基于LlamaIndex工作流与A2A协议的文件对话代理示例

该示例用LlamaIndex Workflows结合Google Gemini构建可上传并解析文件的对话代理,通过A2A协议对外提供标准化交互,支持多轮对话、流式状态更新和行内引用,并说明会话内存与解析额度的限制。

# LlamaIndex 文件聊天工作流程与A2A协议 这个样本显示一个对话代理商 [LlamaIndex 工作流程](https://docs.llamaindex.ai/en/stable/understanding/workflows/) ,并通过 A2A 协议曝光。它显示文件上传和解析,对话互动,支持多回合对话,流出响应/更新,以及线内引用。 ## 如何运作 这个代理使用与Google双子座的LlamaIndex Workflows提供对话代理,可以上传文件,解析文件,并解答有关内容的问题. A2A协议可以实现与代理的标准化互动,允许客户端发送请求并接受实时更新. ```mermaid sequenceDiagram participant Client as A2A Client participant Server as A2A Server participant Workflow as ParseAndChat Workflow participant Services as External APIs Client->>Server: Send message (with or without attachment) Server->>Workflow: Forward as InputEvent alt Has Attachment Workflow-->>Server: Stream LogEvent "Parsing document..." Server-->>Client: Stream status update Workflow->>Services: Parse document Workflow-->>Server: Stream LogEvent "Document parsed successfully" Server-->>Client: Stream status update end Workflow-->>Server: Stream LogEvent about chat processing Server-->>Client: Stream status update Workflow->>Services: LLM Chat (with document context if available) Services->>Workflow: Structured LLM Response Workflow-->>Server: Stream LogEvent about response processing Server-->>Client: Stream status update Workflow->>Server: Return final ChatResponseEvent Server->>Client: Return response with citations (if available) Note over Server: Context is maintained for follow-up questions ``` ## 关键特性 - **文件上传**:客户端可以上传文件并解析,以提供聊天的上下文 - **多回合对话**: 特工可在需要时要求补充资料 - **实时流线**: 处理时提供状态更新 - **推动通知**: 支持基于 Webhook 的通知 - **对话内存**: 在同一会话中保持互动的背景 - **LlamaParse 整合**: 使用 LlamaParse 精确解析文件 **NOTE:** 此样本代理接受多模式输入,但在撰写时,样本UI只支持文本输入. UI将来将成为多模式处理此和其他使用例. ## 先决条件 - Python 3.12 或更高音量 - [UV](https://docs.astral.sh/uv/) - 访问 LLM 和 API 密钥(当前代码假设使用 Google Gen AI API) - LlamaParse API 密钥 ([免费买一个](https://cloud.llamaindex.ai)) ## 设置运行( R) 1. 导航到样本目录 : ```bash cd samples/python/agents/llama_index_file_chat ``` 2. 用您的 API 密钥创建环境文件 : ```bash echo "GOOGLE_API_KEY=your_api_key_here" >> .env echo "LLAMA_CLOUD_API_KEY=your_api_key_here" >> .env ``` 3. 运行代理 : ```bash # Basic run on default port 10010 uv run . # On custom host/port uv run . --host 0.0.0.0 --port 8080 ``` 4. 在单独的终端中,运行一个 A2A [客户端](<https://github.com/samples/python/hosts/README.md>): ```bash cd samples/python/hosts/cli uv run . --agent http://localhost:10010 ``` 下载一个文件来解析, 或者链接到自己的文件。 例如 : ```bash wget https://arxiv.org/pdf/1706.03762 -O attention.pdf ``` 并输入如下内容: ```bash ======= Agent Card ======== {"name":"Parse and Chat","description":"Parses a file and then chats with a user using the parsed content as context.","url":"http://localhost:10010/","version":"1.0.0","capabilities":{"streaming":true,"pushNotifications":true,"stateTransitionHistory":false},"defaultInputModes":["text","text/plain"],"defaultOutputModes":["text","text/plain"],"skills":[{"id":"parse_and_chat","name":"Parse and Chat","description":"Parses a file and then chats with a user using the parsed content as context.","tags":["parse","chat","file","llama_parse"],"examples":["What does this file talk about?"]}]} ========= starting a new task ======== What do you want to send to the agent? (:q or quit to exit): What does this file talk about? Select a file path to attach? (press enter to skip): ./attention.pdf ``` ## 技术实施 - **LlamaIndex 工作流程**: 使用自定义的工作流程来解析文件,然后与用户聊天 - **流动支持**: 处理过程中提供增量更新 - **可串行上下文**:在转弯之间保持对话状态,可以可选择地坚持到 redis,mongodb,到磁盘等状态. - **推动通知系统**: 基于 Webhook 的更新, 并带有 JWK 认证 - **A2A 协议集成**:完全遵守A2A规格. ## 限制 - 只支持基于文本的输出 - LlamaParse为首款10K信用(~ 具有基本设置的3333页面)免费. - 内存基于会话和内存, 因此在服务器重启之间不会持续 。 - 在上下文窗口中插入整个文档对于更大的文件是无法扩展的。您可能想要部署向量 DB 或使用云 DB 运行在一个或多个文件之上的检索以有效 RAG 。 LlamaIndex 集成到一个 [矢量 DB 吨和云 DB 吨](https://docs.llamaindex.ai/en/stable/examples/#vector-stores). ## 实例 **同步请求** 请: ``` POST http://localhost:10010 Content-Type: application/json { "jsonrpc": "2.0", "id": 11, "method": "message/send", "params": { "id": "129", "sessionId": "8f01f3d172cd4396a0e535ae8aec6687", "acceptedOutputModes": [ "text" ], "message": { "role": "user", "parts": [ { "type": "text", "text": "What does this file talk about?" }, { "type": "file", "file": { "bytes": "...", "name": "attention.pdf" } } ] } } } ``` 答复: ``` { "jsonrpc": "2.0", "id": 11, "result": { "id": "129", "status": { "state": "completed", "timestamp": "2025-04-02T16:53:29.301828" }, "artifacts": [ { "parts": [ { "type": "text", "text": "This file is about XYZ... [1]" } ], "metadata": { "1": ["Text for citation 1"] } "index": 0, } ], } } ``` **多回合实例** 请求 - Seq 1 : ``` POST http://localhost:10010 Content-Type: application/json { "jsonrpc": "2.0", "id": 11, "method": "message/send", "params": { "id": "129", "sessionId": "8f01f3d172cd4396a0e535ae8aec6687", "acceptedOutputModes": [ "text" ], "message": { "role": "user", "parts": [ { "type": "text", "text": "What does this file talk about?" }, { "type": "file", "file": { "bytes": "...", "name": "attention.pdf" } } ] } } } ``` 回应-Seq 2: ``` { "jsonrpc": "2.0", "id": 11, "result": { "id": "129", "status": { "state": "completed", "timestamp": "2025-04-02T16:53:29.301828" }, "artifacts": [ { "parts": [ { "type": "text", "text": "This file is about XYZ... [1]" } ], "metadata": { "1": ["Text for citation 1"] } "index": 0, } ], } } ``` 请求 - Seq 3 : ``` POST http://localhost:10010 Content-Type: application/json { "jsonrpc": "2.0", "id": 11, "method": "message/send", "params": { "id": "130", "sessionId": "8f01f3d172cd4396a0e535ae8aec6687", "acceptedOutputModes": [ "text" ], "message": { "role": "user", "parts": [ { "type": "text", "text": "What about thing X?" } ] } } } ``` 回应-Seq 4: ``` { "jsonrpc": "2.0", "id": 11, "result": { "id": "130", "status": { "state": "completed", "timestamp": "2025-04-02T16:53:29.301828" }, "artifacts": [ { "parts": [ { "type": "text", "text": "Thing X is ... [1]" } ], "metadata": { "1": ["Text for citation 1"] } "index": 0, } ], } } ``` **串流实例** 请: ``` { "jsonrpc": "2.0", "id": 11, "method": "message/send", "params": { "id": "129", "sessionId": "8f01f3d172cd4396a0e535ae8aec6687", "acceptedOutputModes": [ "text" ], "message": { "role": "user", "parts": [ { "type": "text", "text": "What does this file talk about?" }, { "type": "file", "file": { "bytes": "...", "name": "attention.pdf" } } ] } } } ``` 答复: ``` stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"working","message":{"role":"agent","parts":[{"type":"text","text":"Parsing document..."}]},"timestamp":"2025-04-15T16:05:18.283682"},"final":false}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"working","message":{"role":"agent","parts":[{"type":"text","text":"Document parsed successfully."}]},"timestamp":"2025-04-15T16:05:24.200133"},"final":false}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"working","message":{"role":"agent","parts":[{"type":"text","text":"Chatting with 1 initial messages."}]},"timestamp":"2025-04-15T16:05:24.204757"},"final":false}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"working","message":{"role":"agent","parts":[{"type":"text","text":"Inserting system prompt..."}]},"timestamp":"2025-04-15T16:05:24.204810"},"final":false}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"working","message":{"role":"agent","parts":[{"type":"text","text":"LLM response received, parsing citations..."}]},"timestamp":"2025-04-15T16:05:26.084829"},"final":false}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","artifact":{"parts":[{"type":"text","text":"This file discusses the Transformer, a novel neural network architecture based solely on attention mechanisms, dispensing with recurrence and convolutions entirely [1]. The document compares the Transformer to recurrent and convolutional layers [2], details the model architecture [3], and presents results from machine translation and English constituency parsing tasks [4]."}],"metadata":{"1":["The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data."],"2":["In this section we compare various aspects of self-attention layers to the recurrent and convolutional layers commonly used for mapping one variable-length sequence of symbol representations (x1, ..., xn) to another sequence of equal length (z1, ..., zn), with xi, zi ∈ Rd, such as a hidden layer in a typical sequence transduction encoder or decoder. Motivating our use of self-attention we consider three desiderata.",""],"3":["# 3 Model Architecture"],"4":["# 6 Results"]},"index":0,"append":false}}} stream event => {"jsonrpc":"2.0","id":"367d0ba9af97457890261ac29a0f6f5b","result":{"id":"373b26d64c5a4f0099fa906c6b7342d9","status":{"state":"completed","timestamp":"2025-04-15T16:05:26.111314"},"final":true}} ``` 您可以看到工作流程产生了带有线内引用的文物, 这些引用的源文本包含在文物的元数据中。 如果我们在同一会话中发送更多的回复, 代理将记住之前的消息, 并继续对话 。 ## 学习更多 - [A2A 协议文档](https://google.github.io/A2A/#/documentation) - [LlamaIndex 工作流程文档](https://docs.llamaindex.ai/en/stable/understanding/workflows/) - [LlamaIndex 工作流程示例](https://docs.llamaindex.ai/en/stable/examples/#agentic-workflows) - [LlamaParse 文档](https://github.com/run-llama/llama_cloud_services/blob/main/parse.md) - [谷歌双子座 API](https://ai.google.dev/gemini-api) ## 免责声明 重要的: 提供的样本代码是用于演示目的, 并说明了代理对代理( A2A) 协议的力学。 在构建生产应用程序时, 将任何在您直接控制下运行的代理视为一个潜在的不信任实体至关重要 。 从外部代理机构收到的所有数据——包括但不限于其AgentCard、消息、文物和任务状态——应作为不可信的输入处理。 例如,恶意代理机构可以提供包含其领域(例如描述、名称、技能.描述)的精心制作的数据的AgentCard。如果使用此数据时没有进行消毒以构建大语言模型( LLM ) 的提示, 可能会使您的应用面临迅速的注射攻击。 如果在使用之前无法正确验证和消毒此数据, 可能会给您的应用带来安全弱点 。 开发者负责实施适当的安全措施,如输入验证和对证书的安全处理,以保护他们的系统和用户.

查看原始来源