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': '一种常见的水果,脆甜多汁,深受人们喜爱。'}
相关推荐
SSH_55232 小时前
【大模型】情绪对话模型项目研发
人工智能·python·语言模型
love530love2 小时前
【笔记】在 MSYS2(MINGW64)中安装 python-maturin 的记录
运维·开发语言·人工智能·windows·笔记·python
拾忆-eleven3 小时前
NLP学习路线图(十四):词袋模型(Bag of Words)
人工智能·学习·自然语言处理·nlp
拾忆-eleven5 小时前
NLP学习路线图(十五):TF-IDF(词频-逆文档频率)
人工智能·学习·自然语言处理·nlp
G皮T5 小时前
【Python Cookbook】文件与 IO(二)
python·i/o·io·文件·gzip·stringio·bytesio
封奚泽优6 小时前
使用Python绘制节日祝福——以端午节和儿童节为例
人工智能·python·深度学习
viperrrrrrrrrr76 小时前
大数据学习(125)-hive数据分析
大数据·学习
干啥都是小小白6 小时前
话题通信之python实现
python·机器人·ros
仟濹6 小时前
「数据采集与网络爬虫(使用Python工具)」【数据分析全栈攻略:爬虫+处理+可视化+报告】
大数据·爬虫·python·数据挖掘·数据分析
水银嘻嘻7 小时前
03 APP 自动化-定位元素工具&元素定位
python·appium·自动化