我有一个文件 txt,构造一个 Ai Agent,它读取这个txt,找到其中所有与汽车相关的名词,然后分别解释这些名词的含义及其功能和使用方法。请使用 LangChain 或 LangGraph 实现。这个过程可以是两个步骤,第一步的prompt是 “找到其中所有与汽车相关的名词”,第二步的prompt是“解释这些名词的含义及其功能和使用方法”。
实现一:
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from langgraph.prebuilt import create_react_agent
import os
import json
# 移除代理设置
os.environ.pop("http_proxy", None)
os.environ.pop("https_proxy", None)
# 初始化 ChatOllama
infer_server_url = "http://localhost:11434"
model_name = "qwen3:1.7b"
model = ChatOllama(
model=model_name,
base_url=infer_server_url,
api_key="none",
temperature=0,
stream=False
)
# 读取文本文件
def read_text_file(file_path: str) -> str:
"""读取指定路径的文本文件内容"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
return f"读取文件失败: {str(e)}"
# 工具 1:提取汽车相关名词
def extract_car_nouns(text: str) -> dict:
"""从文本中提取汽车相关名词"""
prompt = ChatPromptTemplate.from_messages([
("system", """
从以下文本中提取所有与汽车相关的名词,返回 JSON 格式:
{
"nouns": ["名词1", "名词2", ...]
}
确保只提取与汽车直接相关的名词(如部件、系统等),忽略非名词或无关词汇。
文本:{text}
"""),
("human", "{input}")
])
chain = prompt | model | JsonOutputParser()
return chain.invoke({"input": text, "text": text})
# 工具 2:解释名词的含义、功能和使用方法
def explain_car_nouns(nouns: str) -> dict:
"""解释汽车相关名词的含义、功能和使用方法"""
prompt = ChatPromptTemplate.from_messages([
("system", """
对于以下汽车相关名词列表,解释每个名词的含义、功能和使用方法,返回 JSON 格式:
{
"explanations": [
{"noun": "名词1", "meaning": "含义", "function": "功能", "usage": "使用方法"},
...
]
}
名词列表:{nouns}
"""),
("human", "{input}")
])
chain = prompt | model | JsonOutputParser()
return chain.invoke({"input": nouns, "nouns": nouns})
# 创建 ReAct 代理
tools = [extract_car_nouns, explain_car_nouns]
agent = create_react_agent(model=model, tools=tools, debug=True)
# 主逻辑:处理文件并运行代理
def process_car_file(file_path: str):
# 读取文件
text_content = read_text_file(file_path)
if "失败" in text_content:
return {"error": text_content}
# 步骤 1:提取名词
try:
extract_response = extract_car_nouns(text_content)
if not extract_response.get("nouns"):
return {"error": "未提取到汽车相关名词"}
nouns = extract_response["nouns"]
except Exception as e:
return {"error": f"提取名词失败: {str(e)}"}
# 步骤 2:解释名词
try:
explain_response = explain_car_nouns(json.dumps(nouns))
return {
"nouns": nouns,
"explanations": explain_response["explanations"]
}
except Exception as e:
return {"error": f"解释名词失败: {str(e)}"}
# 测试查询
file_path = "car_info.txt"
result = process_car_file(file_path)
# 输出结果
print("代理响应:", json.dumps(result, ensure_ascii=False, indent=2))
实现二:
from langchain.llms import OpenAI # 你可换成其他本地部署的模型接口
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain, SequentialChain
from langchain.text_splitter import CharacterTextSplitter
# 1. 读取txt文件内容
with open("your_file.txt", "r", encoding="utf-8") as f:
file_text = f.read()
# 如文本过长,可拆分;这里只是示例,假设文件不超长
# 如果需要可用下面代码分块
# splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
# chunks = splitter.split_text(file_text)
# file_text = chunks[0] # 这里只用第一块演示
# 2. 定义两个Prompt
# 第一步:找到汽车相关名词
find_nouns_prompt = PromptTemplate(
template=(
"请从以下文本中找出所有与汽车相关的名词,"
"并用逗号分隔列出这些名词:\n"
"文本内容:\n"
"{text}"
),
input_variables=["text"],
)
# 第二步:解释每一个名词
explain_noun_prompt = PromptTemplate(
template=(
"请解释名词 “{noun}” 的含义、功能和使用方法,"
"要求清晰简洁,适合汽车行业相关人员阅读。"
),
input_variables=["noun"],
)
# 3. 初始化LLM,这里用OpenAI接口,你可以换成本地模型
llm = OpenAI(temperature=0) # 或用别的llm,如HuggingFacePipeline包装本地模型
# 4. 定义第一步Chain:找名词
find_nouns_chain = LLMChain(llm=llm, prompt=find_nouns_prompt, output_key="nouns_str")
# 5. 定义第二步Chain:解释单个名词
explain_chain = LLMChain(llm=llm, prompt=explain_noun_prompt, output_key="explanation")
# 6. 执行第一步,获得名词列表
first_step_result = find_nouns_chain.run(text=file_text)
# first_step_result 是字符串,形如 “车轮, 引擎, 方向盘”
nouns = [noun.strip() for noun in first_step_result.split(",") if noun.strip()]
# 7. 对每个名词调用第二步Chain解释,并收集结果
explanations = {}
for noun in nouns:
explanation = explain_chain.run(noun=noun)
explanations[noun] = explanation
# 8. 输出所有解释
for noun, explanation in explanations.items():
print(f"名词: {noun}\n解释: {explanation}\n{'-'*40}")