HIRO GEAR
AI Raspberry Pi OpenAI Python

使用 OpenAI API 时的备忘录笔记

使用 OpenAI API 时的备忘录笔记

记录 OpenAI 的基本用法作为备忘录。

使用 Tools 进行调用的示例

async def process_conversation(*user_input*: str): *# 1. 准备消息* messages = [ { “role”: “system”, “content”: [ {“type”: “input_text”, “text”: “系统提示词”} ] }, { “role”: “user”, “content”: [ {“type”: “input_text”, “text”: user_input} ] } ]
*# 2. 调用 API(使用工具)*
response = client.responses.create(
    *model*=ai_config[“model”],
    *input*=messages,
    *tools*=tools,
    *tool_choice*=”auto”
)

*# 3. 等待完成*
*while* response.status != “completed”:
    *if* response.status == “failed”:
        *return* {“message”: f”错误: {response.error}”}
    *# 等待处理*

*# 4. 处理工具调用*
tool_calls = []
*if* response.output:
    *for* tool_call *in* response.output:
        *if* tool_call.type == “function_call”:
            tool_calls.append(tool_call)

*# 4-1. 工具执行的循环处理*
max_tool_iterations = 7  *# 最大工具执行次数*
tool_iteration_count = 0

*while* tool_iteration_count < max_tool_iterations and tool_calls:
    *# 工具执行处理*
    *for* tool_call *in* tool_calls:
        *# 重复执行检查*

if tool_call.call_id not in processed_tool_calls: # 执行工具并保存结果 # … (详情请参阅“工具执行处理”部分) processed_tool_calls.add(tool_call.call_id)

    tool_iteration_count += 1
   
    *# 检查下一次工具调用*
    *if* tool_iteration_count < max_tool_iterations:
        *# 再次调用 API 以确认工具调用*
        response = client.responses.create(
            *model*=ai_config[“model”],
            *input*=messages,
            *tools*=tools,
            *tool_choice*=”auto”
        )
        *# 等待完成*
        *while* response.status != “completed”:
            *if* response.status == “failed”:
                *return* {“message”: f”错误: {response.error}”}
       
        *# 检查新的工具调用*
        tool_calls = []
        *if* response.output:
            *for* tool_call *in* response.output:
                *if* tool_call.type == “function_call”:
                    tool_calls.append(tool_call)

*# 5. 获取最终回答(不使用工具)*
final_response = client.responses.create(
    *model*=ai_config[“model”],
    *input*=messages,
    *tools*=tools,
    *tool_choice*=”none”
)

*# 6. 处理最终回答*
*while* final_response.status != “completed”:
    *if* final_response.status == “failed”:
        *return* {“message”: f”获取最终回答出错: {final_response.error}”}

*# 将最终回答存入结果*
result = {}
*if* final_response.output and len(final_response.output) > 0:
    result[“message”] = final_response.output[-1].content[0].text
*else*:
    result[“message”] = “未能获取回答”

*return* result</summary>