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>