Assistants API란?
어시스턴트 api를 사용하면, 기존에 사용하던 langchain등을 사용하여 묶인 여러 기능들을 openAI의 서비스만으로 쉽게 구현할 수 있습니다. 또한 GPT4 유료모델에서 제공하는 코드 인터프리터, 검색및 함수 등의 툴들을 지원하기때문에 높은 수준에서의 API개발이 가능합니다. 또한 “스레드”라는 무한한 메세지 스토리지를 제공하므로 더이상 conversation 메모리를 따로 구현할 필요가 없습니다.
- 코드인터프리터, 웹 검색, 함수도출 등의 툴 제공
- 사용자와 대화를 시작하면 스레드를 생성, 이 스레드는 무한한 메세지 추가가 가능
Assistants API 사용해보기
어시스턴트 생성
어시스턴트는 다음과 같은 파라미터를 가질 수 있습니다.
- 지침(instructions) : pre-prompt라고 생각하면됩니다. 어시스턴트 모델이 어떻게 행동하거나 반응해야할지에 대해 정의합니다.
- 모델(model) : 사용할 모델(파인튜닝 포함)을 지정합니다. gpt3.5, gpt4.0 등을 지정할 수도 있습니다.
- 도구(tools) : 확장할 툴을 선택합니다. 코드 인터프리터, 외부검색, 함수 등을 지정할 수 있습니다.
assistant = client.beta.assistants.create(
name="Math Tutor",
instructions="You are a personal math tutor. Write and run code to answer math questions.",
tools=[{"type": "code_interpreter"}],
model="gpt-4-1106-preview"
)
스레드 생성
스레드는 대화를 나타냅니다. 사용자가 대화를 시작하면 스레드가 생성됩니다.
- 스레드에는 크기제한이 없으므로 원하는 만큼 메세지를 추가할 수 있습니다.
- Assistant는 테스트를 토큰화 하는 부분에 대해 알아서 확인하기때문에 이는 고려대상이 아닙니다.
- 복잡성을 처리할 필요가 없어지며 컨텍스트를 어시스턴트가 직접 관리합니다.
thread = client.beta.threads.create()
메세지 추가
메세지에는 텍스트유형과 사용자가 업로드하는 파일 유형을 추가할 수 있습니다.
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
)
메세지를 확인해보면 다음과 같은 데이터를 얻을 수 있습니다.
{
"object": "list",
"data": [
{
"created_at": 1696995451,
"id": "msg_abc123",
"object": "thread.message",
"thread_id": "thread_abc123",
"role": "user",
"content": [{
"type": "text",
"text": {
"value": "I need to solve the equation `3x + 11 = 14`. Can you help me?",
"annotations": []
}
}],
...
어시스턴트 실행
사용자 메세지에 응답을 하려는경우 run을 생성하면 됩니다.
- 이를 통해 어시스턴트는 스레드를 읽고 툴을 호출할지, 아니면 그냥 모델을 사용할지에 대해 알아서 판단한 후에 쿼리에 가장 잘 응답할 방법을 선택하여 결정합니다.
- 또한 모델의 컨텍스트에 포함될 이전 메세지를 스레드에서 찾아 알아서 결정합니다.
- 이 방식은 ChatGPT에서의 내용을 기반으로 최적화되어있습니다.
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="Please address the user as Jane Doe. The user has a premium account."
)
실행상태 확인
이 run은 기본적으로 queued 상태로 전환되고, 주기적으로 상태를 검색하여 completed 되었는지 확인 할 수 있습니다.
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
응답 표시
실행이 완료되면, 어이스턴트가 스레드에 추가한 메세지를 나열할 수 있습니다.
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
해당 스레드의 메세지를 확인해보면 다음과 같은 메세지들을 포함하는것을 확인할 수 있습니다.
ROLE CONTENT
user | I need to solve the equation 3x + 11 = 14. Can you help me? |
assistant | Certainly, Jane Doe. To solve the equation (3x + 11 = 14) for (x), you'll want to isolate (x) on one side of the equation. Here's how you can do that: |
- Subtract 11 from both sides of the equation to get (3x = 3).
- Then, divide both sides by 3 to solve for (x).Let me calculate the value of (x) for you. | | assistant | The solution to the equation (3x + 11 = 14) is (x = 1). |