HIRO GEAR
AI Raspberry Pi OpenAI Python

Reference Notes from Using the OpenAI API

Reference Notes from Using the OpenAI API

A reference memo documenting basic OpenAI API usage.

Example of Calling with Tools

async def process_conversation(*user_input*: str): *# 1. Prepare messages* messages = [ { “role”: “system”, “content”: [ {“type”: “input_text”, “text”: “System prompt”} ] }, { “role”: “user”, “content”: [ {“type”: “input_text”, “text”: user_input} ] } ]
*# 2. API call (with tools)*
response = client.responses.create(
    *model*=ai_config[“model”],
    *input*=messages,
    *tools*=tools,
    *tool_choice*=”auto”
)

*# 3. Wait until completed*
*while* response.status != “completed”:
    *if* response.status == “failed”:
        *return* {“message”: f”Error: {response.error}”}
    *# Wait handling*

*# 4. Handle tool calls*
tool_calls = []
*if* response.output:
    *for* tool_call *in* response.output:
        *if* tool_call.type == “function_call”:
            tool_calls.append(tool_call)

*# 4-1. Tool execution loop*
max_tool_iterations = 7  *# Maximum number of tool executions*
tool_iteration_count = 0

*while* tool_iteration_count < max_tool_iterations and tool_calls:
    *# Tool execution processing*
    *for* tool_call *in* tool_calls:
        *# Duplicate execution check*

if tool_call.call_id not in processed_tool_calls: # Execute tool and store result # … (See the “Tool Execution Processing” section for details) processed_tool_calls.add(tool_call.call_id)

    tool_iteration_count += 1
   
    *# Check for next tool calls*
    *if* tool_iteration_count < max_tool_iterations:
        *# Call API again to check for tool calls*
        response = client.responses.create(
            *model*=ai_config[“model”],
            *input*=messages,
            *tools*=tools,
            *tool_choice*=”auto”
        )
        *# Wait until completed*
        *while* response.status != “completed”:
            *if* response.status == “failed”:
                *return* {“message”: f”Error: {response.error}”}
       
        *# Check for new tool calls*
        tool_calls = []
        *if* response.output:
            *for* tool_call *in* response.output:
                *if* tool_call.type == “function_call”:
                    tool_calls.append(tool_call)

*# 5. Get final answer (without tools)*
final_response = client.responses.create(
    *model*=ai_config[“model”],
    *input*=messages,
    *tools*=tools,
    *tool_choice*=”none”
)

*# 6. Process final answer*
*while* final_response.status != “completed”:
    *if* final_response.status == “failed”:
        *return* {“message”: f”Error retrieving final answer: {final_response.error}”}

*# Store final answer in result*
result = {}
*if* final_response.output and len(final_response.output) > 0:
    result[“message”] = final_response.output[-1].content[0].text
*else*:
    result[“message”] = “Could not retrieve an answer”

*return* result</summary>