openai assistants api介绍及使用流程见
官方文档:
https://platform.openai.com/docs/assistants/overview
https://platform.openai.com/docs/assistants/how-it-works
中文说明参考CSDN博客:
参照上面编写测试代码如下:
第一步:
实例化一个OpenAI对象
_client = OpenAI(api_key='your open api key')
第二步:
创建assistant。并指定 名字;指令:相当于system prompt,指定assistant性质;使用的工具:这里使用code_interpreter,openai集成的还有Retrievel,集成第三方待研究。
【注意】:在上面文档里都建议使用gpt-4-1106-preview,但使用gpt-4*需要是openai chatgpt的plus subscriber并且加入waitlist,参考The model: `gpt-4` does not exist?怎么办?博主已完美解决! 开通openai-api即可! 官方正规渠道使用chatgpt-4-api!_三十一度
若需要,进入官方页面:https://chat.openai.com/#pricing 升级,每月20$。
笔者开始用gpt-4-1106-preview,提示:
openai.BadRequestError: Error code: 400 - {'error': {'message': "The requested model 'gpt-4-1106-preview' does not exist.", 'type': 'invalid_request_error', 'param': 'model', 'code': 'model_not_found'}}
后改成gpt-3.5-turbo-1106。
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-1106'
)
第三步:
创建thread,相当于assistant和user一个对话的session
thread = _client.beta.threads.create()
第四步:
创建用户的message并且添加到thread里,这里在创建message时指定thread_id就已将其与上thread关联
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?'
# assistant_id=assistant.id
)
第五步:
run执行此会话:通过参数 指定thread_id-相当于指定会话session(从中提取消息),assistant_id-assistant对象。
run = _client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions='Please address the user as Corlos Liu. The user has a premium account'
)
第六步:重要
在获取结果前一定要先检查此执行的状态,执行状态有:enqueque,inprogress,complete等,具体见https://platform.openai.com/docs/assistants/how-it-works说明。一定是complete后,才能去获取结果。
run = _client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
print(run)
第七步:
通过查看上thread里的所有信息获取assistent返回的结果,结果作为assistant的消息也添加到thread中了。
message = _client.beta.threads.messages.list(
thread_id=thread.id
)
print(message)
六七步遇到问题:
run的状态打印:
此时list出的messages也只有用户的问题,并没有assistent的回答。
在run的create后增加代码:
import time
time.sleep(3)
之后执行,同样问题。后来将sleep 3s改成sleep 10s,解决问题:
BTW记录下:
若create run后,retrieve,并打印retrieve的返回对象run1,为“in progress”,sleep 10s后,打印相同对象run1,依然为“in progress”,但list的messages里已经有回答结果了。但若sleep 10s后,重新retrieve,打印新retrieve返回的对象run2,为“complete”。
第八步(可选):
提取打印执行的中间步骤
steps = _client.beta.threads.runs.steps.list(
run_id= run.id,
thread_id= thread.id
)
print(steps)
打印结果: