将文本分类为标签
Tagging 意味着用如下类别标记文档
- 情感
- 语言
- 风格(正式、非正式等)
- 涵盖的主题
- 政治倾向
概述
Tagging 有几个组件
快速入门
让我们看一个非常简单的示例,了解如何在 LangChain 中使用 OpenAI 工具调用进行 tagging。我们将使用 OpenAI 模型支持的 with_structured_output
方法。
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")
让我们在我们的模式中指定一个 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")
# LLM
llm = ChatOpenAI(temperature=0, model="gpt-4o-mini").with_structured_output(
Classification
)
API 参考:ChatPromptTemplate | ChatOpenAI
inp = "Estoy increiblemente contento de haberte conocido! Creo que seremos muy buenos amigos!"
prompt = tagging_prompt.invoke({"input": inp})
response = 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 = llm.invoke(prompt)
response.model_dump()
{'sentiment': 'enojado', 'aggressiveness': 8, 'language': 'es'}
正如我们在示例中看到的,它正确地解释了我们想要的内容。
结果各不相同,因此我们可能会获得不同语言的情感(“positive”、“enojado”等)。
我们将在下一节中看到如何控制这些结果。
更精细的控制
仔细的模式定义使我们能够更好地控制模型的输出。
具体来说,我们可以定义
- 每个属性的可能值
- 描述以确保模型理解该属性
- 要返回的必需属性
让我们重新声明我们的 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
中提取元数据。 - 这涵盖了与 tagging 链相同的基本功能,只是应用于 LangChain
Document
。