C.W.K.
Stream
Lesson 02 of 05 · published

OpenAI Responses API

~22 min · openai, responses-api, tool-calls, input

Level 0호기심 많은 독자
0 XP0/48 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

OpenAI 의 modern API 는 Responses API 야. 옛 Chat Completions endpoint 도 동작하지만, 새 코드는 Responses 겨냥해야 해 — text · tool · vision · structured output 에 걸쳐 더 균일한 모양. 옛 튜토리얼 읽을 때 가장 흔한 실수는 새 endpoint 가 input 을 기대하는데 messages 쓰는 거야.

Flow 는: tools 리스트 빌드 → user 메시지를 input 에 담아 client.responses.create 호출 → response 의 output 순회. Tool call 은 type: "function_call" 인 item 으로 등장 — name, arguments (JSON 문자열 — 진짜 string 이야), call_id 를 들고. Function 실행하고, 결과를 다음 호출의 input 에 같은 call_id 참조하는 function_call_output item 으로 보냄.

OpenAI tool 정의는 tool object 의 top level: type: "function", name, description, parameters. (옛 Chat Completions 는 name/description 을 function 서브 object 안에 nest 했어 — 옛 예제에 헷갈리지 마.) tool_choice"auto", "none", "required" 또는 specific function 명시한 explicit object.

Streaming 은 event 기반: 각 청크에 response.created, response.output_text.delta, response.tool_calls.delta, 마지막 response.completed 같은 type. Tool-call streaming 은 arguments delta 를 string 으로 누적했다가 call 끝나면 JSON parse.

Code

OpenAI Responses 의 full round-trip·python
import json
from openai import OpenAI

client = OpenAI()
tools = [{
    "type": "function",
    "name": "get_weather",
    "description": "Get current weather for a city.",
    "parameters": {
        "type": "object",
        "properties": {"location": {"type": "string"}},
        "required": ["location"],
    },
}]

def get_weather(location: str) -> str:
    return f"68°F and clear in {location}"

# Turn 1: 모델한테 물어봄
input_items = [{"role": "user", "content": "Weather in Seoul?"}]
resp = client.responses.create(model="gpt-4.1", tools=tools, input=input_items)

# Output 의 모든 tool call 뽑음
tool_calls = [item for item in resp.output if item.type == "function_call"]
for tc in tool_calls:
    args = json.loads(tc.arguments)
    result = get_weather(**args)
    input_items.append({"type": "function_call", "call_id": tc.call_id, "name": tc.name, "arguments": tc.arguments})
    input_items.append({"type": "function_call_output", "call_id": tc.call_id, "output": result})

# Turn 2: 결과로 계속
final = client.responses.create(model="gpt-4.1", tools=tools, input=input_items)
print(final.output_text)
Tool call 과 함께 streaming·python
stream = client.responses.create(model="gpt-4.1", tools=tools, input=[...], stream=True)
buf = ""
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.tool_calls.delta":
        # arguments 가 JSON 문자열로 조각조각 도착
        buf += event.delta.arguments
    elif event.type == "response.completed":
        print()

External links

Exercise

위 full two-turn flow 를 gpt-4.1 (또는 읽을 때의 OpenAI flagship) 으로 구현. Streaming response 의 모든 event print. tool_calls.delta event 가 call 발동 전에 누적되는 거 봐. Stream 어디서 실제로 parse 가능한 JSON 이 되는지 봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.