본문 바로가기
C.W.K.
Stream
Lesson 03 of 07 · published

Request 직접 만들기 — wire 의 contract

~22 min · request-body, headers, auth

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

request body 를 직접 만들면 API가 실제로 받는 구조가 보여. model, input, tools, instructions, max_output_tokens, stream, tool_choice 의 정확한 이름과 값을 application 이 모두 책임져. SDK helper가 넣어주던 기본값도 없어.

422 오류는 실제 JSON에서 찾아

SDK 호출은 되지만 직접 만든 호출이 422를 낸다면 field 이름 오타나 tool의 type: "function" 누락을 먼저 확인해. 실제 body를 한 번 만들어보면 SDK 뒤에도 단순한 요청 규칙이 있다는 게 보여.

header 도 직접 구성해

Authorization: Bearer <key>, Content-Type: application/json, beta 기능의 OpenAI-Beta: ...를 필요에 따라 넣어. 조직과 project 범위를 지정하려면 OpenAI-Organization, OpenAI-Project도 직접 보내야 해.

streaming 에는 Accept 를 밝혀

streaming 호출에는 Accept: text/event-stream 을 넣어. 일부 proxy 는 이 header가 없으면 SSE를 모았다가 한꺼번에 보내 streaming 효과를 없앨 수 있어.

Code

Hand-rolled chat.completions request·python
import os, httpx

url = "https://api.openai.com/v1/chat/completions"
headers = {
    "Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
    "Content-Type": "application/json",
}
body = {
    "model": "gpt-4.1",
    "messages": [
        {"role": "developer", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"},
    ],
    "temperature": 0.7,
    "max_completion_tokens": 1024,
}

async with httpx.AsyncClient(timeout=httpx.Timeout(connect=10, read=120, write=10, pool=5)) as client:
    resp = await client.post(url, headers=headers, json=body)
    resp.raise_for_status()
    data = resp.json()
    print(data["choices"][0]["message"]["content"])
Hand-rolled responses request with tools·python
url = "https://api.openai.com/v1/responses"
body = {
    "model": "gpt-4.1",
    "input": "Tell me a three sentence bedtime story about a unicorn.",
}
resp = await client.post(url, headers=headers, json=body)
data = resp.json()
# Access output text from response structure
print(data["output"][0]["content"][0]["text"])

External links

Exercise

model gpt-4.1, instructions='You are concise', input='What is 2+2?', max_output_tokens=50 을 담은 body를 직접 만들고 httpx로 POST /v1/responses에 보내. response.output_text가 '4'인지 확인해.

Progress

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

댓글 0

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

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