langchain学习 01
dotenv
库:可以从.env
文件中加载配置信息。
from dotenv import load_dotenv # 加载函数,之后调用这个函数,即可获取配置环境
.env
里面的内容:
deep_seek_api_key=<api_key>
getpass
库:从终端输入password性质的内容。
import getpass
getpass.getpass('Please input key')
导入模型
使用init_chat_model
方法进行导入,可供选择的模型提供商很多,一般需要再安装模型提供商的相关库。
下面是deepseek模型导入内容:安装模型提供商的库,之后输入相关信息即可。
# pip install -U langchain-deepseek
llm = init_chat_model(model_provider='deepseek',model='deepseek-chat',base_url='https://api.deepseek.com/v1/chat/completions',api_key=os.getenv('deep_seek_api_key'),max_retries=3,
)
用invoke
方法进行询问:
def chat_with_llm(prompt):response = llm.invoke(prompt)return response.content
提示词
使用ChatPromptTemplate
格式化提示词,可以灵活且自定义的提示词配置。
将风格<style>
和文本内容<text>
进行格式化。通过invoke
方法填充提示词模板内容。
from langchain_core.prompts import ChatPromptTemplatesystem_template = "请以{style}风格给出下面文字的描述。"prompt_template = ChatPromptTemplate.from_messages([("system", system_template), ("user", "{text}")]
)
prompt = prompt_template.invoke({"style": "恐怖", "text": "我爱你"})
将填充完成的提示词在大模型中进行查询。
response = llm.invoke(prompt)
print(response.content)
(黑暗中传来指甲刮擦玻璃的声音)"我...爱...你..."(耳语突然变成刺耳的尖叫)"看看我腐烂的心啊!每一块腐肉都在喊着你的名字!"(身后传来湿冷的触感)"让我们永远在一起吧...把你的皮...缝在我的..."
(声音戛然而止,只剩诡异的咀嚼声)
结构化输出
使用with_structured_output
方法进行结构化输出。Pydantic 模型会在运行时验证输入数据是否符合定义的结构和约束。
字段的描述(如 description=“The name of the fruit”)不仅提高了代码的可读性,还可以为 LLM 提供上下文,帮助模型理解每个字段的意义。
from pydantic import BaseModel, Fieldclass Fruit(BaseModel):"""Fruit to tell user."""name: str = Field(description="The name of the fruit")color: str = Field(description="The color of the fruit")sweetness: int = Field(default=5, description="How sweet the fruit is, from 1 to 10")structured_llm = llm.with_structured_output(Fruit)reps = structured_llm.invoke("苹果是怎么样的")
print(reps)
也可以使用类型注解进行字典结构化输出。
Annotated 是 Python 3.9 通过 typing 模块引入的,并在 typing_extensions 中进行了扩展。它用于在类型提示中添加额外的注解或元数据,而不会改变类型的本质。
name: Annotated[str, ..., "The name of the fruit"]
表示name字段是字符串类型,...
表示该字段是必须的,后面的内容是字段描述信息。
from typing_extensions import Annotated, TypedDictclass Fruit(TypedDict):"""Fruit to tell user."""name: Annotated[str, ..., "The name of the fruit"]color: Annotated[str, ..., "The color of the fruit"]sweetness: Annotated[int, 5, "How sweet the fruit is, from 1 to 10"]description: Annotated[str, "A brief description of the fruit"]
structured_llm = llm.with_structured_output(Fruit)
reps = structured_llm.invoke("苹果是怎么样的")
{'name': '苹果', 'color': '红色', 'sweetness': 7, 'description': '苹果是一种常见的水果,口感脆甜,富含维生素和纤维。'}
print(reps)
提示词模板+结构化输出
class Fruit(TypedDict):"""Fruit to tell user."""name: Annotated[str, ..., "水果的名称"]color: Annotated[str, ..., "水果的颜色"]sweetness: Annotated[int, 5, "水果的甜度,从1到10"]description: Annotated[str, "水果的简要描述"]
structured_llm = llm.with_structured_output(Fruit)
system_template = "请以{style}风格给出回答。"prompt_template = ChatPromptTemplate.from_messages([("system", system_template), ("human", "{input}")]
)
prompt_structured_llm = prompt_template | structured_llm
reps = prompt_structured_llm.invoke({"style": "幽默", "input": "苹果是怎么样的?"})
print(reps)
# {'name': '苹果', 'color': '红色', 'sweetness': 8, 'description': '一种常见的水果,脆甜多汁,深受人们喜爱。'}
全部代码:
import getpass
import os
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()if not os.getenv('deep_seek_api_key'):os.environ['deep_seek_api_key'] = getpass.getpass('Enter your DeepSeek API key: ')from langchain.chat_models import init_chat_model# pip install -U langchain-deepseek
llm = init_chat_model(model_provider='deepseek',model='deepseek-chat',base_url='https://api.deepseek.com/v1/chat/completions',api_key=os.getenv('deep_seek_api_key'),max_retries=3,
)
def chat_with_llm(prompt):response = llm.invoke(prompt)return response.content
# answer = chat_with_llm("What is the capital of France?")
# print(f"Answer: {answer}")from langchain_core.prompts import ChatPromptTemplatesystem_template = "请以{style}风格给出回答。"prompt_template = ChatPromptTemplate.from_messages([("system", system_template), ("user", "{text}")]
)
prompt = prompt_template.invoke({"style": "恐怖", "text": "我爱你"})
print(prompt)
# messages=[SystemMessage(content='请以恐怖形式说出下面的中文意义。', additional_kwargs={}, response_metadata={}), HumanMessage(content='我爱你', additional_kwargs={}, response_metadata={})]# response = llm.invoke(prompt)
# print(response.content)
# (黑暗中传来指甲刮擦玻璃的声音)# "我...爱...你..."# (耳语突然变成刺耳的尖叫)# "看看我腐烂的心啊!每一块腐肉都在喊着你的名字!"# (身后传来湿冷的触感)# "让我们永远在一起吧...把你的皮...缝在我的..."
# (声音戛然而止,只剩诡异的咀嚼声)# from pydantic import BaseModel, Field# class Fruit(BaseModel):
# """Fruit to tell user."""# name: str = Field(description="The name of the fruit")
# color: str = Field(description="The color of the fruit")
# sweetness: int = Field(
# default=5, description="How sweet the fruit is, from 1 to 10"
# )# structured_llm = llm.with_structured_output(Fruit)# reps = structured_llm.invoke("苹果是怎么样的")
# print(reps)from typing_extensions import Annotated, TypedDict# TypedDict
# class Fruit(TypedDict):
# """Fruit to tell user."""# name: Annotated[str, ..., "The name of the fruit"]
# color: Annotated[str, ..., "The color of the fruit"]
# sweetness: Annotated[int, 5, "How sweet the fruit is, from 1 to 10"]
# description: Annotated[str, "A brief description of the fruit"]
# structured_llm = llm.with_structured_output(Fruit)
# reps = structured_llm.invoke("苹果是怎么样的")
# {'name': '苹果', 'color': '红色', 'sweetness': 7, 'description': '苹果是一种常见的水果,口感脆甜,富含维生素和纤维。'}
# print(reps)class Fruit(TypedDict):"""Fruit to tell user."""name: Annotated[str, ..., "水果的名称"]color: Annotated[str, ..., "水果的颜色"]sweetness: Annotated[int, 5, "水果的甜度,从1到10"]description: Annotated[str, "水果的简要描述"]
structured_llm = llm.with_structured_output(Fruit)
system_template = "请以{style}风格给出回答。"prompt_template = ChatPromptTemplate.from_messages([("system", system_template), ("human", "{input}")]
)
prompt_structured_llm = prompt_template | structured_llm
reps = prompt_structured_llm.invoke({"style": "幽默", "input": "苹果是怎么样的?"})
print(reps)
# {'name': '苹果', 'color': '红色', 'sweetness': 8, 'description': '一种常见的水果,脆甜多汁,深受人们喜爱。'}