콘텐츠로 이동

39. Code Interpreter 응답 처리

실습 데이터

컨테이너

  • 코드 인터프리터를 실행시키는 컴퓨터 환경을 컨테이너라 한다.
  • 코드 인터프리터에서 데이터는 sandbox:/mnt/data/ 안에 저장되며, LLM 모델은 이 경로로 사용자에게 파일을 안내한다.
  • 컨테이너 파일 정보는 annotations 객체 안에 들어있다.
  • 컨테이너 파일은 아래와 같은 형식으로 request 요청을 보내서 받아올 수 있다.
    • url: https://api.openai.com/v1/containers/{container_id}/files/{file_id}/content
    • headers: {"Authorization": "Bearer {OPENAI_API_KEY}"}

test.py

test.py
import requests, os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

input_message = "월별 자전거 사용 비율을 그래프로 그려주세요."

response = client.responses.create(
    input=input_message,
    prompt = { 
        "id": os.environ["PROMPT_ID"]
    }
)

# 응답 텍스트 출력
print(response.output_text)

# annotations (컨테이너 파일) 목록 추출
annotations = []
for output in response.output:
    if output.type == "message":
        for content in output.content:
            content_dict = content.model_dump()
            annotations += content_dict.get('annotations', [])

# annotations (컨테이너 파일) 다운로드
for annotation in annotations:
    filename = annotation['filename']
    container_id = annotation['container_id']
    file_id = annotation['file_id']
    url = f"https://api.openai.com/v1/containers/{container_id}/files/{file_id}/content"
    headers = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}

    # test 폴더에 파일 다운로드
    response = requests.get(url, headers=headers)
    os.makedirs("./test", exist_ok=True)
    with open(f"./test/{filename}", "wb") as f:
        f.write(response.content)
    print("\n[Download]")
    print(f"- from: sandbox:/mnt/data/{filename}")
    print(f"- to: ./test/{filename}")
test.py
import requests, os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

input_message = "월별 자전거 사용 비율을 그래프로 그려주세요."

response = client.responses.create(
    input=input_message,
    stream=True,
    prompt = { 
        "id": os.environ["PROMPT_ID"]
    }
)

# 스트림 응답 처리
annotations = []
for event in response:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        previous_response_id = event.response.id
    elif event.type == "response.output_item.done":
        if event.item.type == "message":
            for content in event.item.content:
                content_dict = content.model_dump()
                annotations += content_dict.get('annotations', [])

# annotations (컨테이너 파일) 다운로드
for annotation in annotations:
    filename = annotation['filename']
    container_id = annotation['container_id']
    file_id = annotation['file_id']
    url = f"https://api.openai.com/v1/containers/{container_id}/files/{file_id}/content"
    headers = {"Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}"}

    # test 폴더에 파일 다운로드
    response = requests.get(url, headers=headers)
    os.makedirs("./test", exist_ok=True)
    with open(f"./test/{filename}", "wb") as f:
        f.write(response.content)
    print("\n[Download]")
    print(f"- from: sandbox:/mnt/data/{filename}")
    print(f"- to: ./test/{filename}")