如何使用Python SDK与OpenAI Assistants API构建助手?

简介: 在这篇文章中,我们将介绍如何使用Python SDK构建最基本的Assistant,你只需要在代码中添加你自己的OpenAI API密钥即可。

介绍

OpenAI和其Assistant功能旨在为制造商提供一个SDK,用于开发有状态、无提示的Assistant。

其目标是简化虚拟助理的创建。目前,Assistant可以使用三种类型的工具:函数、RAG和代码解释器。

在这篇文章中,我们将介绍如何使用Python SDK构建最基本的Assistant你只需要在代码中添加你自己的OpenAI API密钥即可。

一些注意事项

OpenAI推出的Assistant能力适用于实验、探索和作为短期的解决方案,也可以充当更大的自治代理实例的扩展。然而,为了实现高度可扩展、可检查和可观察的目标,需要更加详细的方法论。

基于安全的角度,一个项目组织不会选择在OpenAI的环境中管理和存储对话记录,而是更更倾向于隐私性强的大语言模型(LLM)。此外,OpenAI Assistant的无状态特性要求开发者手动管理会话状态、工具定义、文档检索和代码执行,这同样造成了一些使用阻碍。

解决上述的挑战,或许可以通过实现LLM和框架的独立性,摆脱对特定框架的依赖。

如果将对话记录管理交给OpenAI,虽然减轻了开发者的管理负担,但每次运行都会被收取整个对话历史记录的token费用,这就给框架内的token使用带来了一定程度的不透明性,容易引起误解。

与Chat Completions API中的完成不同,创建Run是一个异步操作。要想得知Assistant何时完成处理,需要在循环中轮询运行,尽管这种方法会增加复杂性和支出,但优势在于运行时可以查询状态值,可用于管理会话和通知用户。

完整的OpenAI Assistant开发流程

接下来,我们将详细展示使用Python SDK构建Assistant的过程:

!pip install — upgrade openai
!pip show openai | grep Version

AssistantAPI的Python SDK要求OpenAI版本>1.2.3。

Version: 1.3.7

定义API密钥。

import json
import os
def show_json(obj):
    display(json.loads(obj.model_dump_json()))
os.environ['OPENAI_API_KEY'] = str("Your OpenAI API Key goes here.")

代理已创建完成。

# You can also create Assistants directly through the Assistants API
from openai import OpenAI
client = OpenAI()
assistant = client.beta.assistants.create(
    name="History Tutor",
    instructions="You are a personal history tutor. Answer questions briefly, in three sentence or less.",
    model="gpt-4-1106-preview",
)
show_json(assistant)

在输出的JSON中。创建代理后,您将看到ID、型号、Assistant命名和其他详细信息。

{'id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
 'created_at': 1702009585,
 'description': None,
 'file_ids': [],
 'instructions': 'You are a personal history tutor. Answer questions briefly, in three sentence or less.',
 'metadata': {},
 'model': 'gpt-4-1106-preview',
 'name': 'History Tutor',
 'object': 'assistant',
 'tools': []
 }

一旦创建了Assistant,就可以通过OpenAI仪表板看到它,并显示其名称、说明和ID。

无论您是通过仪表板还是使用API创建Assistant,都需要跟踪AssistantI D。

image.png

首先创建线程。

# Creating a new thread:
thread = client.beta.threads.create()
show_json(thread)

下面是输出,包括线程ID等。

{'id': 'thread_1flknQB4C8KH4BDYPWsyl0no',
 'created_at': 1702009588,
 'metadata': {},
 'object': 'thread'}

在这里,一条消息被添加到线程中。

# Now we add a message to the thread:
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="What year was the USA founded?",
)
show_json(message)

结果如下。

在这里,您需要注意的是,即使每次都没有发送会话历史记录,您仍要为每次运行整个会话历史记录支付token费用。

{'id': 'msg_5xOq4FV38cS98ohBpQPbpUiE',
 'assistant_id': None,
 'content': [{'text': {'annotations': [],
    'value': 'What year was the USA founded?'},
   'type': 'text'}],
 'created_at': 1702009591,
 'file_ids': [],
 'metadata': {},
 'object': 'thread.message',
 'role': 'user',
 'run_id': None,
 'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'}

当前面提到定义run时,必须同时指定Assistant和Thread。

run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
)
show_json(run)

再次输出:

{'id': 'run_PnwSECkqDDdjWkQ5P7Hcyfor',
 'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
 'cancelled_at': None,
 'completed_at': None,
 'created_at': 1702009598,
 'expires_at': 1702010198,
 'failed_at': None,
 'file_ids': [],
 'instructions': 'You are a personal history tutor. Answer questions briefly, in three sentence or less.',
 'last_error': None,
 'metadata': {},
 'model': 'gpt-4-1106-preview',
 'object': 'thread.run',
 'required_action': None,
 'started_at': None,
 'status': 'queued',
 'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no',
 'tools': []}

