Code fix for Error Code 400 in labs

Continuing the discussion from Still facing the error code: 400 in L3:

I debugged the code by printing the messages, and discovered that a single tool_use message was being incorrectly passed multiple times to the model, which expects a 1:1 correspondence + matching IDs between assistant/tool_use and user/tool_result messages. (I would speculate that this represents a change in the API.)

So inside the chatbot code, the last line in the following code block is where the problem lives:

def process_query(query):
    messages = [{'role':'user', 'content':query}]
    response = anthropic.messages.create(max_tokens = 2024,
                                  #model = 'claude-3-7-sonnet-20250219', #deprecated model
                                  model = 'claude-sonnet-4-6',
                                  tools = tools,
                                  messages = messages)
    process_query = True
    while process_query:
        assistant_content = []
        for content in response.content:
            if content.type =='text':
                print(content.text)
                assistant_content.append(content)
                if(len(response.content)==1):
                    process_query= False
            elif content.type == 'tool_use':
                assistant_content.append(content)
                messages.append({'role':'assistant', 'content':assistant_content}) # <<--ERROR!

Here’s what worked for me:

def process_query(query):
    messages = [{'role':'user', 'content':query}]
    response = anthropic.messages.create(max_tokens = 2024,
                                  #model = 'claude-3-7-sonnet-20250219', #deprecated model
                                  model = 'claude-sonnet-4-6',
                                  tools = tools,
                                  messages = messages)
    process_query = True
    while process_query:
        # assistant_content = [] # No need to pass multiple assistant messages
        for content in response.content:
            if content.type =='text':
                print(content.text)
                # assistant_content.append(content)
                if(len(response.content)==1):
                    process_query= False
            elif content.type == 'tool_use':
                assistant_content.append(content)
                # Just pass the most recent assistant message
                messages.append({'role':'assistant', 'content':[content]})
4 Likes

Thank you @Chris_Falter ! I think it was soon to be updated. Let me check with the team in the meanwhile your solutions looks great! Thanks for sharing!

-- Lesly, DLAI

1 Like

Thanks for reporting and thanks for the patience. The updates have been pushed to the platform.

Note: the def process_query(query) was refactored. Thanks everyone for their suggestions!

Happy Learning!

Lesly - DLAI