当前位置: 首页 > news >正文

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': '一种常见的水果,脆甜多汁,深受人们喜爱。'}

相关文章:

  • [网页五子棋][对战模块]实现游戏房间页面,服务器开发(创建落子请求/响应对象)
  • bert扩充或者缩小词表
  • 【NLP 78、手搓Transformer模型结构及实战】
  • 中文NLP with fastai - Fastai Part4
  • G25-05-31Rust开源项目日报 Top10
  • 基于热力学熵增原理的EM-GAM
  • Baklib企业CMS全流程管控与智能协作
  • 尚硅谷redis7 99 springboot整合redis之连接集群
  • 知识管理五强对比:Baklib高效突围
  • Python简易音乐播放器开发教程
  • LeetCode 算 法 实 战 - - - 移 除 链 表 元 素、反 转 链 表
  • 双目相机深度的误差分析(基线长度和相机焦距的选择)
  • Linux系统编程之共享内存
  • 【设计模式-4.5】行为型——迭代器模式
  • KWIC—Implicit Invocation
  • 【代码坏味道】变更阻碍者Change Preventers
  • Tomcat的整体架构及其设计精髓
  • MAC软件游戏打开提示已损坏
  • 通义灵码深度实战测评:从零构建智能家居控制中枢,体验AI编程新范式
  • azure web app创建分步指南系列之二
  • 建设植绒衣架网站/优化模型数学建模
  • 广州网站建设公司兴田德润可以不/网站软件下载大全
  • 中国万网域名注册价格/引擎优化搜索
  • 视觉品牌网站建设/优化外包服务公司
  • 网站域名怎么做变更/前端seo是什么意思
  • 中国最大的做网站的公司/软文营销代理