以编程方式使用文档

本教程逐步讲解如何根据用户反馈优化分类器。分类器非常适合优化,因为通常可以非常简单收集到期望的输出,这使得根据用户反馈创建少量示例变得容易。我们将在本示例中做的就是这个。

目标

在本例中,我们将构建一个基于标题对 GitHub 问题进行分类的机器人。它将接收一个标题并将其分类为多个不同类别之一。然后,我们将开始收集用户反馈,并用它来塑造这个分类器的行为。

入门

首先,我们要设置将所有跟踪发送到特定项目。我们可以通过设置环境变量来实现:

os.environ["LANGSMITH_PROJECT"] = "classifier"

然后我们可以创建我们的初始应用程序。这将是一个接收 GitHub 问题标题并尝试为其添加标签的简单函数。

from langsmith import traceable, Client


client = openai.Client()

available_topics = [
    "bug",
    "improvement",
    "new_feature",
    "documentation",
    "integration",
]

prompt_template = """Classify the type of the issue as one of {topics}.
Issue: {text}"""

@traceable(
    run_type="chain",
    name="Classifier",
)
def topic_classifier(
    topic: str):
    return client.chat.completions.create(
        model="gpt-5.4-mini",
        temperature=0,
        messages=[
            {
                "role": "user",
                "content": prompt_template.format(
                    topics=','.join(available_topics),
                    text=topic,
                )
            }
        ],
    ).choices[0].message.content

然后我们可以开始与它交互。在交互时,我们会提前生成 LangSmith 运行 ID 并将其传递到这个函数中。我们这样做是为了以后可以附加反馈。

以下是我们如何调用这个应用程序:

from langsmith import uuid7

run_id = uuid7()
topic_classifier(
    "fix bug in LCEL",
    langsmith_extra={"run_id": run_id})

以下是之后如何附加反馈。我们可以通过两种形式收集反馈。

首先,我们可以收集"正面"反馈——这是针对模型正确处理的示例。

ls_client = Client()
run_id = uuid7()
topic_classifier(
    "fix bug in LCEL",
    langsmith_extra={"run_id": run_id})
ls_client.create_feedback(
    run_id,
    key="user-score",
    score=1.0,
)

接下来,我们可以专注于收集对应于生成结果的"更正"反馈。在这个示例中,模型会将其分类为 bug,而我实际上希望它被归类为文档。

ls_client = Client()
run_id = uuid7()
topic_classifier(
    "fix bug in documentation",
    langsmith_extra={"run_id": run_id})
ls_client.create_feedback(
    run_id,
    key="correction",
    correction="documentation")

设置自动化

我们现在可以设置自动化规则,将包含某种反馈形式的示例移动到数据集中。我们将设置两个自动化规则,一个用于正面反馈,另一个用于负面反馈。

第一个规则会将所有带有正面反馈的运行记录自动添加到数据集中。这样做的逻辑是,任何带有正面反馈的运行记录都可以作为未来迭代中的良好示例。让我们创建一个名为 classifier-github-issues 的数据集来添加这些数据。

!优化负面反馈

第二个规则会将所有带有修正的运行记录并使用 webhook 将其添加到数据集中。创建此 webhook 时,我们会选择“使用修正”选项。此选项将确保从运行记录创建数据集时,不是使用运行记录的输出作为数据点的标准答案,而是使用修正内容。

!优化正面反馈

更新应用程序

我们现在可以更新代码,下载正在发送运行记录的数据集。下载后,我们可以创建一个包含示例的字符串。然后可以将这个字符串作为提示词的一部分!

### NEW CODE ###
# Initialize the LangSmith Client so we can use to get the dataset
ls_client = Client()

# Create a function that will take in a list of examples and format them into a string
def create_example_string(examples):
    final_strings = []
    for e in examples:
        final_strings.append(f"Input: {e.inputs['topic']}\n> {e.outputs['output']}")
    return "\n\n".join(final_strings)
### NEW CODE ###

client = openai.Client()

available_topics = [
    "bug",
    "improvement",
    "new_feature",
    "documentation",
    "integration",
]

prompt_template = """Classify the type of the issue as one of {topics}.

Here are some examples:
{examples}

Begin!
Issue: {text}
>"""

@traceable(
    run_type="chain",
    name="Classifier",
)
def topic_classifier(
    topic: str):
    # We can now pull down the examples from the dataset
    # We do this inside the function so it always get the most up-to-date examples,
    # But this can be done outside and cached for speed if desired
    examples = list(ls_client.list_examples(dataset_name="classifier-github-issues"))  # <- New Code
    example_string = create_example_string(examples)
    return client.chat.completions.create(
        model="gpt-5.4-mini",
        temperature=0,
        messages=[
            {
                "role": "user",
                "content": prompt_template.format(
                    topics=','.join(available_topics),
                    text=topic,
                    examples=example_string,
                )
            }
        ],
    ).choices[0].message.content

如果现在使用与之前类似的输入运行应用程序,我们会看到它正确地学习到任何与文档相关的内容(即使是一个 bug)都应该被分类为 documentation

ls_client = Client()
run_id = uuid7()
topic_classifier(
    "address bug in documentation",
    langsmith_extra={"run_id": run_id})

示例的语义搜索

我们还可以做的另一件事是只使用语义最相似的示例。当您开始积累大量示例时,这会非常有用。

为了实现这一点,我们可以首先定义一个示例来查找 k 最相似的示例:

def find_similar(examples, topic, k=5):
    inputs = [e.inputs['topic'] for e in examples] + [topic]
    vectors = client.embeddings.create(input=inputs, model="text-embedding-3-small")
    vectors = [e.embedding for e in vectors.data]
    vectors = np.array(vectors)
    args = np.argsort(-vectors.dot(vectors[-1])[:-1])[:5]
    examples = [examples[i] for i in args]
    return examples

然后我们可以在应用程序中使用它

ls_client = Client()

def create_example_string(examples):
    final_strings = []
    for e in examples:
        final_strings.append(f"Input: {e.inputs['topic']}\n> {e.outputs['output']}")
    return "\n\n".join(final_strings)

client = openai.Client()

available_topics = [
    "bug",
    "improvement",
    "new_feature",
    "documentation",
    "integration",
]

prompt_template = """Classify the type of the issue as one of {topics}.

Here are some examples:
{examples}

Begin!
Issue: {text}
>"""

@traceable(
    run_type="chain",
    name="Classifier",
)
def topic_classifier(
    topic: str):
    examples = list(ls_client.list_examples(dataset_name="classifier-github-issues"))
    examples = find_similar(examples, topic)
    example_string = create_example_string(examples)
    return client.chat.completions.create(
        model="gpt-5.4-mini",
        temperature=0,
        messages=[
            {
                "role": "user",
                "content": prompt_template.format(
                    topics=','.join(available_topics),
                    text=topic,
                    examples=example_string,
                )
            }
        ],
    ).choices[0].message.content