CoolFace
Apppublic

vmthinh159/MultiModal-Agent

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
App README

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

  1. 1.Clone repository:
bash
git clone <repo-url>
cd MultiModal-Agent
  1. 1.Cài đặt dependencies:
bash
pip install -r requirements.txt
  1. 1.Thiết lập API keys:

🔑 Required API Keys:

OPENAI_API_KEY (Bắt buộc):

bash
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ị):

bash
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:

  1. 1.Fork space này
  2. 2.Vào Settings → Variables
  3. 3.Thêm secrets:
  4. 4.OPENAI_API_KEY: youropenaikey
  5. 5.TAVILY_API_KEY: yourtavilykey (optional)

💻 Chạy local:

bash
# 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:

bash
python app.py

Test local:

bash
# 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 template

LangGraph Architecture

mermaid
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:

  1. 1.Question Preprocessing: Thêm hints dựa trên keywords
  2. 2.LLM Processing: Groq/Google/HuggingFace models
  3. 3.Tool Selection: Conditional logic chọn tools phù hợp
  4. 4.Tool Execution: Parallel execution với error handling
  5. 5.Answer Extraction: Pattern matching cho "FINAL ANSWER:"

Tools Coverage

Tool CategoryUsage %Tools Available
Web Search90%websearch, wikisearch, scrape_webpage
Document Processing25%downloadandreadpdf, arxivsearch
Mathematics20%calculatemath, add, subtract, multiply, divide, power, squareroot
Image Analysis15%analyzeimagewithopenai, extracttextfromimage_ocr
File Processing10%analyzecsvfile, analyzeexcelfile, downloadfilefrom_url
Code ExecutionNewexecutepythoncode

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

MetricTargetLangGraph Implementation
Accuracy>50%Optimized for high accuracy
Response Time<30sFast LLM + parallel tools
Tool Success Rate>90%Enhanced error handling
Coverage95% question types17 specialized tools

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ũ

AspectOld (smolagents)New (LangGraph)
ArchitectureLinear tool chainState-based graph
Error HandlingBasicAdvanced with recovery
Tool ExecutionSequentialParallel where possible
Provider SupportOpenAI onlyMulti-provider
DebuggingLimitedLangSmith integration
ScalabilityPoorExcellent
MaintenanceHardEasy

Monitoring & Debugging

LangSmith Integration (Optional)

bash
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_API_KEY="your_langsmith_key"
export LANGCHAIN_PROJECT="multimodal-agent"

Local Debugging

python
# Enable verbose mode
agent = MultiModalAgent(provider="groq")
agent.graph.set_debug(True)

Contributing

  1. 1.Fork repository
  2. 2.Tạo feature branch: git checkout -b feature/new-tool
  3. 3.Implement tool trong tools/langchain_tools.py
  4. 4.Add tool vào tools list trong app.py
  5. 5.Test thoroughly
  6. 6.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