OpenAI 답변 vs. Assistant

OpenAI 답변

• OpenAI Text generation

• 그 중에서도 Chat Completion API

• chat.completions.create로 구성

• system / user / assistant

• JSON API

Assistant API 답변

• OpenAI Assistant API

• 1강에서 Playground에서 만든 Assistant에게 메세지를 실행

[Image: image]

일반 Chat Completion vs. Assistant API

Chat Completion API | Assistant API

주어진 Input에 대한 Output | 주어진 Input에 대한 Output

채팅 내용에 대해 저장 X | 채팅 내용 저장 O (threads)

RAG, 기타 함수 직접 구현
(직접 Prompt에 넣기) | RAG, Code Interpreter 등 특수 기능 사용 가능

Function Calling을 구현 | 사전에 지정한 Assistant

Chat Completion API + FastAPI

OpenAI Chat completion API를 FastAPI에 붙이기

• 서버 띄우기 : python app.py

• http://localhost:8000

• http://localhost:8000/docs (Test Page or Swagger UI)

# pip install fastapi uvicorn openai python-dotenv
from fastapi import FastAPI
from pydantic import BaseModel
import openai
import os
from dotenv import load_dotenv
from fastapi.middleware.cors import CORSMiddleware

load_dotenv()  # Load .env file if present

openai.api_key = os.getenv("OPENAI_API_KEY")

app = FastAPI()

# Allow CORS for local dev
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, restrict this to your domain
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class MessageRequest(BaseModel):
    message: str

@app.post("/chat")
async def chat_endpoint(req: MessageRequest):
    # Call the OpenAI ChatCompletion endpoint
    response = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": req.message},
        ],
        # temperature=0.7,
    )
    # Extract assistant message
    assistant_reply = response.choices[0].message.content
    return {"reply": assistant_reply}

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

예시 Assistant: 논문봇

• 아래 논문을 받아서 설명해주는 Assistant를 만들어봅시다.

• “RetroLLM: Empowering Large Language Models to Retrieve Fine-grained Evidence within Generation" // 2024.12.17

• https://platform.openai.com/playground/assistants

• Assistant ID 확인하기 (ex. asst_tc4AhtsAjNJnRtpJmy1gjJOE)

• 새로 API를 (/assistant) URL에 붙이기

• OpenAI Beta Assistant API로 새 Assistant 논문봇을 지정

@app.post("/assistant")
async def assistant_endpoint(req: MessageRequest):
    # assistant = openai.beta.assistants.create(
    #     name="My Assistant",
    #     instructions="You are a helpful assistant that answers user queries.",
    #     model="gpt-4o",
    # )
    # 우리는 앞서 만든 assistant를 사용합니다.
    assistant = await openai.beta.assistants.retrieve("asst_tc4AhtsAjNJnRtpJmy1gjJOE")

		## 신규 "스레드" 생성 + 질문 던지기
    # Create a new thread with the user's message
    thread = await openai.beta.threads.create(
        messages=[{"role": "user", "content": req.message}]
    )

    # Create a run and poll until completion using the helper method
    run = await openai.beta.threads.runs.create_and_poll(
        thread_id=thread.id, assistant_id=assistant.id
    )

    # Get messages for this specific run
    messages = list(
        await openai.beta.threads.messages.list(thread_id=thread.id, run_id=run.id)
    )

    # Process the first message's content and annotations
    message_content = messages[0][1][0].content[0].text
    annotations = message_content.annotations
    citations = []

    # Replace annotations with citation markers and build citations list
    for index, annotation in enumerate(annotations):
        message_content.value = message_content.value.replace(
            annotation.text, f"[{index}]"
        )
        if file_citation := getattr(annotation, "file_citation", None):
            cited_file = await openai.files.retrieve(file_citation.file_id)
            citations.append(f"[{index}] {cited_file.filename}")

    # Combine message content with citations if any exist
    assistant_reply = message_content.value
    if citations:
        assistant_reply += "\n\n" + "\n".join(citations)

    return {"reply": assistant_reply}

Fast API + Fro

Native Chat (/chat)

• 일반 GPT4o-mini

• RetroLLM 인지 못함

Assistant Chat(/assistant)

• 논문봇 Assistant

• RetroLLM에 대해 잘 답변

• <b>RAG!</b>

Fly.io

FLyctl 설치 : Install flyctl

[Image: image]

Fly.io에 FastAPI 배포하기

• fly 명령어로 실행

• Backend 폴더에서 fly launch 명령어 실행

• web UI 뜨면

• 아래에 “Confirm Settings”

• 배포 ‘준비’ 끝

• fly deploy 명령어로 배포

Fly.io에 환경 변수 설정하기(OpenAI API Key 등)

• secrets 탭에서 확인

• OPENAI_API_KEY 저장

• ⭐fly deploy로 재배포 필수 !⭐

배포된 서버 테스트

기존 : `localhost` (개인)

신규 : ~~.fly.dev (누구나 접속 가능)

백엔드 / 프론트엔드 연동하기 (API 서버 URL 변경)

JS 코드 폴더에 .env.development와 .env.production 생성

• .env.development에 아래와 같이 설정

-
API_ENDPOINT=http://localhost:8000

• .env.prodution에 아래와 같이 설정

• `API_ENDPOINT=https://개인별URL나온것.fly.dev

`(개개인의 Fly.io에서 나온 URL로 설정하기)

Frontend 재배포

• GH-pages: npm run build && npm run deploy

• Vercel: 단순 git push → 자동 배포