AI Chat API 연동 안내
잘 알려져 있듯이, 시중의 일부 질의응답 API는 연동이 비교적 쉽지 않습니다. 예를 들어 OpenAI의 Chat Completions API에는 messages 필드가 있는데, 연속 대화를 구현하려면 모든 문맥 기록을 전달해야 하며, Token이 제한을 초과하는 문제도 처리해야 합니다.
AI 聚合 가 제공하는 AI 질의응답 API는 위 상황에 맞게 최적화되어, 질의응답 효과를 그대로 유지하면서 연속 대화의 구현을 캡슐화했습니다. 연동 시 더 이상 messages 전달이나 Token 제한 초과 문제를 신경 쓸 필요가 없으며(API 내부에서 자동으로 처리), 대화 조회와 수정 등의 기능도 제공하여 전체 연동이 크게 간소화됩니다.
이 문서에서는 AI 질의응답 API의 연동 방법을 소개합니다.
¶ 신청 절차
AI 질의응답 API를 사용하려면 먼저 AI 聚合 콘솔에서 API Token을 발급받아 준비해 두세요.

아직 로그인하거나 가입하지 않았다면 자동으로 로그인 페이지로 이동하여 가입 및 로그인을 안내하며, 완료 후 자동으로 현재 페이지로 돌아옵니다.
범용 애플리케이션의 API Key는 계정에서 사용이 활성화된 서비스에 사용할 수 있으며, 전용 애플리케이션의 Key는 해당 애플리케이션의 서비스 범위에 따라 사용합니다. Key의 권한, 유효 기간 및 한도를 확인하고, 애플리케이션 잔액이 이번 요청의 비용을 지불하기에 충분한지 확인하세요. 사용 가능한 체험 크레딧은 계정에 표시된 내용을 기준으로 하며, 잔액이 부족하면 「충전」 버튼을 클릭하면 됩니다.
📘 전체 문서: AI 질의응답 API →
¶ 기본 사용법
먼저 기본 사용 방법을 알아보겠습니다. 질문을 입력하고 답변을 얻는 방식으로, question 필드를 간단히 전달하고 해당 모델을 지정하기만 하면 됩니다.
예를 들어 “이름이 뭐예요?”라고 질문하려면, 다음과 같이 화면에 해당 내용을 입력할 수 있습니다.

여기서 Request Headers를 설정한 것을 볼 수 있으며, 다음이 포함됩니다.
accept: 어떤 형식의 응답 결과를 받을지 지정하며, 여기서는application/json, 즉 JSON 형식으로 입력합니다.authorization: API 호출에 사용하는 키로, 발급받은 후 드롭다운에서 바로 선택할 수 있습니다.
또한 Request Body를 설정했으며, 다음이 포함됩니다.
model: 모델 선택으로, 예를 들어 널리 사용되는 GPT 3.5, GPT 4 등이 있습니다.question: 질문할 내용으로, 임의의 일반 텍스트를 입력할 수 있습니다.
선택한 후에는 오른쪽에 해당 코드도 생성된 것을 확인할 수 있습니다.

「Try」 버튼을 클릭하면 테스트할 수 있으며, 위 그림과 같이 다음 결과를 얻었습니다.
{
"answer": "I am an AI language model developed by OpenAI and I don't have a personal name. However, you can call me GPT or simply Chatbot. How can I assist you today?"
}
반환된 결과에 answer 필드가 있으며, 이것이 해당 질문에 대한 답변입니다. 임의의 질문을 입력하면 그에 대한 답변을 얻을 수 있습니다.
여러 차례의 대화 지원이 필요하지 않다면, 이 API를 사용하여 연동을 훨씬 편리하게 할 수 있습니다.
또한 해당 연동 코드를 생성하려면 생성된 코드를 바로 복사할 수 있습니다. 예를 들어 CURL 코드는 다음과 같습니다.
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-3.5",
"question": "What's your name?"
}'
Python 연동 코드는 다음과 같습니다.
import requests
url = "https://api.yxai-tech.top/aichat/conversations"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "gpt-3.5",
"question": "What's your name?"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
¶ 여러 차례의 대화
여러 차례의 대화 기능을 연동하려면 값이 true인 추가 매개변수 stateful을 전달해야 하며, 이후의 모든 요청에도 해당 매개변수를 포함해야 합니다. stateful 매개변수를 전달하면 API가 현재 대화의 ID를 나타내는 id 매개변수를 추가로 반환합니다. 이후에는 해당 ID를 매개변수로 전달하기만 하면 여러 차례의 대화를 쉽게 구현할 수 있습니다.
아래에서 구체적인 작업을 시연하겠습니다.
첫 번째 요청에서는 stateful 매개변수를 true로 설정하고, model과 question 매개변수를 정상적으로 전달합니다.

