A Fetch.ai uAgent that accepts PDF files as input, extracts text content, and provides intelligent summaries using the ASI:One API. This agent demonstrates how to build agents that can process PDF attachments through the Agent chat protocol.
- ✅ Accepts PDF files via chat protocol
- ✅ Extracts text from PDFs using multiple libraries (pdfplumber, PyPDF2)
- ✅ Generates intelligent summaries using ASI:One API
- ✅ Runs as a Mailbox Agent (local with Agentverse integration)
- ✅ Handles multiple PDFs in a single message
- ✅ Robust error handling and fallback mechanisms
A document processing agent that:
- Receives PDF attachments from users via ASI:One
- Extracts text content from PDF documents
- Generates concise summaries using AI
- Responds with summarized content
- Python 3.9+
- ASI:One API key
- 5-10 minutes
- Visit ASI:One
- Sign up or log in to your account
- Navigate to API Keys section
- Create a new API key
- Copy your API key
# Navigate to the project directory
cd pdf-summariser-example
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install required packages
pip install -r requirements.txtCreate a .env file in the project root:
ASI_ONE_API_KEY=your_asi_one_api_key_hereNote: The agent uses the ASI:One API for summarization. Make sure your API key has sufficient credits.
The agent consists of three main components:
from uagents import Agent
from chat_proto import chat_proto
agent = Agent(name="PDF Summariser Agent", port=8005, mailbox=True)
# Include the chat protocol to handle text and PDF contents
agent.include(chat_proto, publish_manifest=True)
if __name__ == "__main__":
agent.run()Key Points:
mailbox=Trueenables Mailbox Agent mode (local agent connected to Agentverse)port=8005sets the local server portpublish_manifest=Truemakes the agent discoverable on Agentverse
Handles incoming messages and processes PDF resources:
- Receives
ChatMessagewith PDF attachments - Downloads PDFs from Agentverse storage or URI
- Extracts text using utility functions
- Sends summaries back to the user
Contains PDF processing logic:
extract_text_from_pdf()- Extracts text using pdfplumber (preferred) or PyPDF2 (fallback)get_pdf_text()- Processes content items and extracts PDF textsummarize_text()- Calls ASI:One API to generate summaries
python agent.pyYou should see output like:
INFO: [PDF Summariser Agent]: Starting agent with address: agent1q...
INFO: [PDF Summariser Agent]: Agent inspector available at https://Agentverse.ai/inspect/?uri=...
INFO: [PDF Summariser Agent]: Starting server on http://0.0.0.0:8005 (Press CTRL+C to quit)
INFO: [PDF Summariser Agent]: Starting mailbox client for https://Agentverse.ai
INFO: [PDF Summariser Agent]: Mailbox access token acquired
INFO: [PDF Summariser Agent]: Registration on Almanac API successful
Since this agent uses mailbox=True, you need to connect it to Agentverse:
- Run your agent locally (as shown in Step 5)
- Click the Inspector URL from the terminal output (e.g.,
https://Agentverse.ai/inspect/?uri=...) - Click the "Connect" button in the Inspector UI
- Select "Mailbox" as the connection type
- Click "Finish" to complete the connection
For detailed instructions, refer to the Mailbox Agents documentation.
Your agent is now connected to Agentverse and can receive messages from other agents and users!
- Open ASI:One
- Start a conversation with the agent by typing @agentaddress summarise this PDF and attach a PDF file
- The agent will extract text and provide a summary
This agent serves as a template for building PDF-processing agents. Here's how to customize it:
Modify utils.py to implement your own PDF processing:
def process_pdf_content(pdf_text: str, logger=None) -> str:
"""
Custom processing function - replace summarize_text() with your logic
"""
# Example: Extract specific information
# Example: Answer questions about the PDF
# Example: Translate the content
# Example: Extract structured data
passUpdate chat_proto.py to change how the agent responds:
# Instead of sending a summary, you could:
# - Send structured data
# - Send multiple messages
# - Include metadata
# - Trigger other actionsExtend the agent to handle other document types:
# In chat_proto.py, add support for other MIME types:
if mime_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
# Process .docx files
pass
elif mime_type == "text/plain":
# Process .txt files
passEdit agent.py:
agent = Agent(
name="Your Custom PDF Agent", # Change name
port=8006, # Change port if needed
mailbox=True
)For additional configuration, add to .env:
ASI_ONE_API_KEY=your_key
MAX_PDF_SIZE=10485760 # 10MB in bytes
SUMMARY_LENGTH=500 # Target summary lengthThen use in your code:
import os
max_size = int(os.getenv("MAX_PDF_SIZE", "10485760"))pdf-summariser-example/
├── agent.py # Main agent setup and configuration
├── chat_proto.py # Chat protocol handlers for messages and PDFs
├── utils.py # PDF extraction and summarization utilities
├── requirements.txt # Python dependencies
├── README.md # This file
└── downloads/ # Directory for downloaded PDFs (created at runtime)
The agent uses a dual-library approach for robust PDF text extraction:
- pdfplumber (primary) - Better for complex PDFs with tables and formatting
- PyPDF2 (fallback) - Simpler library, works for basic PDFs
# From utils.py
def extract_text_from_pdf(pdf_bytes: bytes, logger=None) -> str:
# Tries pdfplumber first, falls back to PyPDF2
# Returns page-by-page extracted textUses ASI:One API with the asi1-mini model:
# From utils.py
def summarize_text(text: str, logger=None) -> Optional[str]:
# Sends text to ASI:One API
# Returns concise summary
# Handles errors gracefullyAdjust text extraction behavior in utils.py:
# Maximum text length for summarization
max_length = 100000 # Adjust based on model limits
# Summary prompt customization
prompt = f"""Your custom prompt here:
{text_to_summarize}
"""Modify agent behavior in agent.py:
agent = Agent(
name="PDF Summariser Agent",
port=8005, # Change if port is in use
mailbox=True, # Required for Agentverse connection
# publish_agent_details=True, # Uncomment to publish on Agentverse
# readme_path="README.md" # Uncomment if publishing
)"ASI_ONE_API_KEY not found"
- Check your
.envfile exists in the project root - Verify the variable name is exactly
ASI_ONE_API_KEY - Restart your agent after adding the key
"No PDF extraction library available"
- Ensure
pdfplumberorPyPDF2is installed:pip install pdfplumber PyPDF2 - Check
requirements.txtincludes these packages
"Failed to download PDF"
- Check your internet connection
- Verify the PDF resource is accessible
- Check Agentverse storage permissions
"Agent not responding"
- Check if port 8005 is available (change port if needed)
- Look for errors in console output
- Verify mailbox connection is established
- Check ASI:One API key is valid and has credits
"Can't find agent on ASI:One"
- Wait 1-2 minutes after starting the agent
- Ensure mailbox is connected (check Inspector UI)
- Verify agent is registered on Almanac
- Check agent address is correct
"PDF extraction failed"
- The PDF might be corrupted or password-protected
- Try a different PDF file
- Check PDF is not a scanned image (requires OCR)
- Verify PDF is not empty
Enhance this agent for:
- 📄 Document Q&A - Answer questions about PDF content
- 📊 Data Extraction - Extract structured data from PDFs
- 🌐 Multi-language Processing - Translate and summarize PDFs
- 📝 Content Analysis - Analyze and categorize documents
- 🔍 Search & Retrieval - Build a PDF search system
- 📚 Research Assistant - Process academic papers and research documents
- 💼 Business Intelligence - Extract insights from business documents
- 🎓 Educational Tools - Summarize textbooks and course materials
agent.py- Main agent code and configurationchat_proto.py- Chat protocol implementationutils.py- PDF processing and summarization utilitiesrequirements.txt- Python dependencies
- Mailbox Agents Documentation - How to connect mailbox agents to Agentverse
- Fetch.ai Innovation Lab - Official documentation and resources
- Agentverse - Agent marketplace and deployment platform
- ASI:One - AI platform for agent interactions
- uAgents Documentation - uAgents framework documentation