《Agentic Design Patterns》阅读记录

Chapter 1 Prompt Chaining

1
pip install -U langchain langchain-community langchain-deepseek langgraph python-dotenv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
from langchain_deepseek import ChatDeepSeek
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

## 为了更好地安全性,从 .env 文件加载环境变量
from dotenv import load_dotenv
load_dotenv()
## 确保你的 DEEPSEEK_API_KEY 在 .env 文件中正确设置

## 初始化语言模型(此处使用ChatDeepSeek)
llm = ChatDeepSeek(
model="deepseek-chat",
temperature=0
)

## --- 提示词 1: 提取信息 ---
prompt_extract = ChatPromptTemplate.from_template(
"请从以下文本中提取技术规格:\n\n{text_input}"
)

## --- 提示词 2: 转换为 JSON ---
prompt_transform = ChatPromptTemplate.from_template(
"请将以下规格转换为 JSON 对象,使用'cpu'、'memory' 和 'storage' 作为键:\n\n{specifications}"
)

## --- 利用 LCEL 构建处理链
## StrOutputParser 用于将 LLM 的消息输出解析为简单字符串。
extraction_chain = prompt_extract | llm | StrOutputParser()

## 完整的链将提取链的输出传递到转换提示词的 'specifications' 参数中
full_chain = (
{ "specifications": extraction_chain }
| prompt_transform
| llm
| StrOutputParser()
)

## --- 运行链 ---
input_text = "新款笔记本电脑配备了3.5 GHz 八核处理器,16GB 内存和1TB NVMe SSD存储。"

## 使用输入文本字典执行链。
final_result = full_chain.invoke({ "text_input": input_text })

## 输出最终结果
print("\n--- 最终 JSON 输出---")
print(final_result)