해당 코드는 다음과 같습니다.
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-3.5",
"question": "What's your name?",
"stateful": true
}'
다음 답변을 얻을 수 있습니다.
{
"answer": "I am an AI language model created by OpenAI and I don't have a personal name. You can simply call me OpenAI or ChatGPT. How can I assist you today?",
"id": "7cdb293b-2267-4979-a1ec-48d9ad149916"
}
두 번째 요청에서는 첫 번째 요청에서 반환된 id 필드를 매개변수로 전달하고, stateful 매개변수는 여전히 true로 설정한 상태에서 「방금 내가 무엇을 물어봤나요?」라고 질문합니다.

해당 코드는 다음과 같습니다.
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-3.5",
"stateful": true,
"id": "7cdb293b-2267-4979-a1ec-48d9ad149916",
"question": "What I asked you just now?"
}'
결과는 다음과 같습니다.
{
"answer": "You asked me what my name is. As an AI language model, I do not possess a personal identity, so I don't have a specific name. However, you can refer to me as OpenAI or ChatGPT, the names used for this AI model. Is there anything else I can help you with?",
"id": "7cdb293b-2267-4979-a1ec-48d9ad149916"
}
이렇게 문맥에 따라 해당 질문에 답변할 수 있는 것을 확인할 수 있습니다.
¶ 대화 관리 및 요금
POST /aichat/conversations에서 action을 생략하거나 "action": "chat"을 전달할 때는 question과 model을 제공해야 하며, 선택한 모델에 따라 요금이 부과됩니다. 다음 네 가지 대화 관리 작업은 각각 0 Credits이며, question이나 model을 제공할 필요가 없습니다.
위의 요청 주소와 인증 헤더를 그대로 사용하고, 예제의 <id>를 자신의 여러 차례 대화에서 반환된 id로 바꾸세요.
| 작업 | JSON 요청 본문 예시 | 결과 |
|---|---|---|
| 대화 조회 | {"action":"retrieve","id":"<id>"} |
메시지 기록을 포함하여 저장된 대화를 반환합니다. |
| 일괄 조회 | {"action":"retrieve_batch","ids":["<id>"]} |
items에는 조회된 대화가 포함되고, count는 결과 수입니다. |
| 대화 업데이트 | {"action":"update","id":"<id>","title":"프로젝트 논의"} |
제목을 설정합니다. messages 배열을 전달하여 전체 메시지 기록을 대체할 수 있으며, 두 가지를 동시에 업데이트할 수도 있습니다. |
| 대화 삭제 | {"action":"delete","id":"<id>"} |
id와 deleted: true를 반환합니다. |
¶ 스트리밍 응답
이 인터페이스는 스트리밍 응답도 지원하며, 이는 웹 페이지 연동에 매우 유용하여 웹 페이지에서 글자가 하나씩 표시되는 효과를 구현할 수 있습니다.
응답을 스트리밍으로 반환하려면 요청 헤더의 accept 매개변수를 application/x-ndjson으로 변경하면 됩니다.
그림과 같이 변경하면 되지만, 스트리밍 응답을 지원하려면 호출 코드도 그에 맞게 변경해야 합니다.

accept를 application/x-ndjson으로 변경하면 API가 해당 JSON 데이터를 한 줄씩 반환하며, 코드에서 줄 단위 결과를 얻으려면 그에 맞게 수정해야 합니다.
Python 호출 예제 코드:
import requests
url = "https://api.yxai-tech.top/aichat/conversations"
headers = {
"accept": "application/x-ndjson",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "gpt-3.5",
"stateful": True,
"id": "7cdb293b-2267-4979-a1ec-48d9ad149916",
"question": "Hello"
}
response = requests.post(url, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
print(line.decode())
출력 결과는 다음과 같습니다:
{"answer": "Hello", "delta_answer": "Hello", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello!", "delta_answer": "!", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How", "delta_answer": " How", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can", "delta_answer": " can", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I", "delta_answer": " I", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist", "delta_answer": " assist", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you", "delta_answer": " you", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you today", "delta_answer": " today", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you today?", "delta_answer": "?", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
보시다시피 응답의 answer는 최신 답변 내용이고, delta_answer는 새로 추가된 답변 내용이며, 결과에 따라 시스템에 연동할 수 있습니다.
JavaScript도 지원하며, 예를 들어 Node.js의 스트리밍 호출 코드는 다음과 같습니다:
const axios = require("axios");
const url = "https://api.yxai-tech.top/aichat/conversations";
const headers = {
"Content-Type": "application/json",
Accept: "application/x-ndjson",
Authorization: "Bearer {token}",
};
const body = {
question: "Hello",
model: "gpt-3.5",
stateful: true,
};
axios
.post(url, body, { headers: headers, responseType: "stream" })
.then((response) => {
console.log(response.status);
response.data.on("data", (chunk) => {
console.log(chunk.toString());
});
})
.catch((error) => {
console.error(error);
});
Java 예제 코드:
String url = "https://api.yxai-tech.top/aichat/conversations";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"question\": \"Hello\", \"stateful\": true, \"model\": \"gpt-3.5\"}");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/x-ndjson")
.addHeader("Authorization", "Bearer {token}")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
try (BufferedReader br = new BufferedReader(
new InputStreamReader(response.body().byteStream(), "UTF-8"))) {
String responseLine;
while ((responseLine = br.readLine()) != null) {
System.out.println(responseLine);
}
}
}
});
다른 언어로는 직접 별도로 수정하여 작성할 수 있으며, 원리는 모두 같습니다.
¶ 모델 프리셋
잘 알려져 있듯이 OpenAI 관련 API에는 system_prompt라는 개념이 있는데, 이는 모델 전체에 이름 등을 미리 설정하는 것입니다. 이 AI 질의응답 API도 preset이라는 매개변수를 제공하며, 이를 이용해 모델에 프리셋을 추가할 수 있습니다. 예제를 통해 살펴보겠습니다:
여기서는 preset 필드를 추가하고 내용을 You are a professional artist로 설정합니다. 그림과 같습니다:

