vmthinh159/MultiModal-Agent
0
MultiModal Agent with LangGraph
Một agent đa phương thức hiệu quả được xây dựng bằng LangGraph, được thiết kế để trả lời các câu hỏi phức tạp với độ chính xác cao thông qua việc sử dụng các tools chuyên biệt.
Tính năng
🔍 Web Search & Information Retrieval
- Web Search: Tìm kiếm thông tin trên internet bằng Tavily API
- Wikipedia Search: Truy cập kiến thức từ Wikipedia
- arXiv Search: Tìm kiếm bài báo khoa học
- Content Scraping: Trích xuất nội dung từ các trang web
🧮 Mathematical Capabilities
- Basic Operations: Cộng, trừ, nhân, chia, lũy thừa, căn bậc hai
- Advanced Calculations: Đánh giá biểu thức toán học phức tạp
- Safe Evaluation: Thực thi toán học an toàn với sandbox
💻 Code Execution
- Python Code: Thực thi code Python an toàn
- Timeout Protection: Giới hạn thời gian thực thi (30 giây)
- Safe Environment: Môi trường isolated để tránh lỗi system
📄 Document Processing
- PDF Reader: Đọc và trích xuất nội dung từ file PDF
- CSV/Excel Analysis: Phân tích dữ liệu từ spreadsheets
- File Download: Tải và xử lý file từ URL
🖼️ Advanced Image Analysis
- OpenAI Vision API: Phân tích hình ảnh bằng GPT-4V
- OCR Capabilities: Trích xuất text từ hình ảnh
- Chart/Graph Analysis: Hiểu và giải thích biểu đồ
🏗️ LangGraph Architecture
- State Management: Quản lý trạng thái conversation
- Tool Orchestration: Điều phối tools một cách thông minh
- Multi-Provider Support: Hỗ trợ Groq, Google Gemini, HuggingFace
- Error Recovery: Xử lý lỗi và retry logic
Cài đặt
- Clone repository:
git clone <repo-url>
cd MultiModal-Agent- Cài đặt dependencies:
pip install -r requirements.txt- Thiết lập API keys:
🔑 Required API Keys:
OPENAI_API_KEY (Bắt buộc):
export OPENAI_API_KEY="your_openai_api_key_here"- Đăng ký tại: https://platform.openai.com/
- Cần cho: GPT-4o-mini model và Vision API
TAVILY_API_KEY (Tùy chọn nhưng khuyến nghị):
export TAVILY_API_KEY="your_tavily_api_key_here" - Đăng ký tại: https://tavily.com/
- Nếu không có: Agent sẽ dùng DuckDuckGo fallback
🚀 Chạy trên HuggingFace Space:
- Fork space này
- Vào Settings → Variables
- Thêm secrets:
OPENAI_API_KEY: youropenaikeyTAVILY_API_KEY: yourtavilykey (optional)
💻 Chạy local:
# Tạo file .env
cat > .env << EOF
OPENAI_API_KEY=your_openai_api_key_here
TAVILY_API_KEY=your_tavily_api_key_here
EOF
# Hoặc export trực tiếp
export OPENAI_API_KEY="your_key_here"
export TAVILY_API_KEY="your_key_here"Sử dụng
Chạy ứng dụng Gradio:
python app.pyTest local:
# Test agent với câu hỏi đơn giản
from app import MultiModalAgent
agent = MultiModalAgent(provider="groq")
result = agent("What is the capital of France?")
print(result)Cấu trúc Project
MultiModal-Agent/
├── app.py # Main application với LangGraph
├── prompts.yaml # System prompts
├── requirements.txt # Dependencies
├── tools/
│ ├── __init__.py
│ └── langchain_tools.py # Tất cả tools với LangChain format
├── README.md
└── .env.example # Environment variables templateLangGraph Architecture
graph TD
A[User Question] --> B[Prepare Messages]
B --> C[Assistant LLM]
C --> D{Need Tools?}
D -->|Yes| E[Tool Execution]
E --> C
D -->|No| F[Final Answer]
F --> G[FINAL ANSWER: ...]Workflow:
- Question Preprocessing: Thêm hints dựa trên keywords
- LLM Processing: Groq/Google/HuggingFace models
- Tool Selection: Conditional logic chọn tools phù hợp
- Tool Execution: Parallel execution với error handling
- Answer Extraction: Pattern matching cho "FINAL ANSWER:"
Tools Coverage
Provider Options
1. Groq (Default)
- Model:
qwen-qwq-32b - Pros: Nhanh, free tier tốt
- Best for: Production usage
2. Google Gemini
- Model:
gemini-pro - Pros: Multimodal capabilities
- Best for: Complex reasoning
3. HuggingFace
- Model:
microsoft/DialoGPT-medium - Pros: Open source, customizable
- Best for: Privacy-focused deployments
Advanced Features
Question Preprocessing
Agent tự động thêm hints dựa trên keywords:
arxiv/paper/research→ "Use arxiv_search tool"calculate/math/equation→ "Use calculate_math tool"image/picture/chart→ "Use analyzeimagewith_openai tool"
Enhanced Error Handling
- Timeout Protection: 30 giây cho code execution
- API Rate Limiting: Automatic retry với backoff
- Graceful Failures: Fallback responses khi tools fail
Smart Answer Extraction
- Pattern Matching: Tìm "FINAL ANSWER:" trong response
- Content Filtering: Loại bỏ debug info và metadata
- Clean Output: Chỉ trả về answer cuối cùng
Performance Metrics
Troubleshooting
❌ "Recursion limit reached"
- Nguyên nhân: Agent bị loop khi search không tìm thấy thông tin
- Giải pháp:
- Kiểm tra API keys đã cấu hình đúng chưa
- Agent đã được tối ưu với recursion_limit=20
- Nếu vẫn lỗi: câu hỏi có thể quá phức tạp
❌ "OPENAI_API_KEY must be set"
- Nguyên nhân: Thiếu hoặc sai OpenAI API key
- Giải pháp:
- Kiểm tra API key trong Settings → Variables (HF Space)
- Hoặc
export OPENAI_API_KEY="your_key"(local)
❌ "Error in web search"
- Nguyên nhân: Tavily API key không có hoặc hết quota
- Giải pháp: Agent tự động fallback sang DuckDuckGo search
⚠️ Agent trả lời "I cannot find this information"
- Nguyên nhân: Tools không tìm được thông tin hoặc question quá specific
- Cải thiện: Agent đã được update system prompt tích cực hơn
📊 Performance Tips:
- ✅ OpenAI API key active → Best performance
- ✅ Tavily API key → Better search results
- ✅ HuggingFace Space → Optimal environment
- ⚠️ Local without APIs → Limited functionality
So sánh với phiên bản cũ
Monitoring & Debugging
LangSmith Integration (Optional)
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_API_KEY="your_langsmith_key"
export LANGCHAIN_PROJECT="multimodal-agent"Local Debugging
# Enable verbose mode
agent = MultiModalAgent(provider="groq")
agent.graph.set_debug(True)Contributing
- Fork repository
- Tạo feature branch:
git checkout -b feature/new-tool - Implement tool trong
tools/langchain_tools.py - Add tool vào
toolslist trongapp.py - Test thoroughly
- Submit PR
License
MIT License - Xem file LICENSE để biết chi tiết.
Note: Agent này được thiết kế cho competition format với "FINAL ANSWER:" requirement. Để sử dụng cho mục đích khác, có thể cần modify answer extraction logic.
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
