目錄
(Prompts)提示作用
Prompts 常見操作
基礎 PromptTemplate 使用
Few-shot 提示模板
ChatPromptTemplate (對話提示模板)
(Agents)代理作用
Agents 常見操作
基礎 Agent 使用
自定義工具 Agent
高級應用示例
帶記憶的對話代理
使用本地模型的代理
結構化輸出代理
LangChain框架 Loader 、Vectorstores、Chain 應用-CSDN博客?
另外一篇關于LangChain框架的應用
(Prompts)提示作用
作用:控制大語言模型(LLM)的輸入,通過模板化指令引導模型生成更精準的輸出。
關鍵功能:
-
結構化輸入:將變量動態插入預定義的文本模板(如:
"寫一首關于{topic}的詩"
) -
標準化輸出:通過指令約束模型返回格式(如JSON、列表等)
-
上下文管理:整合示例(Few-shot)、系統消息等提升效果
典型工作流:
提示模板 → 代理接收 → 決策調用工具 → 整合結果 → 返回最終輸出
Prompts 常見操作
基礎 PromptTemplate 使用
from langchain.prompts import PromptTemplate# 創建簡單提示模板
template = "請用{language}寫一個關于{topic}的函數"
prompt = PromptTemplate(input_variables=["language", "topic"],template=template
)# 格式化提示
formatted_prompt = prompt.format(language="Python", topic="快速排序")
print(formatted_prompt)########運行結果############
請用Python寫一個關于快速排序的函數
Few-shot 提示模板
from langchain.prompts import FewShotPromptTemplate, PromptTemplate# 準備示例
examples = [{"input": "高興", "output": "笑容滿面"},{"input": "悲傷", "output": "淚流滿面"}
]# 創建單個示例模板
example_template = """
輸入: {input}
輸出: {output}"""
example_prompt = PromptTemplate(input_variables=["input", "output"],template=example_template
)# 創建Few-shot模板
few_shot_prompt = FewShotPromptTemplate(examples=examples,example_prompt=example_prompt,prefix="將以下情感轉換為成語描述:",suffix="輸入: {adjective}\n輸出:",input_variables=["adjective"]
)print(few_shot_prompt.format(adjective="憤怒"))################運行結果#######################
將以下情感轉換為成語描述:輸入: 高興
輸出: 笑容滿面輸入: 悲傷
輸出: 淚流滿面輸入: 憤怒
輸出:
ChatPromptTemplate (對話提示模板)
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.schema import SystemMessage# 創建聊天提示模板
chat_prompt = ChatPromptTemplate.from_messages([SystemMessage(content="你是一個有幫助的AI助手"),HumanMessagePromptTemplate.from_template("{user_input}")
])formatted_chat = chat_prompt.format_messages(user_input="你好!")
print(formatted_chat)################運行結果########################
[SystemMessage(content='你是一個有幫助的AI助手', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好!', additional_kwargs={}, response_metadata={})]
(Agents)代理作用
作用:讓LLM自主調用工具(Tools)完成復雜任務,實現動態決策和自動化流程。
關鍵功能:
-
工具集成:連接搜索API、計算器、數據庫等外部工具
-
任務編排:自動決定何時調用哪個工具(如先搜索再計算)
-
多步驟推理:通過循環迭代解決需要多步操作的問題
Agents 常見操作
基礎 Agent 使用
from langchain.agents import load_tools, initialize_agent, AgentType
from langchain.llms import Ollama
# 初始化工具和LLM
llm = Ollama(temperature=0,model='qwen')
tools = load_tools(["serpapi","llm-math"], llm=llm)# 創建代理
agent = initialize_agent(tools,llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True
)# 執行任務
agent.run("目前特斯拉的股價是多少?如果是100股,總價值是多少美元?")
自定義工具 Agent
from langchain.agents import tool
from langchain.agents import AgentType, initialize_agent
from langchain.llms import Ollama# 定義自定義工具
@tool
def get_word_length(word: str) -> int:"""返回單詞的長度"""return len(word)# 初始化
llm = Ollama(temperature=0,model='qwen3')
tools = [get_word_length]# 創建代理
agent = initialize_agent(tools,llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True
)# 使用代理
agent.run("單詞'hello'的長度是多少?")##################運行結果#####################
<think>
好的,用戶問的是單詞'hello'的長度是多少。我需要用提供的工具來解決這個問題。首先,我應該調用get_word_length工具,參數是'hello'。然后工具會返回這個單詞的長度。我只需要把結果返回給用戶就可以了。
</think>Thought: 我需要確定單詞'hello'的長度。可以使用get_word_length工具來獲取這個信息。
Action: get_word_length
Action Input: hello
Observation: 5
Thought:<think>
Final Answer: 單詞'hello'的長度是5。
高級應用示例
帶記憶的對話代理
from langchain.agents import AgentType, initialize_agent, load_tools
from langchain.llms import Ollama
from langchain.memory import ConversationBufferMemory# 初始化帶記憶的代理
llm = Ollama(temperature=0,model='qwen')
tools = load_tools(["llm-math"], llm=llm)
memory = ConversationBufferMemory(memory_key="chat_history")agent = initialize_agent(tools,llm,agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,memory=memory,verbose=True
)# 多輪對話
agent.run("3的平方是多少?")
agent.run("再加上7等于多少?")###############運行結果#########################
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [Calculator] ]
Action Input:
Observation: the action to take, should be one of [Calculator] ] is not a valid tool, try one of [Calculator].
Thought:Do I need to use a tool? No
AI: 3的平方是9.
```> Finished chain.> Entering new AgentExecutor chain...
AI: 再加上7等于14.
使用本地模型的代理
from langchain_community.llms import Ollama
from langchain.agents import tool, AgentType
from langchain.agents import initialize_agent# 使用本地Ollama模型
llm = Ollama(model="qwen")# 定義簡單工具
@tool
def word_counter(text: str) -> int:"""計算文本中的單詞數量"""return len(text.split())# 創建代理
agent = initialize_agent([word_counter],llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True
)agent.run("數一數這句話有多少個單詞: 'LangChain是一個強大的AI開發框架'")############運行的結果#################我應該使用word_counter()工具來計算文本中的單詞數量。
Action: word_counter
Action Input: 'LangChain是一個強大的AI開發框架'
Observation: 1
Thought:根據觀察結果,一句話只有一個單詞。Final Answer: 一句話只有一個單詞。
結構化輸出代理
from langchain.llms import Ollama
from langchain_core.tools import tool
from langchain.prompts import PromptTemplate
from langchain.agents import initialize_agent, AgentType
from langchain_community.llms import Ollama
from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from typing import Any, Dict
import json# 1. 定義更簡單的輸出結構
response_schemas = [ResponseSchema(name="summary", description="文章的簡要總結"),ResponseSchema(name="keywords", type="list", description="提取的關鍵詞列表"),ResponseSchema(name="sentiment", description="情感分析結果,只能是positive/neutral/negative")
]# 2. 創建自定義解析器處理Ollama輸出
class OllamaOutputParser(StructuredOutputParser):def parse(self, text: str) -> Dict[str, Any]:try:# 嘗試從輸出中提取JSON部分start = text.find('{')end = text.rfind('}') + 1json_str = text[start:end]return json.loads(json_str)except Exception as e:# 如果解析失敗,返回默認結構return {"summary": "無法生成摘要","keywords": [],"sentiment": "neutral"}output_parser = OllamaOutputParser.from_response_schemas(response_schemas)# 3. 修改提示模板確保JSON格式輸出
ANALYSIS_PROMPT = """請嚴格按以下要求分析文本:
文本:{text}輸出要求:
1. 必須使用JSON格式
2. 包含以下字段:- summary: 50字以內摘要- keywords: 3-5個關鍵詞列表- sentiment: 情感傾向(positive/neutral/negative)返回的JSON必須用```json包裹:
```json
{{你的JSON輸出}}
```"""# 4. 創建工具
@tool
def analyze_text(text: str) -> Dict[str, Any]:"""分析文本并返回結構化結果"""prompt_template = PromptTemplate(template=ANALYSIS_PROMPT,input_variables=["text"],partial_variables={"format_instructions": output_parser.get_format_instructions()})formatted_prompt = prompt_template.format(text=text)llm = Ollama(model="qwen3", temperature=0)result = llm(formatted_prompt)try:return output_parser.parse(result)except Exception as e:print(f"解析失敗: {e}")return {"summary": text[:50] + "...","keywords": ["LangChain"],"sentiment": "neutral"}# 5. 創建并運行代理
agent = initialize_agent([analyze_text],Ollama(model="qwen3", temperature=0),agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True,handle_parsing_errors=True # 關鍵:處理解析錯誤
)text = "LangChain是一個用于開發語言模型應用的框架。它簡化了與LLMs的交互過程,提供了模塊化組件,可以快速開發AI模型應用。"
result = agent.run(f"分析這段文本: {text}")
print(result)################運行結果##################################
<think>
好的,我現在需要分析用戶提供的關于LangChain的文本。首先,用戶的問題是要分析這段文本,所以我要使用analyze_text工具。讓我先仔細閱讀一下文本內容。文本內容是:“LangChain是一個用于開發語言模型應用的框架。它簡化了與LLMs的交互過程,提供了模塊化組件,可以快速開發AI模型應用。” 看起來這段文字在介紹LangChain的功能和優勢。我需要確定用戶的需求是什么,可能他們想了解LangChain的核心功能、它如何簡化開發過程,或者它的主要特點。接下來,我應該調用analyze_text工具來處理這段文本。工具會返回結構化的結果,比如關鍵詞、主題、重要信息等。我需要確保輸入的文本正確無誤,然后等待工具的分析結果。根據返回的觀察結果,我可以提取關鍵點,比如框架的用途、簡化交互的過程、模塊化組件以及快速開發應用的優勢。最后,將這些信息整理成一個清晰、簡潔的最終答案,回答用戶的問題。
</think>Thought: 我需要使用analyze_text工具來分析提供的文本內容。
Action: analyze_text
Action Input: LangChain是一個用于開發語言模型應用的框架。它簡化了與LLMs的交互過程,提供了模塊化組件,可以快速開發AI模型應用。Observation: {'summary': 'LangChain是開發語言模型應用的框架,簡化LLM交互,提供模塊化組件以快速構建AI應用。', 'keywords': ['LangChain', '語言模型應用', 'LLMs交互', '模塊化組件', 'AI應用開發'], 'sentiment': 'neutral'}
Thought:<think>
</think>Final Answer: 這段文本介紹了LangChain是一個用于開發語言模型應用的框架,其核心功能包括簡化與大型語言模型(LLMs)的交互過程,并通過模塊化組件實現快速開發AI模型應用。關鍵詞有LangChain、語言模型應用、LLMs交互、模塊化組件和AI應用開發,整體語氣中性。> Finished chain.
這段文本介紹了LangChain是一個用于開發語言模型應用的框架,其核心功能包括簡化與大型語言模型(LLMs)的交互過程,并通過模塊化組件實現快速開發AI模型應用。關鍵詞有LangChain、語言模型應用、LLMs交互、模塊化組件和AI應用開發,整體語氣中性。
?