응답 읽기
Coddy AI Engineering 여정의 코드에서 모델 호출하기 섹션에 포함된 레슨. 22개 중 4번째.
응답은 Message 객체입니다. content는 블록 목록이며, 모든 블록에는 type이 있습니다. "text" 블록은 .text에 답변을 담고 있습니다. 모델이 먼저 생각하는 경우 그 앞에 "thinking" 블록이 오므로 content[0].text를 읽는 코드는 작동하지 않습니다. 대신 해당 type으로 블록을 찾으세요:
for block in response.content:
if block.type == "text":
print(block.text)
print(response.stop_reason)
print(response.usage.input_tokens, response.usage.output_tokens)What is the capital of Canada?에 대해 이것은 답을 출력한 다음 end_turn, 그 다음 15 8을 출력합니다.
stop_reason은 모델이 중단된 이유를 알려줍니다. "end_turn"은 모델이 스스로 완료했음을 의미합니다. usage는 전송한 토큰(input_tokens)과 모델이 작성한 토큰(output_tokens)의 수를 집계하며, 이는 비용 청구의 기준이 됩니다. model과 id는 모델과 요청의 이름을 나타내어 호출을 기록할 때 유용합니다.
챌린지
쉬움응답에서 프로그램에 필요한 모든 내용을 출력하세요. 스타터 코드는 이미 질문을 high effort로 전송하므로 모델이 먼저 생각합니다.
Blocks:와response.content에 있는 모든 블록의 유형을 쉼표와 공백으로 연결하여 출력하세요.Answer:와 텍스트 블록의 텍스트를 출력하세요.Stop:와stop_reason을 출력하세요.usage의 두 카운트를 사용하여Tokens: <input> in, <output> out을 출력하세요.
예를 들어, What is the capital of Egypt? 입력에 대해 프로그램은 다음과 같이 출력합니다:
Blocks: thinking, text
Answer: The capital of Egypt is Cairo.
Stop: end_turn
Tokens: 15 in, 72 out직접 해보기
import coddy_ai as anthropic # 프로덕션 환경에서는: import anthropic
client = anthropic.Anthropic()
question = input()
# 높은 effort 설정은 모델이 답변하기 전에 생각하도록 만듭니다 (다음 장에서 effort를 설명합니다)
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
output_config={"effort": "high"},
messages=[{"role": "user", "content": question}],
)
# 블록 타입, 답변, 중단 이유(stop reason) 및 토큰 수를 출력합니다
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
코드에서 모델 호출하기의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러