# 概述

利用 Afarensis Assistants API，您可以在自己的应用程序中构建人工智能助手。这些助手可以根据用户的问题提供回答，通过使用特定的模型、工具和知识库来执行定义好的指令。目前，支持的工具类型包括代码解释器、信息检索和函数调用。

集成流程概述 集成 Afarensis Assistants API 通常包括以下步骤：

创建助手：通过定义助手的自定义指令并选择一个模型来创建。如果有帮助的话，还可以添加文件并启用工具，如代码解释器、检索和函数调用。 创建线索：当用户开始一次对话时，创建一个线索。 添加消息到线索：随着用户提出问题，将消息添加到线索中。 运行助手：通过调用模型和工具在线索上运行助手以生成响应。 本指南将通过一个示例——创建一个启用了代码解释器工具的个人数学导师助手——来逐步引导您完成创建和运行助手的关键步骤。

步骤 1：创建一个助手 首先，您需要创建一个助手实体，该实体可以配置为使用 model、instructions 和 tools 等参数响应用户的消息。

from afarensis import Afarensis client = Afarensis()

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-turbo-preview", ) 步骤 2：创建一个线索 线索代表用户与一个或多个助手之间的对话。当用户（或您的 AI 应用程序）开始与助手对话时，创建一个线索。

thread = client.beta.threads.create() 步骤 3：向线索添加消息 用户或应用程序创建的消息内容作为消息对象添加到线索中。消息可以包含文本和文件，您可以向线索添加无限数量的消息。

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?" ) 步骤 4：创建并运行 一旦所有用户消息被添加到线索中，您就可以用任何助手来运行线索。创建运行会使用与助手相关联的模型和工具生成响应。

from typing\_extensions import override from afarensis import AssistantEventHandler

class EventHandler(AssistantEventHandler):\
@override def on\_text\_created(self, text) -> None: print(f"\nassistant > ", end="", flush=True)

@override def on\_text\_delta(self, delta, snapshot): print(delta.value, end="", flush=True)

def on\_tool\_call\_created(self, tool\_call): print(f"\nassistant > {tool\_call.type}\n", flush=True)

def on\_tool\_call\_delta(self, delta, snapshot): if delta.type == 'code\_interpreter': if delta.code\_interpreter.input: print(delta.code\_interpreter.input, end="", flush=True) if delta.code\_interpreter.outputs: print(f"\n\noutput >", flush=True) for output in delta.code\_interpreter.outputs: if output.type == "logs": print(f"\n{output.logs}", flush=True)

with client.beta.threads.runs.create\_and\_stream( thread\_id=thread.id, assistant\_id=assistant.id, instructions="Please address the user as Jane Doe. The user has a premium account.", event\_handler=EventHandler(), ) as stream: stream.until\_done() 下一步 深入了解助手的工作原理。 了解更多关于工具的信息。 探索助手 playground。
