基于openai api构建assistant

主题

今天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`.
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值