Skip to main content
Open In Colab在 GitHub 上打开

Open In Colab

将文本分类到标签中

标记是指使用如下类标记文档:

  • 情绪
  • 语言
  • 风格(正式、非正式等)
  • 涵盖的主题
  • 政治趋势

图片描述

概述

标记有几个组成部分:

  • function:与提取一样,标记使用函数来指定模型应如何标记文档
  • schema:定义我们想要如何标记文档

快速入门

让我们看一个非常简单的例子,说明如何使用 OpenAI 工具调用 LangChain 进行标记。我们将使用with_structured_outputOpenAI 模型支持的方法。

pip install --upgrade --quiet langchain-core

我们需要加载一个聊天模型

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")

让我们在 schema 中指定一个具有一些属性及其预期类型的 Pydantic 模型。

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field

tagging_prompt = ChatPromptTemplate.from_template(
"""
Extract the desired information from the following passage.

Only extract the properties mentioned in the 'Classification' function.

Passage:
{input}
"""
)


class Classification(BaseModel):
sentiment: str = Field(description="The sentiment of the text")
aggressiveness: int = Field(
description="How aggressive the text is on a scale from 1 to 10"
)
language: str = Field(description="The language the text is written in")


# Structured LLM
structured_llm = llm.with_structured_output(Classification)
inp = "Estoy increiblemente contento de haberte conocido! Creo que seremos muy buenos amigos!"
prompt = tagging_prompt.invoke({"input": inp})
response = structured_llm.invoke(prompt)

response
Classification(sentiment='positive', aggressiveness=1, language='Spanish')

如果我们想要字典输出,我们只需调用.model_dump()

inp = "Estoy muy enojado con vos! Te voy a dar tu merecido!"
prompt = tagging_prompt.invoke({"input": inp})
response = structured_llm.invoke(prompt)

response.model_dump()
{'sentiment': 'enojado', 'aggressiveness': 8, 'language': 'es'}

正如我们在示例中看到的,它正确地解释了我们想要的东西。

结果各不相同,因此我们可能会得到,例如,不同语言的情绪('positive'、'enojado' 等)。

我们将在下一节中了解如何控制这些结果。

更精细的控制

仔细的 schema 定义使我们能够更好地控制模型的输出。

具体来说,我们可以定义:

  • 每个属性的可能值
  • Description 以确保模型理解属性
  • 要返回的必需属性

让我们重新声明我们的 Pydantic 模型,以使用枚举控制前面提到的每个方面:

class Classification(BaseModel):
sentiment: str = Field(..., enum=["happy", "neutral", "sad"])
aggressiveness: int = Field(
...,
description="describes how aggressive the statement is, the higher the number the more aggressive",
enum=[1, 2, 3, 4, 5],
)
language: str = Field(
..., enum=["spanish", "english", "french", "german", "italian"]
)
tagging_prompt = ChatPromptTemplate.from_template(
"""
Extract the desired information from the following passage.

Only extract the properties mentioned in the 'Classification' function.

Passage:
{input}
"""
)

llm = ChatOpenAI(temperature=0, model="gpt-4o-mini").with_structured_output(
Classification
)

现在,答案将以我们预期的方式受到限制!

inp = "Estoy increiblemente contento de haberte conocido! Creo que seremos muy buenos amigos!"
prompt = tagging_prompt.invoke({"input": inp})
llm.invoke(prompt)
Classification(sentiment='positive', aggressiveness=1, language='Spanish')
inp = "Estoy muy enojado con vos! Te voy a dar tu merecido!"
prompt = tagging_prompt.invoke({"input": inp})
llm.invoke(prompt)
Classification(sentiment='enojado', aggressiveness=8, language='es')
inp = "Weather is ok here, I can go outside without much more than a coat"
prompt = tagging_prompt.invoke({"input": inp})
llm.invoke(prompt)
Classification(sentiment='neutral', aggressiveness=1, language='English')

LangSmith 跟踪让我们可以窥探幕后:

图片描述

深入了解

  • 您可以使用元数据标记器文档转换器从 LangChain 中提取元数据Document.
  • 这涵盖了与标记链相同的基本功能,仅适用于 LangChainDocument.