AI Chat API 연동 안내

우리가 알다시피, 시중의 일부 질의응답 API는 연동이 상대적으로 쉽지 않습니다. 예를 들어 OpenAI의 Chat Completions API에는 messages 필드가 있는데, 연속 대화를 구현하려면 모든 문맥 기록을 전달해야 하며, Token 제한 초과 문제도 처리해야 합니다.

AceDataCloud에서 제공하는 AI 질의응답 API는 위 상황에 맞춰 최적화되어, 질의응답의 효과를 그대로 유지하면서 연속 대화 구현을 캡슐화했습니다. 연동 시 messages 전달을 더 이상 신경 쓸 필요가 없으며, Token 제한 초과 문제도 신경 쓸 필요가 없습니다(API 내부에서 자동으로 처리합니다). 또한 대화 조회, 수정 등의 기능도 제공하여 전체 연동이 크게 간소화됩니다.

이 문서에서는 AI 질의응답 API의 연동 방법을 소개합니다.

신청 절차

AI 질의응답 API를 사용하려면 먼저 Ace Data Cloud 콘솔에서 API Token을 발급받아 준비해 두세요.

아직 로그인하거나 가입하지 않았다면 로그인 페이지로 자동 이동하여 가입 및 로그인하라는 안내가 표시되며, 완료 후 현재 페이지로 자동 복귀합니다.

범용 애플리케이션의 API Key는 계정에 활성화된 서비스에 사용할 수 있으며, 전용 애플리케이션의 Key는 해당 애플리케이션의 서비스 범위에 따라 사용합니다. Key의 권한, 유효기간 및 한도를 확인하고, 애플리케이션 잔액이 이번 요청 비용을 지불하기에 충분한지 확인하세요. 사용 가능한 체험 한도는 계정에 표시된 내용을 기준으로 하며, 잔액이 부족하면 「충전」 버튼을 클릭하면 됩니다.

📘 전체 문서: AI 질의응답 API →

기본 사용법

먼저 기본 사용 방법을 알아보겠습니다. 질문을 입력하고 답변을 받으려면 question 필드를 간단히 전달하고 해당 모델을 지정하기만 하면 됩니다.

예를 들어 “이름이 뭐예요?”라고 질문한다면, 다음과 같이 화면에 해당 내용을 입력할 수 있습니다.

여기서 Request Headers를 설정한 것을 볼 수 있으며, 다음이 포함됩니다.

  • accept: 어떤 형식의 응답 결과를 받을지 지정하며, 여기서는 JSON 형식인 application/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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"
}

이처럼 문맥에 따라 해당 질문에 답변할 수 있습니다.

스트리밍 응답

이 인터페이스는 스트리밍 응답도 지원하며, 이는 웹페이지 연동에 매우 유용하여 웹페이지에서 글자가 하나씩 표시되는 효과를 구현할 수 있습니다.

응답을 스트리밍으로 반환하려면 요청 헤더의 accept 매개변수를 application/x-ndjson으로 변경하면 됩니다.

아래 그림과 같이 변경하되, 스트리밍 응답을 지원하려면 호출 코드도 그에 맞게 변경해야 합니다.

accept를 application/x-ndjson으로 변경하면 API가 해당 JSON 데이터를 한 줄씩 반환하며, 각 줄의 결과를 얻으려면 코드에서 그에 맞는 수정을 해야 합니다.

Python 호출 예제 코드:

import requests

url = "https://api.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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으로 변경하면 답변 효과가 더 좋아집니다.