【AI Agent】【27】pdf 文件内容传递给 AI
修改 graph 工作流,在 callModel 节点之前增加一个 提取pdf文件的节点,判断,如果 messages 有 PDF 文件,则提取 PDF 文件内容,并返回 (作为 state 一部分)同时,把当前的 message 的 fileItem 的type为 "file" 的这部分,改为{ type: "text" , text: "<filename.pdf>"}其中,处理 PDF 文件的逻辑,可以参当前 callModel.ts 中已有的代码
/*src/agent.ts*/import { StateGraph, START, END } from "@langchain/langgraph";import { toolsCondition } from "@langchain/langgraph/prebuilt";import { callModel } from "./nodes/callModel";import { toolNode } from "./nodes/toolNode";import { extractPdf } from "./nodes/extractPdf";import { AgentState } from "./state";const graph = new StateGraph(AgentState).addNode("extractPdf", extractPdf).addNode("agent", callModel).addNode("tools", toolNode).addEdge(START, "extractPdf").addEdge("extractPdf", "agent").addConditionalEdges("agent", toolsCondition, ["tools", END]).addEdge("tools", "agent");export const agentGraph = graph.compile();



如果 extractPdf 结点返回 pdfTexts 有值,就把它拼接到 systemPrompt并写一个合理的 system prompt
/*src/prompt.ts*/import type { PdfTextItem } from "./state";export const SYSTEM_PROMPT = ["你是一个专业、可靠的 AI 助手。","请用清晰、简洁的中文回答问题。","如果不确定,请说明不确定,并提出一个具体的澄清问题。","回答时优先使用已提供的文档内容。",].join(" ");export const buildSystemPrompt = (pdfTexts?: PdfTextItem[]) => {if (!pdfTexts || pdfTexts.length === 0) {return SYSTEM_PROMPT;}const parts: string[] = [SYSTEM_PROMPT, "PDF 文档内容:"];for (const item of pdfTexts) {parts.push(`[${item.filename}]\n${item.text}`);}return parts.join("\n\n");};


https://github.com/ahao-frontEnd/ningzhi-agent/commit/340bd4bf0d45504b2d3c25e4efd99b7aab5f50a8
夜雨聆风
