Managing Threads and Messages

管理 Afarensis 助手的线索和消息

线索(Threads)和消息(Messages)构成了助手与用户之间的对话会话。Afarensis 助手API通过这两种对象,提供了一种灵活的方式来管理对话的内容和上下文。

创建线索和消息 创建线索:您可以在创建线索时包含一个初始消息列表。这允许您从特定的对话内容开始对话会话。

thread = client.beta.threads.create( messages=[ { "role": "user", "content": "Create 3 data visualizations based on the trends in this file.", "file_ids": [file.id] } ] ) 消息内容:消息可以包含文本、图像或文件。目前,用户创建的消息不支持包含图像文件,但我们计划未来添加此功能。消息的文件大小和令牌限制与助手相同(512 MB 文件大小限制和 2,000,000 令牌限制)。

上下文窗口管理 Afarensis 助手API自动管理上下文窗口,以确保对话的内容不会超出模型的上下文长度限制。当线索中的消息内容超过模型的上下文窗口时,线索将尽可能包含适合上下文窗口的消息,并丢弃最旧的消息。

消息注释 注释类型:消息创建的注释有两种类型:file_citation 和 file_path。file_citation 注释由检索工具创建,定义了对特定文件中特定引文的引用;file_path 注释由代码解释器工具创建,包含对工具生成的文件的引用。

处理注释:当消息对象中存在注释时,您可能会看到文本中的不清楚的模型生成的子字符串。以下是一个示例代码片段,展示了如何用注释中的信息替换这些字符串:

Retrieve the message object

message = client.beta.threads.messages.retrieve( thread_id="...", message_id="..." )

Extract and process message content with annotations

message_content = message.content[0].text annotations = message_content.annotations citations = []

for index, annotation in enumerate(annotations): message_content.value = message_content.value.replace(annotation.text, f' [{index}]') if (file_citation := getattr(annotation, 'file_citation', None)): cited_file = client.files.retrieve(file_citation.file_id) citations.append(f'[{index}] {file_citation.quote} from {cited_file.filename}') elif (file_path := getattr(annotation, 'file_path', None)): cited_file = client.files.retrieve(file_path.file_id) citations.append(f'[{index}] Click to download {cited_file.filename}')

message_content.value += '\n' + '\n'.join(citations)

最后更新于