채팅 완성 보내기

채팅 완성 보내기 (Chat Completions)

채팅 모델에 질문을 던지는 가장 기본적인 방법을 함께 볼게요. Together AI의 chat.completions.create는 한 번의 질문, 여러 턴을 오가는 대화, 그리고 시스템 프롬프트까지 모두 지원해요. 여기서 다루는 메시지 배열과 역할(role) 개념만 알면 대부분의 채팅 애플리케이션을 만들 수 있어요.

출처: 공식문서 - Send chat completions

단일 질문 보내기

chat.completions.create를 호출하면 채팅 모델에 질문 하나를 보낼 수 있어요. 첫 번째 인자로 모델명을, 그리고 messages 배열로 대화 내용을 넘겨주면 돼요.

from together import Together

client = Together()

response = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    reasoning={"enabled": False},
    messages=[
        {
            "role": "user",
            "content": "What are some fun things to do in New York?",
        }
    ],
)

print(response.choices[0].message.content)
curl -X POST "https://api.together.ai/v1/chat/completions" \
     -H "Authorization: Bearer ***" \
     -H "Content-Type: application/json" \
     -d '{
    	"model": "Qwen/Qwen3.5-9B",
        "reasoning": {"enabled": false},
    	"messages": [
    		{"role": "user", "content": "What are some fun things to do in New York?"}
    	]
     }'

messages 배열의 각 항목은 content(내용)와 role(역할)로 이루어져 있어요. 예시에서 roleuser인데, 이 역할은 '이 메시지가 사용자 시스템의 최종 사용자, 예컨대 채팅 앱을 쓰는 고객에게서 온 것이다'라고 모델에게 알려주는 역할이에요.

여러 턴 대화 (Multi-turn)

채팅 모델에 보내는 질문은 매번 독립적이라, 모델이 이전 질문을 자동으로 기억하지 않아요. 그래서 assistant 역할이 필요한데요. 이 역할에 이전 질문들에 모델이 어떻게 답했는지 대화 이력을 담아두면, 채팅봇이나 오래 이어지는 대화를 구현할 수 있어요.

새 질문을 보낼 때 이전 메시지들을 messages 배열에 함께 넣어주면 되고, 사용자가 준 메시지에는 user, 모델이 한 답변에는 assistant 역할을 붙여주세요.

from together import Together

client = Together()

response = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    reasoning={"enabled": False},
    messages=[
        {
            "role": "user",
            "content": "What are some fun things to do in New York?",
        },
        {
            "role": "assistant",
            "content": "You could go to the Empire State Building!",
        },
        {"role": "user", "content": "That sounds fun! Where is it?"},
    ],
)

print(response.choices[0].message.content)

과거 메시지를 어디에 어떻게 저장할지는 전적으로 여러분의 몫이에요. Together AI는 그 저장 방식을 강제하지 않아요.

시스템 프롬프트 추가하기

user 메시지 하나만으로 모델에 질문할 수도 있지만, 보통은 모델이 어떤 태도로 답해야 하는지 알려주는 시스템 프롬프트를 함께 주는 편이에요. 예를 들어 여행 채팅봇을 만든다면, 모델에게 '친절한 여행 가이드처럼 행동해'라고 지시할 수 있어요.

시스템 프롬프트는 system 역할을 가진 첫 메시지로 전달해요.

from together import Together

client = Together()

response = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    reasoning={"enabled": False},
    messages=[
        {"role": "system", "content": "You are a helpful travel guide."},
        {
            "role": "user",
            "content": "What are some fun things to do in New York?",
        },
    ],
)

print(response.choices[0].message.content)

응답 스트리밍하기

모델이 전체 답변을 완성할 때까지 기다리는 대신, 생성되는 조각을 그때그때 받아볼 수 있어요. stream 옵션을 True로 설정하면 모델이 응답을 만드는 동안에도 애플리케이션이 부분 결과를 보여줄 수 있어요.

from together import Together

client = Together()

stream = client.chat.completions.create(
    model="Qwen/Qwen3.5-9B",
    reasoning={"enabled": False},
    messages=[
        {
            "role": "user",
            "content": "What are some fun things to do in New York?",
        }
    ],
    stream=True,
)

for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="", flush=True)

스트리밍 응답은 Server-Sent Events 형태로 JSON으로 인코딩된 페이로드가 이어져 전달돼요. 각 chunk는 data: {...} 형식으로 오고, choices[0].delta.content에 방금 생성된 텍스트 조각이 담겨요.

파이썬에서 비동기 요청 병렬 실행

기본적으로 파이썬 Together 클라이언트는 요청을 동기적으로 실행해서, 서로 독립적인 요청이라도 순서대로 처리돼요. 여러 독립 호출을 병렬로 돌리고 싶다면 파이썬 라이브러리의 AsyncTogether 모듈을 사용하면 돼요.

import os, asyncio
from together import AsyncTogether

async_client = AsyncTogether()
messages = [
    "What are the top things to do in San Francisco?",
    "What country is Paris in?",
]


async def async_chat_completion(messages):
    async_client = AsyncTogether(api_key=os.environ.get("TOGETHER_API_KEY"))
    tasks = [
        async_client.chat.completions.create(
            model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
            messages=[{"role": "user", "content": message}],
        )
        for message in messages
    ]
    responses = await asyncio.gather(*tasks)

    for response in responses:
        print(response.choices[0].message.content)


asyncio.run(async_chat_completion(messages))

asyncio.gather(*tasks)가 여러 호출을 동시에 실행해서, 개별적으로 순차 호출할 때보다 전체 대기 시간을 크게 줄여줘요.

더 알아보기 (Learn more)