与Chat Completions API中的完成不同,创建Run是一个异步操作。它将立即返回运行元数据,其中包括一个 status初始设置为 queued该值将随着Assistant执行操作而更新。

下面的循环检查while循环中的运行状态,直到运行状态达到完整状态。

import time
def wait_on_run(run, thread):
    while run.status == "queued" or run.status == "in_progress":
        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id,
        )
        time.sleep(0.5)
    return run
run = wait_on_run(run, thread)
show_json(run)

低于运行结果。

{'id': 'run_PnwSECkqDDdjWkQ5P7Hcyfor',
 'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
 'cancelled_at': None,
 'completed_at': 1702009605,
 'created_at': 1702009598,
 'expires_at': None,
 'failed_at': None,
 'file_ids': [],
 'instructions': 'You are a personal history tutor. Answer questions briefly, in three sentence or less.',
 'last_error': None,
 'metadata': {},
 'model': 'gpt-4-1106-preview',
 'object': 'thread.run',
 'required_action': None,
 'started_at': 1702009598,
 'status': 'completed',
 'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no',
 'tools': []}

一旦运行完成,我们就可以列出线程中的所有消息。

# Now that the Run has completed, list the Messages in the Thread to 
# see what got added by the Assistant. 
messages = client.beta.threads.messages.list(thread_id=thread.id)
show_json(messages)

再次输出如下…

