AI Raspberry Pi OpenAI Python OpenAI APIを使った時に備忘録メモ 公開日:2025年8月31日 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 ← 前の記事 自分専用AIエージェント作成計画 次の記事 → T-CROSSにてEPC(警告灯)が表示された 記事一覧へ戻る