The chatbot code fails because the API call is within the for loop
Hi!
Thank you for posting. Are you referring to Lesson 3: Chatbot Example
I just tested it and it is working as expected
Try again this Lesson 3! If you have further question, please add more details such as screenshot of the error, links to the course, that would be really appreciate to give you better support!
I think this is due to fact the Claude (at least this version) is allowed to return 1 or more tool calls per turn and this is not handled in the Chatbot Example.
If Claude (the assistant) responds like text, tool_use
then the Chatbot Example works. Note text and tool_use refer to the each content’s type in response.content.
If Claude responds like text, tool_use, tool_use, tool_use, tool_use
then the Chatbot Example doesn’t work as is.
Here is an untested version from Copilot:
def process_query(query):
messages = [{'role': 'user', 'content': query}]
response = client.messages.create(
max_tokens=2024,
model='claude-3-7-sonnet-20250219',
tools=tools,
messages=messages
)
while True:
# Collect all tool_use blocks
tool_calls = [c for c in response.content if c.type == "tool_use"]
# If no tool calls, print final text and exit
if not tool_calls:
for c in response.content:
if c.type == "text":
print(c.text)
break
# Otherwise, process ALL tool calls
tool_results = []
for call in tool_calls:
print(f"Calling tool {call.name} with args {call.input}")
result = execute_tool(call.name, call.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": call.id,
"content": result
})
# Add assistant message containing all tool_use blocks
messages.append({
"role": "assistant",
"content": response.content
})
# Add user message containing ALL tool_results
messages.append({
"role": "user",
"content": tool_results
})
# Ask the model what to do next
response = client.messages.create(
max_tokens=2024,
model='claude-3-7-sonnet-20250219',
tools=tools,
messages=messages
)
