langchain学习 01

dotenv库:可以从.env文件中加载配置信息。

python 复制代码
from dotenv import load_dotenv # 加载函数,之后调用这个函数,即可获取配置环境

.env里面的内容:

.env 复制代码
deep_seek_api_key=<api_key>

getpass库:从终端输入password性质的内容。

python 复制代码
import getpass
getpass.getpass('Please input key')

导入模型

使用init_chat_model方法进行导入,可供选择的模型提供商很多,一般需要再安装模型提供商的相关库。

下面是deepseek模型导入内容:安装模型提供商的库,之后输入相关信息即可。

python 复制代码
# 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方法进行询问:

python 复制代码
def chat_with_llm(prompt):
    response = llm.invoke(prompt)
    return response.content

提示词

使用ChatPromptTemplate格式化提示词,可以灵活且自定义的提示词配置。

将风格<style>和文本内容<text>进行格式化。通过invoke方法填充提示词模板内容。

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

system_template = "请以{style}风格给出下面文字的描述。"

prompt_template = ChatPromptTemplate.from_messages(
    [("system", system_template), ("user", "{text}")]
)
prompt = prompt_template.invoke({"style": "恐怖", "text": "我爱你"})

将填充完成的提示词在大模型中进行查询。

python 复制代码
response = llm.invoke(prompt)
print(response.content)
(黑暗中传来指甲刮擦玻璃的声音)

"我...爱...你..."

(耳语突然变成刺耳的尖叫)

"看看我腐烂的心啊!每一块腐肉都在喊着你的名字!"

(身后传来湿冷的触感)

"让我们永远在一起吧...把你的皮...缝在我的..."
(声音戛然而止,只剩诡异的咀嚼声)

结构化输出

使用with_structured_output方法进行结构化输出。Pydantic 模型会在运行时验证输入数据是否符合定义的结构和约束。

字段的描述(如 description="The name of the fruit")不仅提高了代码的可读性,还可以为 LLM 提供上下文,帮助模型理解每个字段的意义。

python 复制代码
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)

也可以使用类型注解进行字典结构化输出。

Annotated 是 Python 3.9 通过 typing 模块引入的,并在 typing_extensions 中进行了扩展。它用于在类型提示中添加额外的注解或元数据,而不会改变类型的本质。

name: Annotated[str, ..., "The name of the fruit"]表示name字段是字符串类型,...表示该字段是必须的,后面的内容是字段描述信息。

python 复制代码
from typing_extensions import Annotated, 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)

提示词模板+结构化输出

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

全部代码:

python 复制代码
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 ChatPromptTemplate

system_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': '一种常见的水果,脆甜多汁,深受人们喜爱。'}
相关推荐
FreakStudio10 分钟前
不用费劲编译ulab了!纯Mpy矩阵micronumpy库,单片机直接跑
python·嵌入式·边缘计算·电子diy
似水明俊德1 小时前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
adore.9682 小时前
3.18 复试学习
学习
留白_2 小时前
MySQL学习(9)——索引
学习
请你喝好果汁6412 小时前
生信学习笔记:ArchR 处理小麦单细胞 ATAC-seq 中的细胞数差异与 Embedding 报错调试
学习
清水白石0082 小时前
Free-Threaded Python 实战指南:机遇、风险与 PoC 验证方案
java·python·算法
勇往直前plus2 小时前
大模型开发手记(八):LangChain Agent格式化输出
langchain
飞Link3 小时前
具身智能核心架构之 Python 行为树 (py_trees) 深度剖析与实战
开发语言·人工智能·python·架构
jinanwuhuaguo3 小时前
OpenClaw、飞书、Claude Code、Codex:四维AI生态体系的深度解构与颗粒化对比分析
大数据·人工智能·学习·飞书·openclaw
桃气媛媛3 小时前
Pycharm常用快捷键
python·pycharm