Multi-Modal AI Agent System
Project description
xAgent - Multi-Modal AI Agent System
๐ A powerful multi-modal AI Agent system with real-time streaming responses
xAgent provides a complete AI assistant experience with text and image processing capabilities, intelligent vocabulary management, high-performance concurrent tool execution, and real-time streaming CLI interface. Built on FastAPI, Streamlit, and Redis for production-ready scalability.
๐ Table of Contents
- ๐ Installation & Setup
- ๐ Quick Start: HTTP Agent Server
- ๐ป Command Line Interface (CLI)
- ๐ค Advanced Usage: Agent Class
- ๐ฎ Full Project Experience
- ๐๏ธ Architecture
- ๐ง Development Guide
- ๐ค API Reference
- ๐ Monitoring & Observability
- ๐ค Contributing
- ๐ License
๐ Installation & Setup
Prerequisites
| Requirement | Version | Purpose |
|---|---|---|
| Python | 3.12+ | Core runtime |
| Redis | 7.0+ | Message persistence |
| OpenAI API Key | - | AI model access |
Install via pip
pip install myxagent
Environment Configuration
Create a .env file in your project directory:
# Required
OPENAI_API_KEY=your_openai_api_key
# Optional - Redis persistence
REDIS_URL=your_redis_url_with_password
# Optional - Observability
LANGFUSE_SECRET_KEY=your_langfuse_key
LANGFUSE_PUBLIC_KEY=your_langfuse_public_key
LANGFUSE_HOST=https://cloud.langfuse.com
# Optional - Image upload to S3
AWS_ACCESS_KEY_ID=your_aws_access_key_id
AWS_SECRET_ACCESS_KEY=your_aws_secret_access_key
AWS_REGION=us-east-1
BUCKET_NAME=your_bucket_name
you can manually load the .env file into your shell:
export $(cat .env | grep -v '^#' | xargs)
๐ Quick Start: HTTP Agent Server
The simplest way to use xAgent is through the HTTP server. Just create a config file and start serving!
1. Create Agent Configuration
Create agent_config.yaml:
agent:
name: "MyAgent"
system_prompt: |
You are a helpful assistant. Your task is to assist users with their queries and tasks.
model: "gpt-4.1-mini"
tools:
- "web_search" # Built-in web search
- "draw_image" # Built-in image generation (need set AWS credentials in .env)
- "calculate_square" # Custom tool from my_toolkit
server:
host: "0.0.0.0"
port: 8010
you can also add mcp_servers if you want to use MCP (Model Context Protocol) for dynamic tool loading:
agent:
...
mcp_servers:
- "http://localhost:8001/mcp/"
...
you can also set use_local_session to false if you want to use Redis for session persistence(need to set REDIS_URL in .env):
agent:
...
use_local_session: false
...
2. Create Custom Tools (Optional)
Create my_toolkit/ directory with __init__.py and your tool functions in script like your_tools.py:
# my_toolkit/__init__.py
from .your_tools import calculate_square, greet_user
# Agent will automatically discover these tools
TOOLKIT_REGISTRY = {
"calculate_square": calculate_square,
"greet_user": greet_user
}
implement your tools in your_tools.py:
# my_toolkit/your_tools.py
from xagent.utils.tool_decorator import function_tool
@function_tool()
def calculate_square(n: int) -> int:
"""Calculate the square of a number."""
return n * n
@function_tool()
def greet_user(name: str) -> str:
"""Greet a user by name."""
return f"Hello, {name}! Nice to meet you."
3. Start the Server
# Start the HTTP Agent Server
xagent-server --config agent_config.yaml
# With custom toolkit (optional)
xagent-server --config agent_config.yaml --toolkit my_toolkit
# Server will be available at http://localhost:8010
4. Use the API
# Simple chat request
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user123",
"session_id": "session456",
"user_message": "Calculate the square of 15 and greet me as Alice"
}'
# Streaming response
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "user123",
"session_id": "session456",
"user_message": "Hello, how are you?",
"stream": true
}'
5. API Documentation
Visit http://localhost:8010/docs for interactive API documentation.
๐ป Command Line Interface (CLI)
xAgent provides a powerful command-line interface for quick interactions and testing. The CLI supports both single-question mode and interactive chat sessions, with real-time streaming responses for a smooth conversational experience.
Quick Start
# Interactive chat mode with streaming (default)
xagent-cli
# Use custom configuration
xagent-cli chat --config my_config.yaml --toolkit my_toolkit --user_id developer --session_id session123 --verbose
# Ask a single question (non-streaming)
xagent-cli ask "What is the capital of France?"
Interactive Chat Mode
Start a continuous conversation with the agent with streaming enabled by default:
$ xagent-cli chat
๐ค Welcome to xAgent CLI!
Agent: Agent
Model: gpt-4.1-mini
Tools: 3 loaded
Session: cli_session_abc123
Streaming: Enabled
Type 'exit', 'quit', or 'bye' to end the session.
Type 'clear' to clear the session history.
Type 'stream on/off' to toggle streaming mode.
Type 'help' for available commands.
--------------------------------------------------
๐ค You: Hello, how are you?
๐ค Agent: Hello! I'm doing well, thank you for asking...
[Response streams in real-time]
๐ค You: help
๐ Available commands:
exit, quit, bye - Exit the chat session
clear - Clear session history
stream on/off - Toggle streaming mode
help - Show this help message
๐ค You: exit
๐ Goodbye!
CLI Commands Reference
| Command | Description | Example |
|---|---|---|
xagent-cli |
Start interactive chat with streaming (default) | xagent-cli |
xagent-cli chat |
Start interactive chat explicitly | xagent-cli chat --config my_config.yaml |
xagent-cli chat --no-stream |
Start interactive chat without streaming | xagent-cli chat --no-stream |
xagent-cli ask <message> |
Ask single question (non-streaming) | xagent-cli ask "Hello world" |
CLI Options
| Option | Description | Default |
|---|---|---|
--config |
Configuration file path | config/agent.yaml |
--toolkit_path |
Custom toolkit directory | toolkit |
--user_id |
User identifier | Auto-generated |
--session_id |
Session identifier | Auto-generated |
--verbose, -v |
Enable verbose logging | False |
--no-stream |
Disable streaming (chat mode only) | False |
๐ค Advanced Usage: Agent Class
For more control and customization, use the Agent class directly in your Python code.
Basic Agent Usage
import asyncio
from xagent.core import Agent, Session
async def main():
# Create agent
agent = Agent(
name="my_assistant",
system_prompt="You are a helpful AI assistant.",
model="gpt-4.1-mini"
)
# Create session for conversation management
session = Session(session_id="session456")
# Chat interaction
response = await agent.chat("Hello, how are you?", session)
print(response)
# Streaming response example
response = await agent.chat("Tell me a story", session, stream=True)
async for event in response:
print(event, end="")
asyncio.run(main())
Adding Custom Tools
import asyncio
import time
import httpx
from xagent.utils.tool_decorator import function_tool
from xagent.core import Agent, Session
# Sync tools - automatically converted to async
@function_tool()
def calculate_square(n: int) -> int:
"""Calculate square of a number."""
time.sleep(0.1) # Simulate CPU work
return n * n
# Async tools - used directly for I/O operations
@function_tool()
async def fetch_weather(city: str) -> str:
"""Fetch weather data from API."""
async with httpx.AsyncClient() as client:
await asyncio.sleep(0.5) # Simulate API call
return f"Weather in {city}: 22ยฐC, Sunny"
async def main():
# Create agent with custom tools
agent = Agent(
tools=[calculate_square, fetch_weather],
model="gpt-4.1-mini"
)
session = Session(user_id="user123")
# Agent handles all tools automatically
response = await agent.chat(
"Calculate the square of 15 and get weather for Tokyo",
session
)
print(response)
asyncio.run(main())
Structured Outputs with Pydantic
import asyncio
from pydantic import BaseModel
from xagent.core import Agent, Session
from xagent.tools import web_search
class WeatherReport(BaseModel):
location: str
temperature: int
condition: str
humidity: int
async def get_structured_response():
agent = Agent(model="gpt-4.1-mini", tools=[web_search])
session = Session(user_id="user123")
# Request structured output
weather_data = await agent.chat(
"what's the weather like in Hangzhou?",
session,
output_type=WeatherReport
)
print(f"Location: {weather_data.location}")
print(f"Temperature: {weather_data.temperature}ยฐF")
print(f"Condition: {weather_data.condition}")
print(f"Humidity: {weather_data.humidity}%")
asyncio.run(get_structured_response())
Agent as Tool Pattern
import asyncio
from xagent.core import Agent, Session
from xagent.db import MessageDB
from xagent.tools import web_search
async def agent_as_tool_example():
# Create specialized agents
researcher_agent = Agent(
name="research_specialist",
system_prompt="Research expert. Gather information and provide insights.",
model="gpt-4.1-mini",
tools=[web_search]
)
# Convert agent to tool
message_db = MessageDB()
research_tool = researcher_agent.as_tool(
name="researcher",
description="Research topics and provide detailed analysis",
message_db=message_db
)
# Main coordinator agent with specialist tools
coordinator = Agent(
name="coordinator",
tools=[research_tool],
system_prompt="Coordination agent that delegates to specialists.",
model="gpt-4.1"
)
session = Session(user_id="user123")
# Complex multi-step task
response = await coordinator.chat(
"Research renewable energy benefits and write a brief summary",
session
)
print(response)
asyncio.run(agent_as_tool_example())
Persistent Sessions with Redis
import asyncio
from xagent.core import Agent, Session
from xagent.db import MessageDB
async def chat_with_persistence():
# Initialize Redis-backed message storage
message_db = MessageDB()
# Create agent
agent = Agent(
name="persistent_agent",
model="gpt-4.1-mini"
)
# Create session with Redis persistence
session = Session(
user_id="user123",
session_id="persistent_session",
message_db=message_db
)
# Chat with automatic message persistence
response = await agent.chat("Remember this: my favorite color is blue", session)
print(response)
# Later conversation - context is preserved in Redis
response = await agent.chat("What's my favorite color?", session)
print(response)
asyncio.run(chat_with_persistence())
๐ฎ Full Project Experience
If you want to experience the complete xAgent ecosystem with all features, clone the repository and use the provided scripts.
Clone the Repository
git clone https://github.com/ZJCODE/xAgent.git
cd xAgent
pip install -r requirements.txt
Environment Setup
# Copy and edit environment file
cp .env.example .env
# Edit .env with your API keys
Quick Start (All Services)
chmod +x run.sh
./run.sh
This will start:
- HTTP Agent Server (http://localhost:8010) - Standalone agent API
- MCP Server (http://localhost:8001) - Model Context Protocol server
- Chat Interface (http://localhost:8501) - Streamlit web interface
Manual Start (Individual Services)
# Terminal 1: Standalone HTTP Agent Server
python xagent/core/server.py --config config/agent.yaml --toolkit toolkit
# Terminal 2: MCP Server
python toolkit/mcp_server.py
# Terminal 3: Frontend
streamlit run frontend/chat_app.py --server.port 8501
Access Points
| Service | URL | Description |
|---|---|---|
| Chat Interface | http://localhost:8501 | Main user interface |
| API Docs | http://localhost:8000/docs | Interactive API documentation |
| HTTP Agent Server | http://localhost:8010/chat | Standalone agent HTTP API |
| Health Check | http://localhost:8000/health | Service status monitoring |
๐๏ธ Architecture
Modern Design for High Performance
xAgent/
โโโ ๐ค xagent/ # Core async agent framework
โ โโโ core/ # Agent and session management
โ โ โโโ agent.py # Main Agent class with chat
โ โ โโโ session.py # Session management with operations
โ โ โโโ server.py # Standalone HTTP Agent Server
โ โโโ db/ # Database layer (Redis)
โ โ โโโ message.py # Message persistence
โ โโโ schemas/ # Data models and types (Pydantic)
โ โ โโโ message.py # Message and ToolCall models
โ โโโ tools/ # Tool ecosystem
โ โ โโโ __init__.py # Tool registry (web_search, draw_image)
โ โ โโโ openai_tool.py # OpenAI tool integrations
โ โ โโโ mcp_demo/ # MCP demo server and client
โ โโโ utils/ # Utility functions
โ โโโ tool_decorator.py # Tool decorators
โ โโโ mcp_convertor.py # MCP client
โ โโโ image_upload.py # AWS S3 image upload utility
โโโ ๐ ๏ธ toolkit/ # Custom tool ecosystem
โ โโโ __init__.py # Toolkit registry
โ โโโ tools.py # Custom tools (char_count)
โ โโโ mcp_server.py # Main MCP server
โ โโโ vocabulary/ # Vocabulary learning system
โโโ โ๏ธ config/ # Configuration files
โ โโโ agent.yaml # Agent server configuration
โโโ ๐จ frontend/ # Streamlit web interface
โ โโโ chat_app.py # Main chat application
โโโ ๐ examples/ # Usage examples and demos
โ โโโ basic_chat.py # Basic agent usage
โ โโโ stream_chat.py # Streaming response example
โ โโโ cli_streaming_guide.py # Complete CLI streaming guide
โ โโโ streaming_cli_usage.py # CLI usage patterns
โโโ ๐งช tests/ # Comprehensive test suite
๐ Core Components
| Component | Purpose | Technology |
|---|---|---|
| Agent | Core conversation handler | OpenAI API + AsyncIO |
| Session | Message history management | Redis + Operations |
| MessageDB | Scalable persistence layer | Redis with client |
| Tools | Extensible function ecosystem | Auto sync-to-async conversion |
| MCP | Dynamic tool loading protocol | HTTP client |
๐ ๏ธ Creating Tools
Both sync and async functions work seamlessly:
from xagent.utils.tool_decorator import function_tool
import asyncio
import time
# โ
Sync tool - perfect for CPU-bound operations
@function_tool()
def my_sync_tool(input_text: str) -> str:
"""Process text synchronously (runs in thread pool)."""
time.sleep(0.1) # Simulate CPU-intensive work
return f"Sync processed: {input_text}"
# โ
Async tool - ideal for I/O-bound operations
@function_tool()
async def my_async_tool(input_text: str) -> str:
"""Process text asynchronously."""
await asyncio.sleep(0.1) # Simulate async I/O operation
return f"Async processed: {input_text}"
๐ Tool Development Guidelines
| Use Case | Tool Type | Example |
|---|---|---|
| CPU-bound | Sync functions | Math calculations, data processing |
| I/O-bound | Async functions | API calls, database queries |
| Simple operations | Sync functions | String manipulation, file operations |
| Network requests | Async functions | HTTP requests, WebSocket connections |
โ ๏ธ Note: Recursive functions are not supported as tools due to potential stack overflow issues in async environments.
๐ Automatic Conversion
xAgent's @function_tool() decorator automatically handles sync-to-async conversion:
- Sync functions โ Run in thread pool (non-blocking)
- Async functions โ Run directly on event loop
- Concurrent execution โ All tools execute in parallel when called
๐ Override Defaults
You can override the default tool name and description using the function_tool decorator:
@function_tool(name="custom_square", description="Calculate the square of a number")
def calculate_square(n: int) -> int:
return n * n
๐ค API Reference
Core Classes
๐ค Agent
Main AI agent class for handling conversations and tool execution.
Agent(
name: Optional[str] = None,
system_prompt: Optional[str] = None,
model: Optional[str] = None,
client: Optional[AsyncOpenAI] = None,
tools: Optional[list] = None,
mcp_servers: Optional[str | list] = None
)
Key Methods:
async chat(user_message, session, **kwargs) -> str | BaseModel: Main chat interfaceasync __call__(user_message, session, **kwargs) -> str | BaseModel: Shorthand for chatas_tool(name, description, message_db) -> Callable: Convert agent to tool
Parameters:
name: Agent identifier (default: "default_agent")system_prompt: Instructions for the agent behaviormodel: OpenAI model to use (default: "gpt-4.1-mini")client: Custom AsyncOpenAI client instancetools: List of function toolsmcp_servers: MCP server URLs for dynamic tool loading
๐ฌ Session
Manages conversation history and persistence with operations.
Session(
user_id: str,
session_id: Optional[str] = None,
message_db: Optional[MessageDB] = None
)
Key Methods:
async add_messages(messages: Message | List[Message]) -> None: Store messagesasync get_messages(count: int = 20) -> List[Message]: Retrieve message historyasync clear_session() -> None: Clear conversation historyasync pop_message() -> Optional[Message]: Remove last non-tool message
๐๏ธ MessageDB
Redis-backed message persistence layer.
# Initialize with environment variables or defaults
message_db = MessageDB()
# Usage with session
session = Session(
user_id="user123",
message_db=message_db
)
Important Considerations
| Aspect | Details |
|---|---|
| Tool functions | Can be sync or async (automatic conversion) |
| Agent interactions | Always use await |
| Context | Run in context with asyncio.run() |
| Concurrency | All tools execute in parallel automatically |
๐ Monitoring & Observability
xAgent includes comprehensive observability features:
- ๐ Langfuse Integration - Track AI interactions and performance
- ๐ Structured Logging - Throughout the entire system
- โค๏ธ Health Checks - API monitoring endpoints
- โก Performance Metrics - Tool execution time and success rates
๐ค Contributing
We welcome contributions! Here's how to get started:
Development Workflow
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
Development Guidelines
| Area | Requirements |
|---|---|
| Code Style | Follow PEP 8 standards |
| Testing | Add tests for new features |
| Documentation | Update docs as needed |
| Type Safety | Use type hints throughout |
| Commits | Follow conventional commit messages |
Package Upload
First time upload
pip install build twine
python -m build
twine upload dist/*
Subsequent uploads
rm -rf dist/ build/ *.egg-info/
python -m build
twine upload dist/*
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
Special thanks to the amazing open source projects that make xAgent possible:
- OpenAI - GPT models powering our AI
- FastAPI - Robust async API framework
- Streamlit - Intuitive web interface
- Redis - High-performance data storage
- Langfuse - Observability and monitoring
๐ Support & Community
| Resource | Link | Purpose |
|---|---|---|
| ๐ Issues | GitHub Issues | Bug reports & feature requests |
| ๐ฌ Discussions | GitHub Discussions | Community chat & Q&A |
| ๐ง Email | zhangjun310@live.com | Direct support |
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file myxagent-0.1.6.tar.gz.
File metadata
- Download URL: myxagent-0.1.6.tar.gz
- Upload date:
- Size: 41.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4525094d2f99430c3e60dfb95a59d2865743e959e9e11400079f71d761754428
|
|
| MD5 |
6786bea93afbd38b73aab4e235381f27
|
|
| BLAKE2b-256 |
db7265b5a8b38b14ec0029d974d495a20a9c88dd202569e0bdc3ec442bbb25a8
|
File details
Details for the file myxagent-0.1.6-py3-none-any.whl.
File metadata
- Download URL: myxagent-0.1.6-py3-none-any.whl
- Upload date:
- Size: 46.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c9f3c7be63a95929f011970e388611bbe6174fd3650f35a2779769bb03b112e5
|
|
| MD5 |
8daba1d6a5a96937a4c8e8fcc0d86020
|
|
| BLAKE2b-256 |
2e219eef9b6622b1b4b64d14ca65fce4af650f980e346c4fa1bf0fa1065c4ebb
|