Name | myxagent JSON |
Version |
0.2.16
JSON |
| download |
home_page | None |
Summary | Multi-Modal AI Agent System |
upload_time | 2025-08-22 08:27:43 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.10 |
license | MIT |
keywords |
ai
agent
openai
chatbot
async
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# xAgent - Multi-Modal AI Agent System
[](https://www.python.org/)
[](https://fastapi.tiangolo.com/)
[](https://streamlit.io/)
[](https://redis.io/)
[](LICENSE)
> **๐ A powerful and easy-to-use AI Agent system with real-time streaming responses**
xAgent provides a complete AI assistant experience with text and image processing, tool execution, HTTP server, web interface, and streaming CLI. **Production-ready with full multi-user and multi-session support** - perfect for both quick prototypes and enterprise deployments.
Also includes advanced features like multi-agent workflows even with **intelligent automatic workflow generation** that analyzes your task and creates optimal multi-agent coordination patterns.
## ๐ Table of Contents
- [๐ Quick Start](#-quick-start)
- [๐ง Installation](#-installation)
- [๐ HTTP Server](#-http-server)
- [๐ Web Interface](#-web-interface)
- [๐ป Command Line Interface](#-command-line-interface)
- [๐ค Python API](#-python-api)
- [๐ Multi-Agent Workflows](#-multi-agent-workflows)
- [๐ Documentation](#-documentation)
- [๐ค Contributing](#-contributing)
- [๐ License](#-license)
## ๐ Quick Start
Get up and running with xAgent in just a few commands:
```bash
# Install xAgent
pip install myxagent
# Set your OpenAI API key
export OPENAI_API_KEY=your_openai_api_key
# Start interactive CLI chat with default agent
xagent-cli
# Or quickly ask a question
xagent-cli --ask "who are you?"
xagent-cli --ask "what's the weather in Hangzhou and Shanghai?" -v
```
That's it!
### Starting the HTTP Server
The easiest way to deploy xAgent in production is through the HTTP server. **Production-ready with full multi-user and multi-session support** - handle thousands of concurrent users with isolated conversation histories.
```bash
# Start the HTTP server with default agent configuration
xagent-server
# Server runs at http://localhost:8010
```
> if you want to customize the agent, read more at [๐ HTTP Server](#-http-server)
Chat via HTTP API
```bash
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?"
}'
```
Or launch web interface
```bash
xagent-web
```
### Docker Deployment
For production deployments, you can use Docker to run xAgent with all dependencies.
Find the Docker setup in the `deploy/docker/` directory. See the [Docker README](deploy/docker/README.md) for detailed instructions.
## ๐ง Installation
### Prerequisites
- **Python 3.12+**
- **OpenAI API Key**
### Install from PyPI
```bash
# Latest version
pip install myxagent
# Upgrade existing installation
pip install --upgrade myxagent
# Using different mirrors
pip install myxagent -i https://pypi.org/simple
pip install myxagent -i https://mirrors.aliyun.com/pypi/simple # China users
```
### Environment Setup
Create a `.env` file in your project directory:
```bash
# Required
OPENAI_API_KEY=your_openai_api_key
# Redis persistence
REDIS_URL=your_redis_url_with_password
# Observability
LANGFUSE_SECRET_KEY=your_langfuse_key
LANGFUSE_PUBLIC_KEY=your_langfuse_public_key
LANGFUSE_HOST=https://cloud.langfuse.com
# 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
```
## ๐ HTTP Server
Here's how to run the xAgent HTTP server:
### Quick Start
```bash
# Start with default settings
xagent-server
# Server runs at http://localhost:8010
```
<details>
<summary><b>Initialize Project Config (Automatic)</b></summary>
Create default config and toolkit structure, run below command:
```bash
xagent-cli --init
```
This creates:
- `config/agent.yaml` - Configuration file
- `my_toolkit/` - Custom tools directory with examples
</details>
### Basic Configuration
Create `agent_config.yaml`:
```yaml
agent:
name: "MyAgent"
system_prompt: "You are a helpful assistant"
model: "gpt-4.1-mini"
capabilities:
tools:
- "web_search" # Built-in web search
- "draw_image" # Built-in image generation (need set aws credentials for image upload)
- "custom_tool" # Your custom tools
mcp_servers:
- "http://localhost:8001/mcp/" # Example MCP server
server:
host: "0.0.0.0"
port: 8010
```
For advanced configurations including structured outputs and multi-agent systems, see [Configuration Reference](docs/configuration_reference.md).
### Custom Tools
Create `my_toolkit/` directory with `__init__.py` and `tools.py`:
```python
# my_toolkit/__init__.py
from .tools import *
TOOLKIT_REGISTRY = {
"calculate_square": calculate_square,
"fetch_weather": fetch_weather
}
# my_toolkit/tools.py
import asyncio
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()
async def fetch_weather(city: str) -> str:
"""Fetch weather data from an API."""
# Simulate API call
await asyncio.sleep(0.5)
return f"Weather in {city}: 22ยฐC, Sunny"
```
### Start with Custom Config
```bash
# Use the generated config and toolkit
xagent-server --config config/agent.yaml --toolkit_path my_toolkit
```
### API Usage
```bash
# Multi-user chat examples
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"
}'
# Different user, different session
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "alice",
"session_id": "work_session",
"user_message": "What is the weather in Tokyo?"
}'
# Same user, different session for separate conversation
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "alice",
"session_id": "personal_session",
"user_message": "Help me plan a vacation"
}'
# Image analysis with URL
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "alice",
"session_id": "image_session",
"user_message": "What do you see in this image?",
"image_source": "https://example.com/image.jpg"
}'
# Multiple images can be sent as a list
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "alice",
"session_id": "image_session",
"user_message": "What do you see in these images?",
"image_source": [
"https://example.com/image1.jpg",
"https://example.com/image2.jpg"
]
}'
# Streaming response for any user/session
curl -X POST "http://localhost:8010/chat" \
-H "Content-Type: application/json" \
-d '{
"user_id": "bob",
"session_id": "session789",
"user_message": "Tell me a story",
"stream": true
}'
```
## ๐ Web Interface
User-friendly Streamlit chat interface for interactive conversations with your AI agent.
```bash
# Start the chat interface with default settings
xagent-web
# With custom agent server URL
xagent-web --agent-server http://localhost:8010
# With custom host and port
xagent-web --host 0.0.0.0 --port 8501 --agent-server http://localhost:8010
```
## ๐ป Command Line Interface
Interactive CLI with real-time streaming for quick testing and development.
### Basic Usage
```bash
# Interactive chat mode (default with streaming)
xagent-cli
# Ask a single question
xagent-cli --ask "What is the capital of France?"
# Use custom configuration
xagent-cli --config my_config.yaml --toolkit_path my_toolkit
```
### Interactive Chat Session
```bash
$ xagent-cli
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ค Welcome to xAgent CLI! โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
๐ Config: Default configuration
๐ค Agent: Agent
๐ง Model: gpt-4o-mini
๐ ๏ธ Tools: 1 loaded
๐ Session: cli_session_d02daf21
โ๏ธ Status: ๐ Verbose: Off | ๐ Stream: On
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Quick Start:
โข Type your message to chat with the agent
โข Use 'help' to see all available commands
โข Use 'exit', 'quit', or 'bye' to end session
โข Use 'clear' to reset conversation history
โข Use 'stream on/off' to toggle response streaming
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ค You: Hello, how are you?
๐ค Agent: Hello! I'm doing well, thank you for asking...
๐ค You: help
โญโ ๐ Commands โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ exit, quit, bye Exit the chat session โ
โ clear Clear conversation history โ
โ stream on/off Toggle streaming response mode โ
โ help Show this help message โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โญโ ๐ง Built-in Tools โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ 1. web_search โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
๐ค You: exit
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ ๐ Thank you for using xAgent CLI! โ
โ See you next time! ๐ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
```
### CLI Options
| Option | Description | Example |
|--------|-------------|---------|
| `--config` | Configuration file path | `--config my_config.yaml` |
| `--toolkit_path` | Custom toolkit directory | `--toolkit_path my_toolkit` |
| `--user_id` | User ID for session | `--user_id user123` |
| `--session_id` | Session ID for chat | `--session_id session456`
| `--ask` | Ask single question and exit | `--ask "Hello world"` |
| `--init` | Create default config and toolkit | `--init` |
| `--verbose`, `-v` | Enable verbose logging | `--verbose` |
## ๐ค Python API
Use xAgent directly in your Python applications with full control and customization.
### Basic Usage
```python
import asyncio
from xagent.core import Agent
async def main():
# Create agent
agent = Agent(
name="my_assistant",
system_prompt="You are a helpful AI assistant.",
model="gpt-4.1-mini"
)
# Text chat interaction
response = await agent.chat(
user_message="Hello, how are you?",
user_id="user123",
session_id="session456"
)
print(response)
# Image analysis with URL
response = await agent.chat(
user_message="What do you see in this image?",
user_id="user123",
session_id="session456",
image_source="https://example.com/image.jpg"
)
print(response)
# Multiple images can be sent as a list
response = await agent.chat(
user_message="What do you see in these images?",
user_id="user123",
session_id="session456",
image_source=[
"https://example.com/image1.jpg",
"https://example.com/image2.jpg"
]
)
print(response)
asyncio.run(main())
```
### Streaming Responses
```python
async def streaming_example():
agent = Agent()
response = await agent.chat(
user_message="Tell me a story",
user_id="user123",
session_id="session456",
stream=True
)
async for chunk in response:
print(chunk, end="")
asyncio.run(streaming_example())
```
### Adding Custom Tools
```python
import asyncio
import time
import httpx
from xagent.utils.tool_decorator import function_tool
from xagent.core import Agent
# 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"
)
# Agent handles all tools automatically
response = await agent.chat(
user_message="Calculate the square of 15 and get weather for Tokyo",
user_id="user123",
session_id="session456"
)
print(response)
asyncio.run(main())
```
### Structured Outputs
With Pydantic structured outputs, you can:
- Parse and validate an agentโs response into typed data
- Easily extract specific fields
- Ensure the response matches the expected format
- Guarantee type safety in your application
- Reliably chain multi-step tasks using structured data
```python
import asyncio
from pydantic import BaseModel
from xagent.core import Agent
from xagent.tools import web_search
class WeatherReport(BaseModel):
location: str
temperature: int
condition: str
humidity: int
class Step(BaseModel):
explanation: str
output: str
class MathReasoning(BaseModel):
steps: list[Step]
final_answer: str
async def get_structured_response():
agent = Agent(model="gpt-4.1-mini",
tools=[web_search],
output_type=WeatherReport) # You can set a default output type here or leave it None
# Request structured output for weather
weather_data = await agent.chat(
user_message="what's the weather like in Hangzhou?",
user_id="user123",
session_id="session456"
)
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}%")
# Request structured output for mathematical reasoning (overrides output_type)
reply = await agent.chat(
user_message="how can I solve 8x + 7 = -23",
user_id="user123",
session_id="session456",
output_type=MathReasoning
) # Override output_type for this call
for index, step in enumerate(reply.steps):
print(f"Step {index + 1}: {step.explanation} => Output: {step.output}")
print("Final Answer:", reply.final_answer)
if __name__ == "__main__":
asyncio.run(get_structured_response())
```
### Agent as Tool Pattern
```python
import asyncio
from xagent.core import Agent
from xagent.components import MessageStorageLocal
from xagent.tools import web_search
async def agent_as_tool_example():
# Create specialized agents with message storage
message_storage = MessageStorageLocal()
researcher_agent = Agent(
name="research_specialist",
system_prompt="Research expert. Gather information and provide insights.",
model="gpt-4.1-mini",
tools=[web_search],
message_storage=message_storage
)
# Convert agent to tool
research_tool = researcher_agent.as_tool(
name="researcher",
description="Research topics and provide detailed analysis"
)
# 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",
message_storage=message_storage
)
# Complex multi-step task
response = await coordinator.chat(
user_message="Research renewable energy benefits and write a brief summary",
user_id="user123",
session_id="session456"
)
print(response)
asyncio.run(agent_as_tool_example())
```
### Persistent Sessions with Redis
```python
import asyncio
from xagent.core import Agent
from xagent.components import MessageStorageRedis
async def chat_with_persistence():
# Initialize Redis-backed message storage
message_storage = MessageStorageRedis()
# Create agent with Redis persistence
agent = Agent(
name="persistent_agent",
model="gpt-4.1-mini",
message_storage=message_storage
)
# Chat with automatic message persistence
response = await agent.chat(
user_message="Remember this: my favorite color is blue",
user_id="user123",
session_id="persistent_session"
)
print(response)
# Later conversation - context is preserved in Redis
response = await agent.chat(
user_message="What's my favorite color?",
user_id="user123",
session_id="persistent_session"
)
print(response)
asyncio.run(chat_with_persistence())
```
you can implement your own message storage by inheriting from `MessageStorageBase` and implementing the required methods like `add_messages`, `get_messages`, etc.
For detailed guidance, see the [Message Storage Inheritance](docs/message_storage_inheritance.md) documentation.
### HTTP Server with Agent Instance
Launch an HTTP server by directly passing a pre-configured Agent instance:
```python
import asyncio
from xagent.core import Agent
from xagent.interfaces.server import AgentHTTPServer
from xagent.tools import web_search
# Create a custom agent with specific tools and configuration
agent = Agent(
name="MyCustomAgent",
system_prompt="You are a helpful research assistant specialized in web search and analysis.",
model="gpt-4o",
tools=[web_search]
)
# Start HTTP server with the agent
server = AgentHTTPServer(agent=agent)
server.run(host="0.0.0.0", port=8010)
# Server is now running at http://localhost:8010
# You can interact via API:
# curl -X POST "http://localhost:8010/chat" \
# -H "Content-Type: application/json" \
# -d '{"user_id": "user123", "session_id": "session456", "user_message": "Hello!"}'
```
## ๐ Multi-Agent Workflows
xAgent features **intelligent automatic workflow generation** that analyzes your task and creates optimal multi-agent coordination patterns.
### Workflow Patterns
| Pattern | Use Case | Setup Required | AI Optimization |
|---------|----------|----------------|-----------------|
| **Auto** | Any complex task | None - just describe the task | Full AI analysis and optimization |
| **Sequential** | Pipeline processing | Manual agent design | None |
| **Parallel** | Multiple perspectives | Manual agent design | None |
| **Graph** | Complex dependencies | Manual agent + dependency design | None |
| **Hybrid** | Multi-stage workflows | Manual stage configuration | None |
### Quick Start Examples
### ๐ Auto Workflow (AI-Powered)
Zero configuration required - AI automatically creates optimal agent teams:
```python
import asyncio
from xagent.multi.workflow import Workflow
async def auto_workflow_example():
workflow = Workflow()
# AI creates optimal agents and dependencies automatically
result = await workflow.run_auto(
task="Develop a comprehensive go-to-market strategy for a new SaaS product targeting healthcare providers"
)
print(f"โ
AI created {result.metadata['agent_count']} specialized agents:")
for agent in result.metadata['generated_agents']:
print(f" โข {agent['name']}: {agent['system_prompt'][:80]}...")
print(f"๐ Generated dependencies: {result.metadata['generated_dependencies']}")
print(f"๐ง AI reasoning: {result.metadata['agent_selection_reasoning']}")
print(f"๐ Result: {result.result}")
asyncio.run(auto_workflow_example())
```
<details>
<summary><b>๐ค Agent Definitions (Click to expand)</b></summary>
```python
from xagent import Agent
# Market Research Specialist
market_researcher = Agent(
name="MarketResearcher",
system_prompt="""You are a senior market research analyst with 10+ years of experience.
Your expertise includes:
- Industry trend analysis and forecasting
- Competitive landscape assessment
- Market size estimation and growth projections
- Consumer behavior analysis
- Technology adoption patterns
Always provide data-driven insights with specific metrics, sources, and actionable recommendations.""",
model="gpt-4o"
)
# Data Science Specialist
data_scientist = Agent(
name="DataScientist",
system_prompt="""You are a senior data scientist specializing in business intelligence and predictive analytics.
Your core competencies:
- Statistical analysis and hypothesis testing
- Predictive modeling and machine learning
- Data visualization and storytelling
- Risk assessment and scenario planning
- Performance metrics and KPI development
Transform raw research into quantitative insights, identify patterns, and build predictive models.""",
model="gpt-4o"
)
# Business Writing Specialist
business_writer = Agent(
name="BusinessWriter",
system_prompt="""You are an executive business writer and strategic communications expert.
Your specializations:
- Executive summary creation
- Strategic recommendation development
- Stakeholder communication
- Risk and opportunity assessment
- Implementation roadmap design
Create compelling, actionable business reports that drive decision-making at the C-level.""",
model="gpt-4o"
)
# Financial Analysis Specialist
financial_analyst = Agent(
name="FinancialAnalyst",
system_prompt="""You are a CFA-certified financial analyst with expertise in valuation and investment analysis.
Your focus areas:
- Financial modeling and valuation
- Investment risk assessment
- ROI and NPV calculations
- Capital allocation strategies
- Market opportunity sizing
Provide detailed financial analysis with concrete numbers, projections, and investment recommendations.""",
model="gpt-4o"
)
# Strategy Consulting Specialist
strategy_consultant = Agent(
name="StrategyConsultant",
system_prompt="""You are a senior strategy consultant from a top-tier consulting firm.
Your expertise includes:
- Strategic planning and execution
- Business model innovation
- Competitive strategy development
- Organizational transformation
- Change management
Synthesize complex information into clear strategic recommendations with implementation timelines.""",
model="gpt-4o"
)
# Quality Assurance Specialist
quality_reviewer = Agent(
name="QualityReviewer",
system_prompt="""You are a senior partner-level consultant specializing in quality assurance and risk management.
Your responsibilities:
- Strategic recommendation validation
- Risk identification and mitigation
- Stakeholder impact assessment
- Implementation feasibility review
- Compliance and regulatory considerations
Ensure all recommendations are practical, well-researched, and aligned with business objectives.""",
model="gpt-4o"
)
```
</details>
### ๐ Sequential Workflow
Pipeline processing where each agent builds on the previous output:
```python
import asyncio
from xagent.multi.workflow import Workflow
async def sequential_workflow_example():
workflow = Workflow()
# Research โ Analysis โ Report Pipeline
result = await workflow.run_sequential(
agents=[market_researcher, data_scientist, business_writer],
task="Analyze the electric vehicle charging infrastructure market opportunity in North America for 2024-2027"
)
print("Sequential Pipeline Result:", result.result)
asyncio.run(sequential_workflow_example())
```
### ๐ Parallel Workflow
Multiple expert perspectives on the same challenge:
```python
import asyncio
from xagent.multi.workflow import Workflow
async def parallel_workflow_example():
workflow = Workflow()
# Multiple experts analyze the same problem simultaneously
# Note: Can set output_type for structured consensus validation
result = await workflow.run_parallel(
agents=[financial_analyst, strategy_consultant, data_scientist],
task="Evaluate the investment potential and strategic implications of generative AI adoption in enterprise software companies"
)
print("Expert Panel Analysis:", result.result)
asyncio.run(parallel_workflow_example())
```
### ๐ธ๏ธ Graph Workflow
Complex dependency networks with conditional execution:
```python
import asyncio
from xagent.multi.workflow import Workflow
async def graph_workflow_example():
workflow = Workflow()
# Complex dependency analysis
dependencies = "MarketResearcher->DataScientist, MarketResearcher->FinancialAnalyst, DataScientist&FinancialAnalyst->StrategyConsultant, StrategyConsultant->BusinessWriter"
result = await workflow.run_graph(
agents=[market_researcher, data_scientist, financial_analyst, strategy_consultant, business_writer],
dependencies=dependencies,
task="Develop a comprehensive go-to-market strategy for a B2B SaaS startup entering the healthcare analytics space"
)
print("Strategic Analysis Result:", result.result)
asyncio.run(graph_workflow_example())
```
### ๐ Hybrid Workflow
Multi-stage workflows combining different patterns:
```python
import asyncio
from xagent.multi.workflow import Workflow
async def hybrid_workflow_example():
workflow = Workflow()
# Multi-stage comprehensive business analysis
# Note: Tasks can include placeholders like {previous_result} and {original_task}
stages = [
{
"pattern": "sequential",
"agents": [market_researcher, financial_analyst],
"task": "Conduct market and financial analysis for: {original_task}",
"name": "market_financial_analysis"
},
{
"pattern": "parallel",
"agents": [data_scientist, strategy_consultant],
"task": "Analyze strategic implications and develop data-driven insights based on: {previous_result}",
"name": "strategic_data_analysis"
},
{
"pattern": "graph",
"agents": [business_writer, quality_reviewer, strategy_consultant],
"dependencies": "BusinessWriter->QualityReviewer, StrategyConsultant->QualityReviewer",
"task": "Create final strategic report with quality validation from: {previous_result}",
"name": "report_synthesis_validation"
}
]
result = await workflow.run_hybrid(
task="Develop a digital transformation strategy for a traditional manufacturing company looking to implement IoT and predictive maintenance solutions",
stages=stages
)
print("Comprehensive Strategy Report:", result["final_result"])
asyncio.run(hybrid_workflow_example())
```
### DSL Syntax
Use intuitive arrow notation for complex dependencies:
```python
# Simple chain
"A->B->C"
# Parallel branches
"A->B, A->C"
# Fan-in pattern
"A->C, B->C"
# Complex dependencies
"A->B, A->C, B&C->D"
```
For detailed workflow patterns and examples, see [Multi-Agent Workflows](docs/workflows.md) and [Workflow DSL](docs/workflow_dsl.md).
## ๐ Documentation
### Core Documentation
- [Configuration Reference](docs/configuration_reference.md) - Complete YAML configuration guide and examples
- [API Reference](docs/api_reference.md) - Complete API documentation and parameter reference
- [Multi-Agent Workflows](docs/workflows.md) - Workflow patterns and orchestration examples
- [Workflow DSL](docs/workflow_dsl.md) - Domain-specific language for defining agent dependencies
### Examples
- [examples/demo](examples/demo) - Complete usage examples and demos
- [examples/config/](examples/config/) - Configuration file templates
- [examples/toolkit/](examples/toolkit/) - Custom tool development examples
### Deployment
- [deploy/docker/](deploy/docker/) - Production deployment with Docker and Docker Compose
### Architecture Overview
xAgent is built with a modular architecture:
- **Core (`xagent/core/`)** - Agent and session management
- **Interfaces (`xagent/interfaces/`)** - CLI, HTTP server, and web interface
- **Components (`xagent/components/`)** - Message storage and persistence
- **Tools (`xagent/tools/`)** - Built-in and custom tool ecosystem
- **Multi (`xagent/multi/`)** - Multi-agent coordination and workflows
### Key Features
- **๐ Auto Workflow** - Revolutionary AI-powered automatic workflow generation with zero configuration
- **๐ข Production Ready** - Multi-user and multi-session support with enterprise-grade reliability
- **๐ฅ Multi-User Support** - Concurrent user handling with isolated sessions and conversation histories
- **๐ Multi-Session Management** - Each user can maintain multiple independent conversation sessions
- **๐ Easy to Use** - Simple API for quick prototyping
- **โก High Performance** - Async/await throughout, concurrent tool execution
- **๐ง Intelligent Agent Design** - AI creates optimal specialist teams (2-6 agents) based on task complexity
- **๐ Smart Dependencies** - Automatic dependency optimization for maximum parallel execution
- **๐ง Extensible** - Custom tools, MCP integration, plugin system
- **๐ Multiple Interfaces** - CLI, HTTP API, web interface
- **๐พ Persistent** - Redis-backed conversation storage
- **๐ค Multi-Agent** - Hierarchical agent systems and workflows
- **๐ Observable** - Built-in logging and monitoring
**Key Methods:**
- `async chat(user_message, user_id, session_id, **kwargs) -> str | BaseModel`: Main chat interface
- `async __call__(user_message, user_id, session_id, **kwargs) -> str | BaseModel`: Shorthand for chat
- `as_tool(name, description) -> Callable`: Convert agent to tool
**Chat Method Parameters:**
- `user_message`: The user's message (string or Message object)
- `user_id`: User identifier for message storage (default: "default_user")
- `session_id`: Session identifier for message storage (default: "default_session")
- `history_count`: Number of previous messages to include (default: 16)
- `max_iter`: Maximum model call attempts (default: 10)
- `image_source`: Optional image(s) for analysis (URL, path, or base64)
- `output_type`: Pydantic model for structured output
- `stream`: Enable streaming response (default: False)
**Agent Parameters:**
- `name`: Agent identifier (default: "default_agent")
- `system_prompt`: Instructions for the agent behavior
- `model`: OpenAI model to use (default: "gpt-4.1-mini")
- `client`: Custom AsyncOpenAI client instance
- `tools`: List of function tools
- `mcp_servers`: MCP server URLs for dynamic tool loading
- `sub_agents`: List of sub-agent configurations (name, description, server URL)
## ๐ค Contributing
We welcome contributions! Here's how to get started:
### Development Workflow
1. **Fork** the repository
2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
3. **Commit** your changes: `git commit -m 'Add amazing feature'`
4. **Push** to the branch: `git push origin feature/amazing-feature`
5. **Open** a Pull Request
### Development Guidelines
- Follow PEP 8 standards for code style
- Add tests for new features
- Update documentation as needed
- Use type hints throughout
- Follow conventional commit messages
## ๐ License
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
## ๐ Acknowledgments
Special thanks to these amazing open source projects:
- **[OpenAI](https://openai.com/)** - GPT models powering our AI
- **[FastAPI](https://fastapi.tiangolo.com/)** - Robust async API framework
- **[Streamlit](https://streamlit.io/)** - Intuitive web interface
- **[Redis](https://redis.io/)** - High-performance data storage
## ๐ Support & Community
| Resource | Purpose |
|----------|---------|
| **[GitHub Issues](https://github.com/ZJCODE/xAgent/issues)** | Bug reports & feature requests |
| **[GitHub Discussions](https://github.com/ZJCODE/xAgent/discussions)** | Community chat & Q&A |
| **Email: zhangjun310@live.com** | Direct support |
---
<div align="center">
**xAgent** - Empowering conversations with AI ๐
[](https://github.com/ZJCODE/xAgent)
[](https://github.com/ZJCODE/xAgent)
*Built with โค๏ธ for the AI community*
</div>
Raw data
{
"_id": null,
"home_page": null,
"name": "myxagent",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "ai, agent, openai, chatbot, async",
"author": null,
"author_email": "ZJun <zhangjun310@live.com>",
"download_url": "https://files.pythonhosted.org/packages/96/3e/b46af880d6481d22e3303d7fe4b9c681e01de28e8e4a08fdf56bb8c7b0cd/myxagent-0.2.16.tar.gz",
"platform": null,
"description": "# xAgent - Multi-Modal AI Agent System\n\n[](https://www.python.org/)\n[](https://fastapi.tiangolo.com/)\n[](https://streamlit.io/)\n[](https://redis.io/)\n[](LICENSE)\n\n> **\ud83d\ude80 A powerful and easy-to-use AI Agent system with real-time streaming responses**\n\nxAgent provides a complete AI assistant experience with text and image processing, tool execution, HTTP server, web interface, and streaming CLI. **Production-ready with full multi-user and multi-session support** - perfect for both quick prototypes and enterprise deployments.\n\nAlso includes advanced features like multi-agent workflows even with **intelligent automatic workflow generation** that analyzes your task and creates optimal multi-agent coordination patterns.\n\n## \ud83d\udccb Table of Contents\n\n- [\ud83d\ude80 Quick Start](#-quick-start)\n- [\ud83d\udd27 Installation](#-installation)\n- [\ud83c\udf10 HTTP Server](#-http-server)\n- [\ud83c\udf10 Web Interface](#-web-interface)\n- [\ud83d\udcbb Command Line Interface](#-command-line-interface)\n- [\ud83e\udd16 Python API](#-python-api)\n- [\ud83d\udd04 Multi-Agent Workflows](#-multi-agent-workflows)\n- [\ud83d\udcda Documentation](#-documentation)\n- [\ud83e\udd1d Contributing](#-contributing)\n- [\ud83d\udcc4 License](#-license)\n\n\n## \ud83d\ude80 Quick Start\n\nGet up and running with xAgent in just a few commands:\n\n```bash\n# Install xAgent\npip install myxagent\n\n# Set your OpenAI API key\nexport OPENAI_API_KEY=your_openai_api_key\n\n# Start interactive CLI chat with default agent \nxagent-cli\n\n# Or quickly ask a question\nxagent-cli --ask \"who are you?\"\nxagent-cli --ask \"what's the weather in Hangzhou and Shanghai?\" -v\n\n```\n\nThat's it!\n\n### Starting the HTTP Server\n\nThe easiest way to deploy xAgent in production is through the HTTP server. **Production-ready with full multi-user and multi-session support** - handle thousands of concurrent users with isolated conversation histories.\n\n```bash\n# Start the HTTP server with default agent configuration\nxagent-server\n\n# Server runs at http://localhost:8010\n```\n\n> if you want to customize the agent, read more at [\ud83c\udf10 HTTP Server](#-http-server)\n\nChat via HTTP API\n\n```bash\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"user123\",\n \"session_id\": \"session456\", \n \"user_message\": \"Hello, how are you?\"\n }'\n```\n\nOr launch web interface\n\n```bash\nxagent-web\n```\n\n### Docker Deployment\n\nFor production deployments, you can use Docker to run xAgent with all dependencies.\n\nFind the Docker setup in the `deploy/docker/` directory. See the [Docker README](deploy/docker/README.md) for detailed instructions.\n\n## \ud83d\udd27 Installation\n\n### Prerequisites\n\n- **Python 3.12+**\n- **OpenAI API Key**\n\n### Install from PyPI\n\n```bash\n# Latest version\npip install myxagent\n\n# Upgrade existing installation\npip install --upgrade myxagent\n\n# Using different mirrors\npip install myxagent -i https://pypi.org/simple\npip install myxagent -i https://mirrors.aliyun.com/pypi/simple # China users\n```\n\n### Environment Setup\n\nCreate a `.env` file in your project directory:\n\n```bash\n# Required\nOPENAI_API_KEY=your_openai_api_key\n\n# Redis persistence\nREDIS_URL=your_redis_url_with_password\n\n# Observability\nLANGFUSE_SECRET_KEY=your_langfuse_key\nLANGFUSE_PUBLIC_KEY=your_langfuse_public_key\nLANGFUSE_HOST=https://cloud.langfuse.com\n\n# Image upload to S3\nAWS_ACCESS_KEY_ID=your_aws_access_key_id\nAWS_SECRET_ACCESS_KEY=your_aws_secret_access_key\nAWS_REGION=us-east-1\nBUCKET_NAME=your_bucket_name\n```\n\n\n## \ud83c\udf10 HTTP Server\n\nHere's how to run the xAgent HTTP server: \n\n\n### Quick Start\n\n```bash\n# Start with default settings\nxagent-server\n\n# Server runs at http://localhost:8010\n```\n\n<details>\n<summary><b>Initialize Project Config (Automatic)</b></summary>\n\nCreate default config and toolkit structure, run below command:\n\n```bash \nxagent-cli --init\n```\n\nThis creates:\n- `config/agent.yaml` - Configuration file\n- `my_toolkit/` - Custom tools directory with examples\n</details>\n\n\n### Basic Configuration\n\nCreate `agent_config.yaml`:\n\n```yaml\nagent:\n name: \"MyAgent\"\n system_prompt: \"You are a helpful assistant\"\n model: \"gpt-4.1-mini\"\n capabilities:\n tools:\n - \"web_search\" # Built-in web search\n - \"draw_image\" # Built-in image generation (need set aws credentials for image upload)\n - \"custom_tool\" # Your custom tools\n mcp_servers:\n - \"http://localhost:8001/mcp/\" # Example MCP server\n\nserver:\n host: \"0.0.0.0\"\n port: 8010\n```\n\nFor advanced configurations including structured outputs and multi-agent systems, see [Configuration Reference](docs/configuration_reference.md).\n\n### Custom Tools\n\nCreate `my_toolkit/` directory with `__init__.py` and `tools.py`:\n\n```python\n# my_toolkit/__init__.py\nfrom .tools import *\n\nTOOLKIT_REGISTRY = {\n \"calculate_square\": calculate_square,\n \"fetch_weather\": fetch_weather\n}\n\n# my_toolkit/tools.py\nimport asyncio\nfrom xagent.utils.tool_decorator import function_tool\n\n@function_tool()\ndef calculate_square(n: int) -> int:\n \"\"\"Calculate the square of a number.\"\"\"\n return n * n\n\n@function_tool()\nasync def fetch_weather(city: str) -> str:\n \"\"\"Fetch weather data from an API.\"\"\"\n # Simulate API call\n await asyncio.sleep(0.5)\n return f\"Weather in {city}: 22\u00b0C, Sunny\"\n```\n\n### Start with Custom Config\n\n```bash\n# Use the generated config and toolkit\nxagent-server --config config/agent.yaml --toolkit_path my_toolkit\n```\n\n### API Usage\n\n```bash\n# Multi-user chat examples\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"user123\",\n \"session_id\": \"session456\", \n \"user_message\": \"Calculate the square of 15\"\n }'\n\n# Different user, different session\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"alice\",\n \"session_id\": \"work_session\", \n \"user_message\": \"What is the weather in Tokyo?\"\n }'\n\n# Same user, different session for separate conversation\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"alice\",\n \"session_id\": \"personal_session\", \n \"user_message\": \"Help me plan a vacation\"\n }'\n\n# Image analysis with URL\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"alice\",\n \"session_id\": \"image_session\", \n \"user_message\": \"What do you see in this image?\",\n \"image_source\": \"https://example.com/image.jpg\"\n }'\n\n# Multiple images can be sent as a list\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"alice\",\n \"session_id\": \"image_session\",\n \"user_message\": \"What do you see in these images?\",\n \"image_source\": [\n \"https://example.com/image1.jpg\",\n \"https://example.com/image2.jpg\"\n ]\n }'\n\n# Streaming response for any user/session\ncurl -X POST \"http://localhost:8010/chat\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"user_id\": \"bob\",\n \"session_id\": \"session789\",\n \"user_message\": \"Tell me a story\",\n \"stream\": true\n }'\n```\n\n\n## \ud83c\udf10 Web Interface\n\nUser-friendly Streamlit chat interface for interactive conversations with your AI agent.\n\n```bash\n# Start the chat interface with default settings\nxagent-web\n\n# With custom agent server URL\nxagent-web --agent-server http://localhost:8010\n\n# With custom host and port\nxagent-web --host 0.0.0.0 --port 8501 --agent-server http://localhost:8010\n```\n\n## \ud83d\udcbb Command Line Interface\n\nInteractive CLI with real-time streaming for quick testing and development.\n\n### Basic Usage\n\n```bash\n# Interactive chat mode (default with streaming)\nxagent-cli\n\n# Ask a single question\nxagent-cli --ask \"What is the capital of France?\"\n\n# Use custom configuration\nxagent-cli --config my_config.yaml --toolkit_path my_toolkit\n```\n\n### Interactive Chat Session\n\n```bash\n$ xagent-cli\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 \ud83e\udd16 Welcome to xAgent CLI! \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\ud83d\udcc1 Config: Default configuration\n\ud83e\udd16 Agent: Agent\n\ud83e\udde0 Model: gpt-4o-mini\n\ud83d\udee0\ufe0f Tools: 1 loaded\n\ud83d\udd17 Session: cli_session_d02daf21\n\u2699\ufe0f Status: \ud83d\udd07 Verbose: Off | \ud83c\udf0a Stream: On\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ud83d\ude80 Quick Start:\n \u2022 Type your message to chat with the agent\n \u2022 Use 'help' to see all available commands\n \u2022 Use 'exit', 'quit', or 'bye' to end session\n \u2022 Use 'clear' to reset conversation history\n \u2022 Use 'stream on/off' to toggle response streaming\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\ud83d\udc64 You: Hello, how are you?\n\ud83e\udd16 Agent: Hello! I'm doing well, thank you for asking...\n\n\ud83d\udc64 You: help\n\n\u256d\u2500 \ud83d\udccb Commands \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 exit, quit, bye Exit the chat session \u2502\n\u2502 clear Clear conversation history \u2502\n\u2502 stream on/off Toggle streaming response mode \u2502\n\u2502 help Show this help message \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\u256d\u2500 \ud83d\udd27 Built-in Tools \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 1. web_search \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n\n\ud83d\udc64 You: exit\n\n\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 \ud83d\udc4b Thank you for using xAgent CLI! \u2502\n\u2502 See you next time! \ud83d\ude80 \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n```\n\n### CLI Options\n\n| Option | Description | Example |\n|--------|-------------|---------|\n| `--config` | Configuration file path | `--config my_config.yaml` |\n| `--toolkit_path` | Custom toolkit directory | `--toolkit_path my_toolkit` |\n| `--user_id` | User ID for session | `--user_id user123` |\n| `--session_id` | Session ID for chat | `--session_id session456`\n| `--ask` | Ask single question and exit | `--ask \"Hello world\"` |\n| `--init` | Create default config and toolkit | `--init` |\n| `--verbose`, `-v` | Enable verbose logging | `--verbose` |\n\n## \ud83e\udd16 Python API\n\nUse xAgent directly in your Python applications with full control and customization.\n\n### Basic Usage\n\n```python\nimport asyncio\nfrom xagent.core import Agent\n\nasync def main():\n # Create agent\n agent = Agent(\n name=\"my_assistant\",\n system_prompt=\"You are a helpful AI assistant.\",\n model=\"gpt-4.1-mini\"\n )\n\n # Text chat interaction\n response = await agent.chat(\n user_message=\"Hello, how are you?\",\n user_id=\"user123\", \n session_id=\"session456\"\n )\n print(response)\n \n # Image analysis with URL\n response = await agent.chat(\n user_message=\"What do you see in this image?\",\n user_id=\"user123\",\n session_id=\"session456\",\n image_source=\"https://example.com/image.jpg\"\n )\n print(response)\n\n # Multiple images can be sent as a list\n response = await agent.chat(\n user_message=\"What do you see in these images?\",\n user_id=\"user123\",\n session_id=\"session456\",\n image_source=[\n \"https://example.com/image1.jpg\",\n \"https://example.com/image2.jpg\"\n ]\n )\n print(response)\n\nasyncio.run(main())\n```\n\n### Streaming Responses\n\n```python\nasync def streaming_example():\n agent = Agent()\n \n response = await agent.chat(\n user_message=\"Tell me a story\",\n user_id=\"user123\",\n session_id=\"session456\",\n stream=True\n )\n \n async for chunk in response:\n print(chunk, end=\"\")\n\nasyncio.run(streaming_example())\n```\n\n### Adding Custom Tools\n\n```python\nimport asyncio\nimport time\nimport httpx\nfrom xagent.utils.tool_decorator import function_tool\nfrom xagent.core import Agent\n\n# Sync tools - automatically converted to async\n@function_tool()\ndef calculate_square(n: int) -> int:\n \"\"\"Calculate square of a number.\"\"\"\n time.sleep(0.1) # Simulate CPU work\n return n * n\n\n# Async tools - used directly for I/O operations\n@function_tool()\nasync def fetch_weather(city: str) -> str:\n \"\"\"Fetch weather data from API.\"\"\"\n async with httpx.AsyncClient() as client:\n await asyncio.sleep(0.5) # Simulate API call\n return f\"Weather in {city}: 22\u00b0C, Sunny\"\n\nasync def main():\n # Create agent with custom tools\n agent = Agent(\n tools=[calculate_square, fetch_weather],\n model=\"gpt-4.1-mini\"\n )\n \n # Agent handles all tools automatically\n response = await agent.chat(\n user_message=\"Calculate the square of 15 and get weather for Tokyo\",\n user_id=\"user123\",\n session_id=\"session456\"\n )\n print(response)\n\nasyncio.run(main())\n```\n\n### Structured Outputs\n\nWith Pydantic structured outputs, you can:\n- Parse and validate an agent\u2019s response into typed data\n- Easily extract specific fields\n- Ensure the response matches the expected format\n- Guarantee type safety in your application\n- Reliably chain multi-step tasks using structured data\n\n```python\nimport asyncio\nfrom pydantic import BaseModel\nfrom xagent.core import Agent\nfrom xagent.tools import web_search\n\nclass WeatherReport(BaseModel):\n location: str\n temperature: int\n condition: str\n humidity: int\n\nclass Step(BaseModel):\n explanation: str\n output: str\n\nclass MathReasoning(BaseModel):\n steps: list[Step]\n final_answer: str\n\n\nasync def get_structured_response():\n \n agent = Agent(model=\"gpt-4.1-mini\", \n tools=[web_search], \n output_type=WeatherReport) # You can set a default output type here or leave it None\n \n # Request structured output for weather\n weather_data = await agent.chat(\n user_message=\"what's the weather like in Hangzhou?\",\n user_id=\"user123\",\n session_id=\"session456\"\n )\n \n print(f\"Location: {weather_data.location}\")\n print(f\"Temperature: {weather_data.temperature}\u00b0F\")\n print(f\"Condition: {weather_data.condition}\")\n print(f\"Humidity: {weather_data.humidity}%\")\n\n\n # Request structured output for mathematical reasoning (overrides output_type)\n reply = await agent.chat(\n user_message=\"how can I solve 8x + 7 = -23\",\n user_id=\"user123\",\n session_id=\"session456\",\n output_type=MathReasoning\n ) # Override output_type for this call\n for index, step in enumerate(reply.steps):\n print(f\"Step {index + 1}: {step.explanation} => Output: {step.output}\")\n print(\"Final Answer:\", reply.final_answer)\n\nif __name__ == \"__main__\":\n asyncio.run(get_structured_response())\n```\n\n### Agent as Tool Pattern\n\n```python\nimport asyncio\nfrom xagent.core import Agent\nfrom xagent.components import MessageStorageLocal\nfrom xagent.tools import web_search\n\nasync def agent_as_tool_example():\n # Create specialized agents with message storage\n message_storage = MessageStorageLocal()\n \n researcher_agent = Agent(\n name=\"research_specialist\",\n system_prompt=\"Research expert. Gather information and provide insights.\",\n model=\"gpt-4.1-mini\",\n tools=[web_search],\n message_storage=message_storage\n )\n \n # Convert agent to tool\n research_tool = researcher_agent.as_tool(\n name=\"researcher\",\n description=\"Research topics and provide detailed analysis\"\n )\n \n # Main coordinator agent with specialist tools\n coordinator = Agent(\n name=\"coordinator\",\n tools=[research_tool],\n system_prompt=\"Coordination agent that delegates to specialists.\",\n model=\"gpt-4.1\",\n message_storage=message_storage\n )\n \n # Complex multi-step task\n response = await coordinator.chat(\n user_message=\"Research renewable energy benefits and write a brief summary\",\n user_id=\"user123\",\n session_id=\"session456\"\n )\n print(response)\n\nasyncio.run(agent_as_tool_example())\n```\n\n### Persistent Sessions with Redis\n\n```python\nimport asyncio\nfrom xagent.core import Agent\nfrom xagent.components import MessageStorageRedis\n\nasync def chat_with_persistence():\n # Initialize Redis-backed message storage\n message_storage = MessageStorageRedis()\n \n # Create agent with Redis persistence\n agent = Agent(\n name=\"persistent_agent\",\n model=\"gpt-4.1-mini\",\n message_storage=message_storage\n )\n\n # Chat with automatic message persistence\n response = await agent.chat(\n user_message=\"Remember this: my favorite color is blue\",\n user_id=\"user123\",\n session_id=\"persistent_session\"\n )\n print(response)\n \n # Later conversation - context is preserved in Redis\n response = await agent.chat(\n user_message=\"What's my favorite color?\",\n user_id=\"user123\",\n session_id=\"persistent_session\"\n )\n print(response)\n\nasyncio.run(chat_with_persistence())\n```\n\nyou can implement your own message storage by inheriting from `MessageStorageBase` and implementing the required methods like `add_messages`, `get_messages`, etc.\n\nFor detailed guidance, see the [Message Storage Inheritance](docs/message_storage_inheritance.md) documentation.\n\n### HTTP Server with Agent Instance\n\nLaunch an HTTP server by directly passing a pre-configured Agent instance:\n\n```python\nimport asyncio\nfrom xagent.core import Agent\nfrom xagent.interfaces.server import AgentHTTPServer\nfrom xagent.tools import web_search\n\n# Create a custom agent with specific tools and configuration\nagent = Agent(\n name=\"MyCustomAgent\",\n system_prompt=\"You are a helpful research assistant specialized in web search and analysis.\",\n model=\"gpt-4o\",\n tools=[web_search]\n)\n\n# Start HTTP server with the agent\nserver = AgentHTTPServer(agent=agent)\nserver.run(host=\"0.0.0.0\", port=8010)\n\n# Server is now running at http://localhost:8010\n# You can interact via API:\n# curl -X POST \"http://localhost:8010/chat\" \\\n# -H \"Content-Type: application/json\" \\\n# -d '{\"user_id\": \"user123\", \"session_id\": \"session456\", \"user_message\": \"Hello!\"}'\n```\n\n\n## \ud83d\udd04 Multi-Agent Workflows\n\nxAgent features **intelligent automatic workflow generation** that analyzes your task and creates optimal multi-agent coordination patterns.\n\n### Workflow Patterns\n\n| Pattern | Use Case | Setup Required | AI Optimization |\n|---------|----------|----------------|-----------------|\n| **Auto** | Any complex task | None - just describe the task | Full AI analysis and optimization |\n| **Sequential** | Pipeline processing | Manual agent design | None |\n| **Parallel** | Multiple perspectives | Manual agent design | None |\n| **Graph** | Complex dependencies | Manual agent + dependency design | None |\n| **Hybrid** | Multi-stage workflows | Manual stage configuration | None |\n\n### Quick Start Examples\n\n\n### \ud83c\udf1f Auto Workflow (AI-Powered)\n\nZero configuration required - AI automatically creates optimal agent teams:\n\n```python\nimport asyncio\nfrom xagent.multi.workflow import Workflow\n\nasync def auto_workflow_example():\n workflow = Workflow()\n \n # AI creates optimal agents and dependencies automatically\n result = await workflow.run_auto(\n task=\"Develop a comprehensive go-to-market strategy for a new SaaS product targeting healthcare providers\"\n )\n \n print(f\"\u2705 AI created {result.metadata['agent_count']} specialized agents:\")\n for agent in result.metadata['generated_agents']:\n print(f\" \u2022 {agent['name']}: {agent['system_prompt'][:80]}...\")\n print(f\"\ud83d\udd17 Generated dependencies: {result.metadata['generated_dependencies']}\")\n print(f\"\ud83e\udde0 AI reasoning: {result.metadata['agent_selection_reasoning']}\")\n print(f\"\ud83d\udcca Result: {result.result}\")\n\nasyncio.run(auto_workflow_example())\n```\n\n\n<details>\n<summary><b>\ud83e\udd16 Agent Definitions (Click to expand)</b></summary>\n\n```python\nfrom xagent import Agent\n\n# Market Research Specialist\nmarket_researcher = Agent(\n name=\"MarketResearcher\",\n system_prompt=\"\"\"You are a senior market research analyst with 10+ years of experience. \n Your expertise includes:\n - Industry trend analysis and forecasting\n - Competitive landscape assessment\n - Market size estimation and growth projections\n - Consumer behavior analysis\n - Technology adoption patterns\n \n Always provide data-driven insights with specific metrics, sources, and actionable recommendations.\"\"\",\n model=\"gpt-4o\"\n)\n\n# Data Science Specialist\ndata_scientist = Agent(\n name=\"DataScientist\", \n system_prompt=\"\"\"You are a senior data scientist specializing in business intelligence and predictive analytics.\n Your core competencies:\n - Statistical analysis and hypothesis testing\n - Predictive modeling and machine learning\n - Data visualization and storytelling\n - Risk assessment and scenario planning\n - Performance metrics and KPI development\n \n Transform raw research into quantitative insights, identify patterns, and build predictive models.\"\"\",\n model=\"gpt-4o\"\n)\n\n# Business Writing Specialist\nbusiness_writer = Agent(\n name=\"BusinessWriter\",\n system_prompt=\"\"\"You are an executive business writer and strategic communications expert.\n Your specializations:\n - Executive summary creation\n - Strategic recommendation development\n - Stakeholder communication\n - Risk and opportunity assessment\n - Implementation roadmap design\n \n Create compelling, actionable business reports that drive decision-making at the C-level.\"\"\",\n model=\"gpt-4o\"\n)\n\n# Financial Analysis Specialist\nfinancial_analyst = Agent(\n name=\"FinancialAnalyst\",\n system_prompt=\"\"\"You are a CFA-certified financial analyst with expertise in valuation and investment analysis.\n Your focus areas:\n - Financial modeling and valuation\n - Investment risk assessment\n - ROI and NPV calculations\n - Capital allocation strategies\n - Market opportunity sizing\n \n Provide detailed financial analysis with concrete numbers, projections, and investment recommendations.\"\"\",\n model=\"gpt-4o\"\n)\n\n# Strategy Consulting Specialist\nstrategy_consultant = Agent(\n name=\"StrategyConsultant\",\n system_prompt=\"\"\"You are a senior strategy consultant from a top-tier consulting firm.\n Your expertise includes:\n - Strategic planning and execution\n - Business model innovation\n - Competitive strategy development\n - Organizational transformation\n - Change management\n \n Synthesize complex information into clear strategic recommendations with implementation timelines.\"\"\",\n model=\"gpt-4o\"\n)\n\n# Quality Assurance Specialist\nquality_reviewer = Agent(\n name=\"QualityReviewer\",\n system_prompt=\"\"\"You are a senior partner-level consultant specializing in quality assurance and risk management.\n Your responsibilities:\n - Strategic recommendation validation\n - Risk identification and mitigation\n - Stakeholder impact assessment\n - Implementation feasibility review\n - Compliance and regulatory considerations\n \n Ensure all recommendations are practical, well-researched, and aligned with business objectives.\"\"\",\n model=\"gpt-4o\"\n)\n```\n</details>\n\n### \ud83d\udccb Sequential Workflow\n\nPipeline processing where each agent builds on the previous output:\n\n```python\nimport asyncio\nfrom xagent.multi.workflow import Workflow\n\nasync def sequential_workflow_example():\n workflow = Workflow()\n \n # Research \u2192 Analysis \u2192 Report Pipeline\n result = await workflow.run_sequential(\n agents=[market_researcher, data_scientist, business_writer],\n task=\"Analyze the electric vehicle charging infrastructure market opportunity in North America for 2024-2027\"\n )\n \n print(\"Sequential Pipeline Result:\", result.result)\n\nasyncio.run(sequential_workflow_example())\n```\n\n### \ud83d\udd04 Parallel Workflow\n\nMultiple expert perspectives on the same challenge:\n\n```python\nimport asyncio\nfrom xagent.multi.workflow import Workflow\n\nasync def parallel_workflow_example():\n workflow = Workflow()\n \n # Multiple experts analyze the same problem simultaneously\n # Note: Can set output_type for structured consensus validation\n result = await workflow.run_parallel(\n agents=[financial_analyst, strategy_consultant, data_scientist],\n task=\"Evaluate the investment potential and strategic implications of generative AI adoption in enterprise software companies\"\n )\n \n print(\"Expert Panel Analysis:\", result.result)\n\nasyncio.run(parallel_workflow_example())\n```\n\n### \ud83d\udd78\ufe0f Graph Workflow\n\nComplex dependency networks with conditional execution:\n\n```python\nimport asyncio\nfrom xagent.multi.workflow import Workflow\n\nasync def graph_workflow_example():\n workflow = Workflow()\n \n # Complex dependency analysis\n dependencies = \"MarketResearcher->DataScientist, MarketResearcher->FinancialAnalyst, DataScientist&FinancialAnalyst->StrategyConsultant, StrategyConsultant->BusinessWriter\"\n \n result = await workflow.run_graph(\n agents=[market_researcher, data_scientist, financial_analyst, strategy_consultant, business_writer],\n dependencies=dependencies,\n task=\"Develop a comprehensive go-to-market strategy for a B2B SaaS startup entering the healthcare analytics space\"\n )\n \n print(\"Strategic Analysis Result:\", result.result)\n\nasyncio.run(graph_workflow_example())\n```\n\n### \ud83d\udd00 Hybrid Workflow\n\nMulti-stage workflows combining different patterns:\n\n```python\nimport asyncio\nfrom xagent.multi.workflow import Workflow\n\nasync def hybrid_workflow_example():\n workflow = Workflow()\n \n # Multi-stage comprehensive business analysis\n # Note: Tasks can include placeholders like {previous_result} and {original_task}\n stages = [\n {\n \"pattern\": \"sequential\",\n \"agents\": [market_researcher, financial_analyst],\n \"task\": \"Conduct market and financial analysis for: {original_task}\",\n \"name\": \"market_financial_analysis\"\n },\n {\n \"pattern\": \"parallel\", \n \"agents\": [data_scientist, strategy_consultant],\n \"task\": \"Analyze strategic implications and develop data-driven insights based on: {previous_result}\",\n \"name\": \"strategic_data_analysis\"\n },\n {\n \"pattern\": \"graph\",\n \"agents\": [business_writer, quality_reviewer, strategy_consultant],\n \"dependencies\": \"BusinessWriter->QualityReviewer, StrategyConsultant->QualityReviewer\",\n \"task\": \"Create final strategic report with quality validation from: {previous_result}\",\n \"name\": \"report_synthesis_validation\"\n }\n ]\n \n result = await workflow.run_hybrid(\n task=\"Develop a digital transformation strategy for a traditional manufacturing company looking to implement IoT and predictive maintenance solutions\",\n stages=stages\n )\n \n print(\"Comprehensive Strategy Report:\", result[\"final_result\"])\n\nasyncio.run(hybrid_workflow_example())\n```\n\n### DSL Syntax\n\nUse intuitive arrow notation for complex dependencies:\n\n```python\n# Simple chain\n\"A->B->C\"\n\n# Parallel branches\n\"A->B, A->C\"\n\n# Fan-in pattern\n\"A->C, B->C\"\n\n# Complex dependencies\n\"A->B, A->C, B&C->D\"\n```\n\nFor detailed workflow patterns and examples, see [Multi-Agent Workflows](docs/workflows.md) and [Workflow DSL](docs/workflow_dsl.md).\n\n## \ud83d\udcda Documentation\n\n### Core Documentation\n- [Configuration Reference](docs/configuration_reference.md) - Complete YAML configuration guide and examples\n- [API Reference](docs/api_reference.md) - Complete API documentation and parameter reference\n- [Multi-Agent Workflows](docs/workflows.md) - Workflow patterns and orchestration examples\n- [Workflow DSL](docs/workflow_dsl.md) - Domain-specific language for defining agent dependencies\n\n### Examples\n- [examples/demo](examples/demo) - Complete usage examples and demos\n- [examples/config/](examples/config/) - Configuration file templates\n- [examples/toolkit/](examples/toolkit/) - Custom tool development examples\n\n### Deployment\n\n- [deploy/docker/](deploy/docker/) - Production deployment with Docker and Docker Compose\n\n### Architecture Overview\n\nxAgent is built with a modular architecture:\n\n- **Core (`xagent/core/`)** - Agent and session management\n- **Interfaces (`xagent/interfaces/`)** - CLI, HTTP server, and web interface\n- **Components (`xagent/components/`)** - Message storage and persistence\n- **Tools (`xagent/tools/`)** - Built-in and custom tool ecosystem\n- **Multi (`xagent/multi/`)** - Multi-agent coordination and workflows\n\n### Key Features\n\n- **\ud83c\udf1f Auto Workflow** - Revolutionary AI-powered automatic workflow generation with zero configuration\n- **\ud83c\udfe2 Production Ready** - Multi-user and multi-session support with enterprise-grade reliability\n- **\ud83d\udc65 Multi-User Support** - Concurrent user handling with isolated sessions and conversation histories\n- **\ud83d\udd04 Multi-Session Management** - Each user can maintain multiple independent conversation sessions\n- **\ud83d\ude80 Easy to Use** - Simple API for quick prototyping\n- **\u26a1 High Performance** - Async/await throughout, concurrent tool execution\n- **\ud83e\udde0 Intelligent Agent Design** - AI creates optimal specialist teams (2-6 agents) based on task complexity\n- **\ud83d\udd17 Smart Dependencies** - Automatic dependency optimization for maximum parallel execution\n- **\ud83d\udd27 Extensible** - Custom tools, MCP integration, plugin system\n- **\ud83c\udf10 Multiple Interfaces** - CLI, HTTP API, web interface\n- **\ud83d\udcbe Persistent** - Redis-backed conversation storage\n- **\ud83e\udd16 Multi-Agent** - Hierarchical agent systems and workflows\n- **\ud83d\udcca Observable** - Built-in logging and monitoring\n\n**Key Methods:**\n- `async chat(user_message, user_id, session_id, **kwargs) -> str | BaseModel`: Main chat interface\n- `async __call__(user_message, user_id, session_id, **kwargs) -> str | BaseModel`: Shorthand for chat\n- `as_tool(name, description) -> Callable`: Convert agent to tool\n\n**Chat Method Parameters:**\n- `user_message`: The user's message (string or Message object)\n- `user_id`: User identifier for message storage (default: \"default_user\")\n- `session_id`: Session identifier for message storage (default: \"default_session\")\n- `history_count`: Number of previous messages to include (default: 16)\n- `max_iter`: Maximum model call attempts (default: 10)\n- `image_source`: Optional image(s) for analysis (URL, path, or base64)\n- `output_type`: Pydantic model for structured output\n- `stream`: Enable streaming response (default: False)\n\n**Agent Parameters:**\n- `name`: Agent identifier (default: \"default_agent\")\n- `system_prompt`: Instructions for the agent behavior\n- `model`: OpenAI model to use (default: \"gpt-4.1-mini\")\n- `client`: Custom AsyncOpenAI client instance\n- `tools`: List of function tools\n- `mcp_servers`: MCP server URLs for dynamic tool loading\n- `sub_agents`: List of sub-agent configurations (name, description, server URL)\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Here's how to get started:\n\n### Development Workflow\n\n1. **Fork** the repository\n2. **Create** a feature branch: `git checkout -b feature/amazing-feature` \n3. **Commit** your changes: `git commit -m 'Add amazing feature'`\n4. **Push** to the branch: `git push origin feature/amazing-feature`\n5. **Open** a Pull Request\n\n### Development Guidelines\n\n- Follow PEP 8 standards for code style\n- Add tests for new features\n- Update documentation as needed\n- Use type hints throughout\n- Follow conventional commit messages\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\ude4f Acknowledgments\n\nSpecial thanks to these amazing open source projects:\n\n- **[OpenAI](https://openai.com/)** - GPT models powering our AI\n- **[FastAPI](https://fastapi.tiangolo.com/)** - Robust async API framework \n- **[Streamlit](https://streamlit.io/)** - Intuitive web interface\n- **[Redis](https://redis.io/)** - High-performance data storage\n\n## \ud83d\udcde Support & Community\n\n| Resource | Purpose |\n|----------|---------|\n| **[GitHub Issues](https://github.com/ZJCODE/xAgent/issues)** | Bug reports & feature requests |\n| **[GitHub Discussions](https://github.com/ZJCODE/xAgent/discussions)** | Community chat & Q&A |\n| **Email: zhangjun310@live.com** | Direct support |\n\n---\n\n<div align=\"center\">\n\n**xAgent** - Empowering conversations with AI \ud83d\ude80\n\n[](https://github.com/ZJCODE/xAgent)\n[](https://github.com/ZJCODE/xAgent)\n\n*Built with \u2764\ufe0f for the AI community*\n\n</div>\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Multi-Modal AI Agent System",
"version": "0.2.16",
"project_urls": {
"Homepage": "https://github.com/ZJCODE/xagent#readme",
"Issues": "https://github.com/ZJCODE/xagent/issues",
"Repository": "https://github.com/ZJCODE/xagent"
},
"split_keywords": [
"ai",
" agent",
" openai",
" chatbot",
" async"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "2d997032726c17dd06b32b4d8033786dbc32f080c88a196461dd63bea286a309",
"md5": "00770b87c182e3fbef99d96dac6a05b8",
"sha256": "0a75072e2555592a9516a6f4a20ecb96dda90f7c840db0baaf4624be0357aee4"
},
"downloads": -1,
"filename": "myxagent-0.2.16-py3-none-any.whl",
"has_sig": false,
"md5_digest": "00770b87c182e3fbef99d96dac6a05b8",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 72144,
"upload_time": "2025-08-22T08:27:39",
"upload_time_iso_8601": "2025-08-22T08:27:39.678253Z",
"url": "https://files.pythonhosted.org/packages/2d/99/7032726c17dd06b32b4d8033786dbc32f080c88a196461dd63bea286a309/myxagent-0.2.16-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "963eb46af880d6481d22e3303d7fe4b9c681e01de28e8e4a08fdf56bb8c7b0cd",
"md5": "7a45a2f96ac3425b6e2ae44bfa4242ab",
"sha256": "0b2085cbff1a91a7a60e8d9ee4396af7c6bfc7e0ff7363814b38f98ae3c53b37"
},
"downloads": -1,
"filename": "myxagent-0.2.16.tar.gz",
"has_sig": false,
"md5_digest": "7a45a2f96ac3425b6e2ae44bfa4242ab",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 86473,
"upload_time": "2025-08-22T08:27:43",
"upload_time_iso_8601": "2025-08-22T08:27:43.231448Z",
"url": "https://files.pythonhosted.org/packages/96/3e/b46af880d6481d22e3303d7fe4b9c681e01de28e8e4a08fdf56bb8c7b0cd/myxagent-0.2.16.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-22 08:27:43",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "ZJCODE",
"github_project": "xagent#readme",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "myxagent"
}