跳到主要内容
许多 LLM 应用程序都有类似聊天机器人的界面,用户和 LLM 应用程序之间进行多轮对话。为了跟踪这些对话,您可以使用 LangSmith 中的 Threads 功能。

将跟踪分组到线程中

Thread 是一系列代表单次对话的跟踪。每个响应都表示为一个独立的跟踪,但这些跟踪通过属于同一个线程而相互链接。 要将跟踪关联起来,您需要传入一个特殊的 metadata 键,其值是该线程的唯一标识符。键名应为以下之一:
  • session_id
  • thread_id
  • conversation_id.
该值可以是您想要的任何字符串,但我们建议使用 UUID,例如 f47ac10b-58cc-4372-a567-0e02b2c3d479。有关向跟踪添加元数据的说明,请查阅此指南

示例

此示例演示了如何使用结构化消息格式记录和检索对话历史记录,以维护长时间运行的聊天。
import os
from typing import List, Dict, Any, Optional

import openai
from langsmith import traceable, Client
import langsmith as ls
from langsmith.wrappers import wrap_openai

# Initialize clients
client = wrap_openai(openai.Client())
langsmith_client = Client()

# Configuration
LANGSMITH_PROJECT = "project-with-threads"
THREAD_ID = "thread-id-1"
langsmith_extra={"project_name": LANGSMITH_PROJECT, "metadata":{"session_id": THREAD_ID}}

# gets a history of all LLM calls in the thread to construct conversation history
def get_thread_history(thread_id: str, project_name: str):
    # Filter runs by the specific thread and project
    filter_string = f'and(in(metadata_key, ["session_id","conversation_id","thread_id"]), eq(metadata_value, "{thread_id}"))'
    # Only grab the LLM runs
    runs = [r for r in langsmith_client.list_runs(project_name=project_name, filter=filter_string, run_type="llm")]

    # Sort by start time to get the most recent interaction
    runs = sorted(runs, key=lambda run: run.start_time, reverse=True)

    # Reconstruct the conversation state
    latest_run = runs[0]
    return latest_run.inputs['messages'] + [latest_run.outputs['choices'][0]['message']]


@traceable(name="Chat Bot")
def chat_pipeline(messages: list, get_chat_history: bool = False):
    # Whether to continue an existing thread or start a new one
    if get_chat_history:
        run_tree = ls.get_current_run_tree()
        # Get existing conversation history and append new messages
        history_messages = get_thread_history(run_tree.extra["metadata"]["session_id"], run_tree.session_name)
        all_messages = history_messages + messages
        # Include the complete conversation in the input for tracing
        input_messages = all_messages
    else:
        all_messages = messages
        input_messages = messages

    # Invoke the model
    chat_completion = client.chat.completions.create(
        model="gpt-4o-mini", messages=all_messages
    )

    # Return the complete conversation including input and response
    response_message = chat_completion.choices[0].message
    return {
        "messages": input_messages + [response_message]
    }

# Format message
messages = [
    {
        "content": "Hi, my name is Sally",
        "role": "user"
    }
]
get_chat_history = False

# Call the chat pipeline
result = chat_pipeline(messages, get_chat_history, langsmith_extra=langsmith_extra)
等待几秒钟后,您可以进行以下调用以继续对话。通过传递 get_chat_history=True,/getChatHistory: true,您可以从上次中断的地方继续对话。这意味着 LLM 将接收整个消息历史记录并对其作出响应,而不仅仅是响应最新消息。
# Continue the conversation.
messages = [
    {
        "content": "What is my name?",
        "role": "user"
    }
]
get_chat_history = True

chat_pipeline(messages, get_chat_history, langsmith_extra=langsmith_extra)
继续对话。由于包含过去的聊天记录,LLM 将记住对话内容。
# Continue the conversation.
messages = [
    {
        "content": "What was the first message I sent you?",
        "role": "user"
    }
]
get_chat_history = True

chat_pipeline(messages, get_chat_history, langsmith_extra=langsmith_extra)

查看线程

您可以点击任何项目详情页面中的线程选项卡来查看线程。然后,您将看到一个按最新活动排序的所有线程列表。
LangSmith UI showing the threads table.

查看线程

然后,您可以点击进入某个特定线程。这将打开该特定线程的历史记录。
LangSmith UI showing the threads table.
线程可以通过两种不同的方式查看 您可以使用页面顶部的按钮在两种视图之间切换,也可以使用键盘快捷键 T 在两种视图之间切换。

线程概览

线程概览页面显示了一个类似聊天机器人的用户界面,您可以在其中查看对话每一轮的输入和输出。您可以通过点击配置按钮来配置在概览中显示输入和输出中的哪些字段,或者显示多个字段。 输入和输出的 JSON 路径支持负索引,因此您可以使用 -1 访问数组的最后一个元素。例如,inputs.messages[-1].content 将访问 messages 数组中的最后一条消息。

跟踪视图

这里的跟踪视图与查看单个运行时的跟踪视图类似,不同之处在于您可以轻松访问线程中每一轮的所有运行。

查看反馈

查看线程时,页面顶部会看到一个名为 Feedback 的部分。在这里,您可以查看构成线程的每个运行的反馈。此反馈是聚合的,因此如果您根据相同的标准评估线程的每个运行,您将看到所有运行的平均分数。您还可以在此处查看线程级别反馈

保存线程级别过滤器

与在项目级别保存过滤器类似,您也可以在线程级别保存常用的过滤器。要保存线程表上的过滤器,请使用过滤器按钮设置过滤器,然后点击保存过滤器按钮。 您可以通过分别点击 AnnotateOpen trace,在侧边面板中打开或标注跟踪。
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.