{'data': [{'id': 'msg_WhzkHcPnszsmbdrn0H5Ugl7I',
   'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
   'content': [{'text': {'annotations': [],
      'value': 'The United States of America was founded in 1776, with the adoption of the Declaration of Independence on July 4th of that year.'},
     'type': 'text'}],
   'created_at': 1702009604,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'assistant',
   'run_id': 'run_PnwSECkqDDdjWkQ5P7Hcyfor',
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'},
  {'id': 'msg_5xOq4FV38cS98ohBpQPbpUiE',
   'assistant_id': None,
   'content': [{'text': {'annotations': [],
      'value': 'What year was the USA founded?'},
     'type': 'text'}],
   'created_at': 1702009591,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'user',
   'run_id': None,
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'}],
 'object': 'list',
 'first_id': 'msg_WhzkHcPnszsmbdrn0H5Ugl7I',
 'last_id': 'msg_5xOq4FV38cS98ohBpQPbpUiE',
 'has_more': False}

一条消息被附加到线程…

# Create a message to append to our thread
message = client.beta.threads.messages.create(
    thread_id=thread.id, role="user", content="Could you give me a little more detail on this?"
)
# Execute our run
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
)
# Wait for completion
wait_on_run(run, thread)
# Retrieve all the messages added after our last user message
messages = client.beta.threads.messages.list(
    thread_id=thread.id, order="asc", after=message.id
)
show_json(messages)

根据结果,考虑内容价值…

{'data': [{'id': 'msg_oIOfuARjk20zZRn6lAytf0Hz',
   'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
   'content': [{'text': {'annotations': [],
      'value': 'Certainly! The founding of the USA is marked by the Declaration of Independence, which was ratified by the Continental Congress on July 4, 1776. This act declared the thirteen American colonies free and independent states, breaking away from British rule.'},
     'type': 'text'}],
   'created_at': 1702009645,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'assistant',
   'run_id': 'run_9dWR1QFrN983q1AG1cjcQ9Le',
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'}],
 'object': 'list',
 'first_id': 'msg_oIOfuARjk20zZRn6lAytf0Hz',
 'last_id': 'msg_oIOfuARjk20zZRn6lAytf0Hz',
 'has_more': False}

运行完成后,可以在线程中列出消息。

# Now that the Run has completed, list the Messages in the Thread to see 
# what got added by the Assistant.
messages = client.beta.threads.messages.list(thread_id=thread.id)
show_json(messages)

结果再次出现。

{'data': [{'id': 'msg_oIOfuARjk20zZRn6lAytf0Hz',
   'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
   'content': [{'text': {'annotations': [],
      'value': 'Certainly! The founding of the USA is marked by the Declaration of Independence, which was ratified by the Continental Congress on July 4, 1776. This act declared the thirteen American colonies free and independent states, breaking away from British rule.'},
     'type': 'text'}],
   'created_at': 1702009645,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'assistant',
   'run_id': 'run_9dWR1QFrN983q1AG1cjcQ9Le',
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'},
  {'id': 'msg_dDeGGSj4w3CIVRd5hsQpGHmF',
   'assistant_id': None,
   'content': [{'text': {'annotations': [],
      'value': 'Could you give me a little more detail on this?'},
     'type': 'text'}],
   'created_at': 1702009643,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'user',
   'run_id': None,
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'},
  {'id': 'msg_WhzkHcPnszsmbdrn0H5Ugl7I',
   'assistant_id': 'asst_qlaTYRSyl9EWeftjKSskdaco',
   'content': [{'text': {'annotations': [],
      'value': 'The United States of America was founded in 1776, with the adoption of the Declaration of Independence on July 4th of that year.'},
     'type': 'text'}],
   'created_at': 1702009604,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'assistant',
   'run_id': 'run_PnwSECkqDDdjWkQ5P7Hcyfor',
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'},
  {'id': 'msg_5xOq4FV38cS98ohBpQPbpUiE',
   'assistant_id': None,
   'content': [{'text': {'annotations': [],
      'value': 'What year was the USA founded?'},
     'type': 'text'}],
   'created_at': 1702009591,
   'file_ids': [],
   'metadata': {},
   'object': 'thread.message',
   'role': 'user',
   'run_id': None,
   'thread_id': 'thread_1flknQB4C8KH4BDYPWsyl0no'}],
 'object': 'list',
 'first_id': 'msg_oIOfuARjk20zZRn6lAytf0Hz',
 'last_id': 'msg_5xOq4FV38cS98ohBpQPbpUiE',
 'has_more': False}


原文链接:https://cobusgreyling.medium.com/openai-assistants-api-python-sdk-abce8518b645

编译:幂简集成

相关文章
|
6天前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
21 4
|
3天前
|
消息中间件 监控 网络协议
Python中的Socket魔法:如何利用socket模块构建强大的网络通信
本文介绍了Python的`socket`模块,讲解了其基本概念、语法和使用方法。通过简单的TCP服务器和客户端示例,展示了如何创建、绑定、监听、接受连接及发送/接收数据。进一步探讨了多用户聊天室的实现,并介绍了非阻塞IO和多路复用技术以提高并发处理能力。最后,讨论了`socket`模块在现代网络编程中的应用及其与其他通信方式的关系。
|
5天前
|
JSON API 数据格式
使用Python和Flask构建简单的RESTful API
【10月更文挑战第12天】使用Python和Flask构建简单的RESTful API
17 1
|
5天前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
【10月更文挑战第12天】本文介绍了如何使用Python和Flask构建一个简单的RESTful API。首先概述了API的重要性及RESTful API的基本概念,接着详细讲解了Flask框架的特性和安装方法。通过创建一个基本的Flask应用,定义了处理“图书”资源的GET、POST、PUT和DELETE方法的路由,展示了如何处理请求和响应,以及如何进行错误处理。最后,提供了运行和测试API的方法,总结了Flask在构建RESTful API方面的优势。
15 1
|
5天前
|
JSON JavaScript 前端开发
使用JavaScript和Node.js构建简单的RESTful API服务器
【10月更文挑战第12天】使用JavaScript和Node.js构建简单的RESTful API服务器
6 0
|
5天前
|
API 网络架构 Python
使用Python和Flask构建简单的RESTful API
【10月更文挑战第12天】使用Python和Flask构建简单的RESTful API
10 0
|
2天前
|
编解码 监控 API
直播源怎么调用api接口
调用直播源的API接口涉及开通服务、添加域名、获取API密钥、调用API接口、生成推流和拉流地址、配置直播源、开始直播、监控管理及停止直播等步骤。不同云服务平台的具体操作略有差异,但整体流程简单易懂。
|
14天前
|
人工智能 自然语言处理 PyTorch
Text2Video Huggingface Pipeline 文生视频接口和文生视频论文API
文生视频是AI领域热点,很多文生视频的大模型都是基于 Huggingface的 diffusers的text to video的pipeline来开发。国内外也有非常多的优秀产品如Runway AI、Pika AI 、可灵King AI、通义千问、智谱的文生视频模型等等。为了方便调用,这篇博客也尝试了使用 PyPI的text2video的python库的Wrapper类进行调用,下面会给大家介绍一下Huggingface Text to Video Pipeline的调用方式以及使用通用的text2video的python库调用方式。
|
14天前
|
JSON JavaScript API
(API接口系列)商品详情数据封装接口json数据格式分析
在成长的路上,我们都是同行者。这篇关于商品详情API接口的文章,希望能帮助到您。期待与您继续分享更多API接口的知识,请记得关注Anzexi58哦!