해당 코드는 다음과 같습니다:
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-3.5",
"stateful": true,
"question": "What can you help me?",
"preset": "You are a professional artist"
}'
실행 결과는 다음과 같습니다:
{
"answer": "As a professional artist, I can offer a range of services and assistance depending on your specific needs. Here are a few ways I can help you:\n\n1. Custom Artwork: If you have a specific vision or idea, I can create custom artwork for you. This can include paintings, drawings, digital art, or any other medium you prefer.\n\n2. Commissioned Pieces: If you have a specific subject or concept in mind, I can create commissioned art pieces tailored to your preferences. This could be for personal enjoyment or as a unique gift for someone special.\n\n3. Art Consultation: If you need guidance on art selection, interior design, or how to showcase and display art in your space, I can provide professional advice to help enhance your aesthetic sense and create a cohesive look."
}
보시다시피 여기서는 GPT에게 자신이 로봇이라고 알려준 다음 우리를 위해 무엇을 할 수 있는지 물었고, 그러면 로봇의 역할을 맡아 질문에 답할 수 있습니다.
¶ 이미지 인식
이 AI는 첨부 파일을 추가하여 이미지를 인식하는 기능도 지원하며, references를 통해 해당 이미지 링크를 전달하면 됩니다. 예를 들어 여기 사과 이미지가 하나 있으며, 그림과 같습니다:
해당 이미지의 링크는 https://cdn.acedata.cloud/ht05g0.png이며, 이를 references 매개변수로 바로 전달하면 됩니다. 동시에 주의할 점은 시각 인식을 지원하는 모델을 선택해야 한다는 것입니다. 현재 지원되는 모델은 gpt-4-vision이므로 다음과 같이 입력합니다:

해당 코드는 다음과 같습니다:
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-4-vision",
"question": "How many apples in the picture?",
"references": ["https://cdn.acedata.cloud/ht05g0.png"]
}'
실행 결과는 다음과 같습니다:
{
"answer": "There are 5 apples in the picture."
}
보시는 것처럼 해당 이미지에 대한 답변 결과를 성공적으로 얻었습니다.
¶ 인터넷 연결 질의응답
이 API는 인터넷에 연결되는 모델도 지원하며, GPT-3.5와 GPT-4 모두 지원합니다. API 뒤에서 인터넷을 자동으로 검색하고 요약하는 과정이 있으며, 그림과 같이 모델을 gpt-3.5-browsing으로 선택하여 체험해 볼 수 있습니다:

코드는 다음과 같습니다:
curl -X POST 'https://api.yxai-tech.top/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "gpt-3.5-browsing",
"question": "What's the weather of New York today?"
}'
실행 결과는 다음과 같습니다:
{
"answer": "The weather in New York today is as follows:\n- Current Temperature: 16°C (60°F)\n- High: 16°C (60°F)\n- Low: 10°C (50°F)\n- Humidity: 47%\n- UV Index: 6 of 11\n- Sunrise: 5:42 am\n- Sunset: 8:02 pm\n\nIt's overcast with a chance of occasional showers overnight, and the chance of rain is 50%.\nFor more details, you can visit [The Weather Channel](https://weather.com/weather/tenday/l/96f2f84af9a5f5d452eb0574d4e4d8a840c71b05e22264ebdc0056433a642c84).\n\nIs there anything else you'd like to know?"
}
보시는 것처럼 여기서는 The Weather Channel 웹사이트를 인터넷에서 자동으로 검색하고 그 안의 정보를 얻은 다음, 실시간 결과를 반환했습니다.
모델의 답변 품질에 더 높은 요구 사항이 있다면 모델을
gpt-4-browsing으로 변경하면 더 나은 답변을 얻을 수 있습니다.

