今天openai开了发布会,除了发布新的模型之外,也重点介绍了openai api中的assistant模块,用户可以在api中,通过自定义assistant的方式,实现一些特定的功能。
下面直接给出创建assistant并且调用的代码,穿插着注释讲解。
openai官方链接:https://platform.openai.com/docs/assistants/overview
| 注意:openai的版本需要更新到1.1.x,否则无法使用该功能
from openai import OpenAI
import time
# 构建client
client = OpenAI()
# 构建assistant
# 下面定义的是assistant的系统属性、使用的工具以及使用的模型
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-3.5-turbo"
)
# 创建消息队列处理线程
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?"
)
# 开始处理消息
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions=""
)
result = None
while True:
# 查询消息的状态
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
# 如果状态完成,则获取结果,break
if run.status == "completed":
messages = client.beta.threads.messages.list(thread_id=thread.id)
result = messages.data[0].content[0].text.value
break
# 继续请求
time.sleep(1)
print(f"still waiting for the respone, status: {run.status}")
print(f"resp: {result}")
still waiting for the respone, status: in_progress
...
still waiting for the respone, status: in_progress
resp: The solution to the equation `3x + 11 = 14` is `x = 1`.