멋사 부트캠프

[멋사 부트캠프] Day04 - Gpt API

sagecode 2025. 6. 20. 20:18

WebSocket을 활용한 GPT AI 챗봇 만들기

1. WebSocket으로 client가 메시지를 전송한다.

2. 서버가 클라이언트에게서 받은 메시지를 GPT api로 http전송한다.

3. chat gpt는 받은 메시지를 바탕으로 응답을 WebSocket에게 다시 전송한다.

4.서버가 gpt API 응답으로 받은 메시지를 WebSocket 통신으로 클라이언트에게 메시지 전송한다.

 

OpenAI api 플랫폼에 가면 이런 명령어가 존재한다.

 

OpenAI의 API에 요청을 보내서 GPT 모델로부터 응답(Response)을 받아오는 것이다.

 

http://api.openai.com/v1/response -> url

-H(헤더) Content-Type: application/json -> 보내는 데이터의 type이 json 형식

-H(헤더) Authorization: Bearer $OPENAI_API_KEY -> API 키로 인증 (환경 변수 OPENAI_API_KEY에 키가 저장되어 있어야 함)

-d (데이터) {json형식의 모델 버전과 채팅 내용}

 

응답 예시

{
    "id": "resp_6854d1de45808198a979d1b29fa2250e0eda0c42f3ed927e",
    "object": "response",
    "created_at": 1750389214,
    "status": "completed",
    "background": false,
    "error": null,
    "incomplete_details": null,
    "instructions": null,
    "max_output_tokens": null,
    "max_tool_calls": null,
    "model": "gpt-4.1-2025-04-14",
    "output": [
        {
            "id": "msg_6854d1dea5e481989aa8b9a45d26e2780eda0c42f3ed927e",
            "type": "message",
            "status": "completed",
            "content": [
                {
                    "type": "output_text",
                    "annotations": [],
                    "text": "Under a sky full of twinkling stars, a gentle unicorn named Luna tiptoed through a moonlit meadow, weaving dreams of kindness for all the children fast asleep."
                }
            ],
            "role": "assistant"
        }
    ],
    "parallel_tool_calls": true,
    "previous_response_id": null,
    "reasoning": {
        "effort": null,
        "summary": null
    },
    "service_tier": "default",
    "store": true,
    "temperature": 1.0,
    "text": {
        "format": {
            "type": "text"
        }
    },
    "tool_choice": "auto",
    "tools": [],
    "top_p": 1.0,
    "truncation": "disabled",
    "usage": {
        "input_tokens": 18,
        "input_tokens_details": {
            "cached_tokens": 0
        },
        "output_tokens": 36,
        "output_tokens_details": {
            "reasoning_tokens": 0
        },
        "total_tokens": 54
    },
    "user": null,
    "metadata": {}
}