from openai import OpenAI
openai_client = OpenAI()
MODEL = "gpt-4o-mini"
def run_turn(history, user_message):
history.append({"role": "user", "content": user_message})
with weave.start_turn(user_message=user_message, model=MODEL):
# LLM Call 1: 모델이 도구를 사용하기로 결정할 수 있습니다.
with weave.start_llm(model=MODEL, provider_name="openai") as llm:
resp = openai_client.chat.completions.create(
model=MODEL, messages=history, tools=[wikipedia_tool_schema],
)
msg = resp.choices[0].message
llm.output(msg.content or "")
llm.usage = weave.Usage(
input_tokens=resp.usage.prompt_tokens,
output_tokens=resp.usage.completion_tokens,
)
history.append(msg.model_dump(exclude_none=True))
# 도구가 요청되지 않은 경우, 첫 번째 LLM 응답이 최종 답변입니다.
if not msg.tool_calls:
return msg.content
# 요청된 각 도구 Call을 실행합니다.
for tc in msg.tool_calls:
with weave.start_tool(
name=tc.function.name,
arguments=tc.function.arguments,
tool_call_id=tc.id,
) as tool:
tool.result = wikipedia_search(**json.loads(tc.function.arguments))
history.append({
"role": "tool",
"tool_call_id": tc.id,
"content": tool.result,
})
# LLM Call 2: 최종 답변을 종합합니다.
with weave.start_llm(model=MODEL, provider_name="openai") as llm:
resp = openai_client.chat.completions.create(model=MODEL, messages=history)
msg = resp.choices[0].message
llm.output(msg.content)
llm.usage = weave.Usage(
input_tokens=resp.usage.prompt_tokens,
output_tokens=resp.usage.completion_tokens,
)
history.append({"role": "assistant", "content": msg.content})
return msg.content
with weave.start_conversation(agent_name="research-bot") as conversation:
history = []
for question in [
"Who founded Anthropic?",
"What is Claude (the AI assistant)?",
"Summarize what we discussed in one sentence.",
]:
print(f"USER: {question}")
print(f"AGENT: {run_turn(history, question)}\n")