### Complete Runnable Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/3_set_config.md
A complete, runnable code example demonstrating the setup of Oxygent with an LLM, tools, and an agent, including starting a web service.
```python
import asyncio
from oxygent import MAS, oxy, Config
from oxygent.utils.env_utils import get_env_var
import prompts
import tools
Config.set_agent_llm_model("default_llm")
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
timeout=240,
),
tools.file_tools,
oxy.ReActAgent(
name="master_agent",
is_master=True,
tools=["file_tools"],
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="Hello!"
)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Run OxyGent Demos
Source: https://github.com/jd-opensource/oxygent/blob/main/CONTRIBUTING_zh.md
Commands to run example demonstrations of the OxyGent project. These are useful for understanding the project's functionality and for testing.
```bash
python demo.py
```
```bash
python -m examples.agents.single_demo
```
--------------------------------
### Setup and Run OxyGent Tests
Source: https://github.com/jd-opensource/oxygent/blob/main/CONTRIBUTING_zh.md
Instructions for setting up the testing environment and running various tests for the OxyGent project, including unit and integration tests, as well as code formatting.
```bash
pip install pytest pytest-asyncio
```
```bash
ruff format .
```
```bash
docformatter -r -i --wrap-summaries 88 --wrap-descriptions 88 oxygent/
```
```bash
pytest oxygent/test/unittest
```
```bash
pytest oxygent/test/integration
```
--------------------------------
### OxyGent with Multiple LLMs and Agent Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/3_1_set_database.md
A complete runnable example demonstrating the use of OxyGent with multiple LLMs and an agent. It includes setting up Elasticsearch configuration and running a simple agent interaction.
```Python
"""Demo for using OxyGent with multiple LLMs and an agent."""
import asyncio
from oxygent import MAS, Config, oxy
from oxygent.utils.env_utils import get_env_var
Config.set_es_config(
{
"hosts": ["${PROD_ES_HOST_1}", "${PROD_ES_HOST_2}", "${PROD_ES_HOST_3}"],
"user": "${PROD_ES_USER}",
"password": "${ES_TEST_PASSWORD}",
}
)
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
timeout=240,
),
oxy.ReActAgent(
name="master_agent",
is_master=True,
llm_model="default_llm",
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
messages = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "hello"},
]
result = await mas.call(callee="master_agent", arguments={"messages": messages})
print(result)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Complete Oxygent Multimodal Workflow Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/10_multimodal.md
A full runnable example showcasing the setup and usage of multimodal input in Oxygent. It configures an HttpLLM for multimodal support, defines chat agents for image description and discrimination, and orchestrates a workflow to process an image.
```Python
import asyncio
from oxygent import MAS, Config, OxyRequest, OxyResponse, oxy
from oxygent.utils.env_utils import get_env_var
# Set LLM model
Config.set_agent_llm_model("default_vlm")
async def master_workflow(oxy_request: OxyRequest) -> OxyResponse:
# Call generate_agent to describe the image
generate_agent_oxy_response = await oxy_request.call(
callee="generate_agent",
arguments={
"query": oxy_request.get_query(),
"attachments": oxy_request.arguments.get("attachments", []),
"llm_params": {"temperature": 0.6},
},
)
# Call discriminate_agent to check if the image description is accurate
discriminate_agent_oxy_response = await oxy_request.call(
callee="discriminate_agent",
arguments={
"query": str(generate_agent_oxy_response.output),
"attachments": oxy_request.arguments.get("attachments", []),
},
)
return f"generate_agent output: {generate_agent_oxy_response.output} \n discriminate_agent output: {discriminate_agent_oxy_response.output}"
# Initialize oxy_space
oxy_space = [
oxy.HttpLLM(
name="default_vlm",
api_key=get_env_var("DEFAULT_VLM_API_KEY"),
base_url=get_env_var("DEFAULT_VLM_BASE_URL"),
model_name=get_env_var("DEFAULT_VLM_MODEL_NAME"),
llm_params={"temperature": 0.6, "max_tokens": 2048},
max_pixels=10000000, # Set maximum pixel count
is_multimodal_supported=True, # Enable multimodal support
is_convert_url_to_base64=True, # Convert image URL to base64 format
semaphore=4,
),
oxy.ChatAgent(
name="generate_agent",
prompt="You are a helpful assistant. Please describe the content of the image in detail.",
),
oxy.ChatAgent(
name="discriminate_agent",
prompt="Please determine whether the following text is a description of the content of the image. If it is, please output 'True', otherwise output 'False'.",
),
oxy.Workflow(
name="master_agent",
is_master=True,
permitted_tool_name_list=["generate_agent", "discriminate_agent"],
func_workflow=master_workflow,
),
]
# Main function
async def main():
# Multimodal input
async with MAS(oxy_space=oxy_space) as mas:
"""Single turn conversation"""
payload = {
"query": "What is it in the picture?",
"attachments": [get_env_var("DEFAULT_IMAGE_URL")], # Pass image URL
}
oxy_response = await mas.chat_with_agent(payload=payload)
print("LLM: ", oxy_response.output)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Python Environment Setup (uv)
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
Commands to set up a Python environment using 'uv', including installing Python and creating a virtual environment.
```Bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv python install 3.10
uv venv .venv --python 3.10
source .venv/bin/activate
```
--------------------------------
### Complete OxyGent Application Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/2_register_single_tool.md
This comprehensive Python script sets up an OxyGent MAS (Multi-Agent System) with an LLM, file tools, and a ReActAgent. It demonstrates how to start the system and initiate a conversation with 'Hello!'. The script includes necessary imports and asynchronous execution.
```Python
import asyncio
from oxygent import MAS, oxy
from oxygent.utils.env_utils import get_env_var
import prompts
import tools
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
timeout=240,
),
tools.file_tools, # Toolkits can be placed entirely in oxy_space
oxy.ReActAgent(
name="master_agent",
is_master=True,
tools=["file_tools"], # Place tools here
llm_model="default_llm",
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="Hello!"
)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Oxygent Initialization Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/9_workflow.md
Provides a complete, runnable code example for initializing Oxygent, setting the LLM model, and importing necessary modules and tools.
```Python
import asyncio
from oxygent import MAS, OxyRequest, Config, oxy
from oxygent.utils.env_utils import get_env_var
import tools
import prompts
# 设置 LLM 模型
Config.set_agent_llm_model("default_llm")
```
--------------------------------
### Install OxyGent from Source
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
Steps to clone the OxyGent repository, install dependencies, and set up the development environment.
```Bash
git clone https://github.com/jd-opensource/OxyGent.git
cd OxyGent
pip install -r requirements.txt # or in uv
brew install coreutils # maybe essential
```
--------------------------------
### Complete OxyGent Agent Setup and Execution
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/1_register_single_agent.md
A full Python script demonstrating how to set up an LLM and an agent within OxyGent, and then run them. It includes importing necessary modules, defining prompts, configuring the `oxy_space` with `HttpLLM` and `ReActAgent`, and starting the agent system.
```Python
import asyncio
from oxygent import MAS, oxy
from oxygent.utils.env_utils import get_env_var
master_prompt = """
你是一个文档分析专家,用户会向你提供文档,请为用户提供简要的文档摘要。
摘要可以是markdown格式。
"""
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
timeout=240,
),
oxy.ReActAgent(
name="master_agent",
prompt = master_prompt,
is_master=True,
llm_model="default_llm",
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="Hello!"
)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### ReActAgent Usage Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/agent/react_agent.md
A simple Python example demonstrating how to instantiate and configure a ReActAgent.
```python
import oxy
# Assuming SYSTEM_PROMPT is defined elsewhere
# SYSTEM_PROMPT = "..."
agent = oxy.ReActAgent(
name="time_agent",
desc="A tool that can query the time",
tools=["time_tools"],
llm_model="default_llm",
prompt=SYSTEM_PROMPT,
timeout=30,
is_multimodal_supported=False,
semaphore=2
)
```
--------------------------------
### LocalAgent Initialization and Setup
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/agent/local_agent.md
Initializes the LocalAgent object, verifies LLM model settings, and performs one-time setup tasks like tool discovery and multimodal checks.
```Python
class LocalAgent:
def __init__(**kwargs):
# Initialise the object and verify llm_model is set.
pass
def init():
# One-time setup; runs tool discovery, multimodal check and optional team spawning.
pass
```
--------------------------------
### Full Oxygent RAG Example with Asyncio
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/12_rag.md
A complete, runnable Python example demonstrating RAG with OxyGent. It sets up an LLM, a ReActAgent with a custom prompt and query processing function, and runs it as an asynchronous web service.
```Python
import asyncio
from oxygent import MAS, OxyRequest, oxy
from oxygent.utils.env_utils import get_env_var
INSTRUCTION = """
You are a helpful assistant and can use these tools:
${tools_description}
Experience in choosing tools:
${knowledge}
Select the appropriate tool based on the user's question.
If no tool is needed, reply directly.
If answering the user's question requires calling multiple tools, call only one tool at a time. After the user receives the tool result, they will give you feedback on the tool call result.
Important notes:
1. When you have collected enough information to answer the user's question, please respond in the following format:
Your reasoning (if analysis is needed)
Your response content
2. When you find that the user's question lacks certain conditions, you can ask them back. Please respond in the following format:
Your reasoning (if analysis is needed)
Your follow-up question to the user
3. When you need to use a tool, you must respond **only** with the following exact JSON object format, and nothing else:
{
"think": "Your reasoning (if analysis is needed)",
"tool_name": "Tool name",
"arguments": {
"Parameter name": "Parameter value"
}
}
"""
def update_query(oxy_request: OxyRequest):
current_query = oxy_request.get_query()
def retrieval(query):
return "\n".join(["knowledge1", "knowledge2", "knowledge3"])
oxy_request.arguments["knowledge"] = retrieval(current_query)
return oxy_request
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
),
oxy.ReActAgent(
name="master_agent",
is_master=True,
llm_model="default_llm",
timeout=100,
prompt=INSTRUCTION,
func_process_input=update_query,
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="This is an example for rag. Please modify it according to the specific needs",
)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Run OxyGent Demo
Source: https://github.com/jd-opensource/oxygent/blob/main/CONTRIBUTING.md
Executes the main demo script for the OxyGent project to verify successful environment setup.
```bash
python demo.py
```
--------------------------------
### Start OxyGent Web Service
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/14_debugging.md
Launches the OxyGent visual debugging service. This function starts the web service, allowing for interactive debugging and monitoring of the MAS application. It requires an `oxy_space` object and can take an initial query.
```Python
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(first_query="How many chars in 'OxyGent'?")
```
--------------------------------
### Setting Up OxyGent Environment
Source: https://github.com/jd-opensource/oxygent/blob/main/README_zh.md
Instructions for setting up a Python environment for OxyGent using Conda or uv, including installing the oxygent package.
```Bash
conda create -n oxy_env python==3.10
conda activate oxy_env
```
```Bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv python install 3.10
uv venv .venv --python 3.10
source .venv/bin/activate
```
```Bash
pip install oxygent
```
```Bash
uv pip install oxygent
```
```Bash
git clone https://github.com/jd-opensource/OxyGent.git
cd OxyGent
pip install -r requirements.txt # or in uv
brew install coreutils # maybe essential
```
--------------------------------
### Run Single Agent Demo
Source: https://github.com/jd-opensource/oxygent/blob/main/CONTRIBUTING.md
Executes a single agent demonstration within the OxyGent examples.
```bash
python -m examples.agents.single_demo
```
--------------------------------
### Running the Oxygent Example
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
Command to execute the Python script ('demo.py') that runs the configured multi-agent system.
```Bash
python demo.py
```
--------------------------------
### Install OxyGent Package
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
Instructions for installing the OxyGent Python package using pip (with Conda) or uv.
```Bash
pip install oxygent
```
```Bash
uv pip install oxygent
```
--------------------------------
### Install Testing Dependencies
Source: https://github.com/jd-opensource/oxygent/blob/main/CONTRIBUTING.md
Installs necessary packages for running tests, including pytest and pytest-asyncio.
```bash
pip install pytest pytest-asyncio
```
--------------------------------
### ParallelAgent Usage Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/agent/parallel_agent.md
Demonstrates how to instantiate and configure a ParallelAgent with specific tools and settings.
```python
oxy.ParallelAgent(
name="expert_panel",
llm_model="default_llm",
desc="Expert panel parallel evaluation",
permitted_tool_name_list=[
"tech_expert",
"business_expert",
"risk_expert",
"legal_expert",
],
is_master=True,
)
```
--------------------------------
### Oxygent MAS Python Script
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
A Python script demonstrating the setup and execution of a Multi-Agent System (MAS) using the Oxygent library. It configures an LLM, defines ReActAgents for time, file system, and math operations, and a master agent to orchestrate them. The script includes an asynchronous main function to start the MAS web service with an initial query.
```Python
import os
from oxygent import MAS, Config, oxy, preset_tools
Config.set_agent_llm_model("default_llm")
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=os.getenv("DEFAULT_LLM_API_KEY"),
base_url=os.getenv("DEFAULT_LLM_BASE_URL"),
model_name=os.getenv("DEFAULT_LLM_MODEL_NAME"),
),
preset_tools.time_tools,
oxy.ReActAgent(
name="time_agent",
desc="A tool that can query the time",
tools=["time_tools"],
),
preset_tools.file_tools,
oxy.ReActAgent(
name="file_agent",
desc="A tool that can operate the file system",
tools=["file_tools"],
),
preset_tools.math_tools,
oxy.ReActAgent(
name="math_agent",
desc="A tool that can perform mathematical calculations.",
tools=["math_tools"],
),
oxy.ReActAgent(
is_master=True,
name="master_agent",
sub_agents=["time_agent", "file_agent", "math_agent"],
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="What time is it now? Please save it into time.txt."
)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
--------------------------------
### Oxygent Workflow Example
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/9_workflow.md
Demonstrates a workflow that first queries the time and then calculates Pi. It shows how to use `oxy_request.call` to sequence agent tasks and retrieve their outputs.
```Python
async def workflow(oxy_request: OxyRequest):
short_memory = oxy_request.get_short_memory()
print("--- History record --- :", short_memory)
master_short_memory = oxy_request.get_short_memory(master_level=True)
print("--- History record-User layer --- :", master_short_memory)
print("user query:", oxy_request.get_query(master_level=True))
await oxy_request.send_message("msg")
oxy_response = await oxy_request.call(
callee="time_agent",
arguments={"query": "What time is it now in Asia/Shanghai?"},
)
print("--- Current time --- :", oxy_response.output)
oxy_response = await oxy_request.call(
callee="default_llm",
arguments={
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
"llm_params": {"temperature": 0.6},
},
)
print(oxy_response.output)
import re
numbers = re.findall(r"\d+", oxy_request.get_query())
if numbers:
n = numbers[-1]
oxy_response = await oxy_request.call(callee="calc_pi", arguments={"prec": n})
return f"Save {n} positions: {oxy_response.output}"
else:
return "Save 2 positions: 3.14, or you could ask me to save how many positions you want."
```
--------------------------------
### Python Environment Setup (Conda)
Source: https://github.com/jd-opensource/oxygent/blob/main/README.md
Commands to create and activate a Python environment using Conda for the OxyGent project.
```Bash
conda create -n oxy_env python==3.10
conda activate oxy_env
```
--------------------------------
### Load Configuration from JSON
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/3_set_config.md
Loads configuration settings by importing a JSON configuration file. This allows for centralized management of settings.
```python
Config.load_from_json("./config.json", env="default")
```
--------------------------------
### Customizing LLM Output Format with System Prompt
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/8_2_handle_output.md
Example of a system prompt to guide the LLM to return tool call outputs in a specific JSON format or as a direct answer.
```Python
SYSTEM_PROMPT = """
You are a helpful assistant that can use these tools:
${tools_description}
Choose the appropriate tool based on the user's question.
If no tool is needed, respond directly.
If answering the user's question requires multiple tool calls, call only one tool at a time. After the user receives the tool result, they will provide you with feedback on the tool call result.
Important instructions:
1. When you have collected enough information to answer the user's question, please respond in the following format:
Your thinking (if analysis is needed)
Your answer content
2. When you find that the user's question lacks conditions, you can ask the user back, please respond in the following format:
Your thinking (if analysis is needed)
Your question to the user
3. When you need to use a tool, you must only respond with the exact JSON object format below, nothing else:
{
"think": "Your thinking (if analysis is needed)",
"tool_name": "Tool name",
"arguments": {
"parameter_name": "parameter_value"
}
}
After receiving the tool's response:
1. Transform the raw data into a natural conversational response
2. The answer should be concise but rich in content
3. Focus on the most relevant information
4. Use appropriate context from the user's question
5. Avoid simply repeating the raw data
Please only use the tools explicitly defined above.
"""
```
--------------------------------
### Pass Attachments to Oxygent Chat
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/10_multimodal.md
Demonstrates how to pass image attachments to an Oxygent MAS chat session using the `attachments` parameter in the payload. The example uses a URL for the image attachment.
```Python
async with MAS(oxy_space=oxy_space) as mas:
"""Single turn conversation"""
payload = {
"query": "What is it in the picture?", # Ask a question
"attachments": [get_env_var("DEFAULT_IMAGE_URL")], # Pass image attachment
}
oxy_response = await mas.chat_with_agent(payload=payload)
print("LLM: ", oxy_response.output)
```
--------------------------------
### Distributed Time Agent Example (Python)
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/11_dstributed.md
This Python script demonstrates how to create a distributed time query agent using OxyGent MAS. It configures an LLM, a time MCP client, and a ReAct agent, then starts a web service for the agent. It's designed to be run as a distributed service.
```Python
# app_time_agent.py
from oxygent import MAS, Config, oxy
from oxygent.utils.env_utils import get_env_var
Config.set_app_name("app-time")
Config.set_server_port(8082) # 替换为实际端口
oxy_space = [
oxy.HttpLLM(
name="default_name",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
),
oxy.StdioMCPClient(
name="time",
params={
"command": "uvx",
"args": ["mcp-server-time", "--local-timezone=Asia/Shanghai"],
},
),
oxy.ReActAgent(
name="time_agent",
desc="A tool for time query",
is_master=True,
tools=["time"],
llm_model="default_name",
timeout=10,
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(first_query="What time is it now?")
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
--------------------------------
### OxyGent MAS Configuration with Custom Prompt Handling
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/8_update_prompts.md
This Python code demonstrates a full OxyGent Multi-Agent System (MAS) setup. It configures various agents, including ReActAgent, ChatAgent, and ParallelAgent, and applies the custom `update_query` function to `func_process_input` for agents that require modified prompts. The example also includes LLM and tool configurations, setting up a complete, runnable MAS.
```Python
import asyncio
from oxygent import MAS, oxy, Config, OxyRequest
from oxygent.utils.env_utils import get_env_var
import prompts
import tools
Config.set_agent_llm_model("default_llm")
def update_query(oxy_request: OxyRequest):
user_query = oxy_request.get_query(master_level=True)
current_query = oxy_request.get_query()
oxy_request.set_query(
f"user query is {user_query}\ncurrent query is {current_query}"
)
return oxy_request
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
timeout=240,
),
oxy.StdioMCPClient(
name="time_tools",
params={
"command": "uvx",
"args": ["mcp-server-time", "--local-timezone=Asia/Shanghai"],
},
),
tools.file_tools,
oxy.ReActAgent(
name="file_agent",
desc="A tool that can operate the file system",
tools=["file_tools"],
func_process_input=update_query,
),
oxy.ReActAgent(
name="time_agent",
desc="A tool that can get current time",
tools=["time_tools"],
),
oxy.ChatAgent(
name="text_summarizer",
desc="A tool that can summarize markdown text",
prompt=prompts.text_summarizer_prompt,
func_process_input=update_query,
),
oxy.ChatAgent(
name="data_analyser",
desc="A tool that can summarize echart data",
prompt=prompts.data_analyser_prompt,
func_process_input=update_query,
),
oxy.ChatAgent(
name="document_checker",
desc="A tool that can find problems in document",
prompt=prompts.document_checker_prompt,
func_process_input=update_query,
),
oxy.ParallelAgent(
name="analyzer",
desc="A tool that analyze markdown document",
permitted_tool_name_list=["text_summarizer", "data_analyser", "document_checker"],
func_process_input=update_query,
),
oxy.ReActAgent(
name="master_agent",
is_master=True,
sub_agents=["file_agent","time_agent","analyzer"],
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="Hello!"
)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### MAS Class Initialization and Usage
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/mas.md
Demonstrates how to initialize and use the MAS class for starting web services or CLI mode. It highlights the asynchronous context management and the `first_query` parameter.
```Python
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="Hello!"
)
```
```Python
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_cli_mode(
first_query="Hello!"
)
```
--------------------------------
### OxyGent Demo: Multi-Agent System Example
Source: https://github.com/jd-opensource/oxygent/blob/main/README_zh.md
A Python script demonstrating how to create and run a multi-agent system using OxyGent. It configures LLM, time, file, and math agents, and a master agent to coordinate them.
```Python
import os
from oxygent import MAS, Config, oxy, preset_tools
Config.set_agent_llm_model("default_llm")
oxy_space = [
oxy.HttpLLM(
name="default_llm",
api_key=os.getenv("DEFAULT_LLM_API_KEY"),
base_url=os.getenv("DEFAULT_LLM_BASE_URL"),
model_name=os.getenv("DEFAULT_LLM_MODEL_NAME"),
),
preset_tools.time_tools,
oxy.ReActAgent(
name="time_agent",
desc="A tool that can query the time",
tools=["time_tools"],
),
preset_tools.file_tools,
oxy.ReActAgent(
name="file_agent",
desc="A tool that can operate the file system",
tools=["file_tools"],
),
preset_tools.math_tools,
oxy.ReActAgent(
name="math_agent",
desc="A tool that can perform mathematical calculations.",
tools=["math_tools"],
),
oxy.ReActAgent(
is_master=True,
name="master_agent",
sub_agents=["time_agent", "file_agent", "math_agent"],
),
]
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_web_service(
first_query="What time is it now? Please save it into time.txt."
)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
--------------------------------
### StdioMCPClient Methods
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/tools/stdio_mcp_client.md
Provides details on the methods available in StdioMCPClient. init() is a coroutine for initializing the stdio connection, and _ensure_directories_exist(args) is a coroutine to ensure necessary directories are present before starting the MCP server.
```APIDOC
StdioMCPClient:
init()
Coroutine (async): Yes
Return Value: None
Purpose: Initialize the stdio connection to the MCP server process
_ensure_directories_exist(args)
Coroutine (async): Yes
Return Value: None
Purpose: Ensure required directories exist before starting MCP server
```
--------------------------------
### Start OxyGent Command-Line Mode
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/1_1_chat_with_agent.md
Starts OxyGent in command-line mode, allowing interaction directly from the terminal. This is an alternative for users who prefer command-line interfaces.
```Python
async def main():
async with MAS(oxy_space=oxy_space) as mas:
await mas.start_cli_mode(
first_query="Hello!" #聊天框中的默认内容
)
```
--------------------------------
### Workflow Step: Get Time
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/9_workflow.md
Code snippet for a workflow step that calls the 'time_agent' to get the current time. It demonstrates passing arguments to the agent and accessing its output.
```Python
time_resp = await oxy_request.call(
callee="time_agent", arguments={"query": "现在的北京时间是?"}
)
current_time = time_resp.output
```
--------------------------------
### HttpLLM Initialization and Usage
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/llms/http_llm.md
Demonstrates how to instantiate the HttpLLM class with necessary parameters like name, API key, base URL, model name, LLM parameters, and semaphore.
```python
oxy.HttpLLM(
name="default_name",
api_key=get_env_var("DEFAULT_LLM_API_KEY"),
base_url=get_env_var("DEFAULT_LLM_BASE_URL"),
model_name=get_env_var("DEFAULT_LLM_MODEL_NAME"),
llm_params={"temperature": 0.01},
semaphore=4,
)
```
--------------------------------
### OxyGent MAS Application Startup Information
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/14_debugging.md
Displays system and application information upon successful compilation and startup of the OxyGent MAS application. This includes version, environment, port, Python version, cache directory, and startup time.
```Apache
____ ______ __
/ __ \_ ____ __/ ____/__ ____ / /_
/ / / / |/_/ / / / / __/ _ \/ __ \/ __/
/ /_/ /> /_/ / /_/ / __/ / / / /_
\____/_/|_|\__, /\____/\___/_/ /_/\__/
/____/
2025-07-20 20:36:03,613 - INFO ================================================================
2025-07-20 20:36:03,613 - INFO 🚀 OxyGent MAS Application Startup Information
2025-07-20 20:36:03,613 - INFO ================================================================
2025-07-20 20:36:03,613 - INFO App Name : app
2025-07-20 20:36:03,613 - INFO Version : 1.0.0
2025-07-20 20:36:03,613 - INFO Environment : default
2025-07-20 20:36:03,613 - INFO Port : 8080
2025-07-20 20:36:03,613 - INFO Python Ver : 3.10.18
2025-07-20 20:36:03,613 - INFO Cache Dir : ./cache_dir
2025-07-20 20:36:03,614 - INFO Start Time : 2025-07-20 20:36:03
2025-07-20 20:36:03,614 - INFO ================================================================
2025-07-20 20:36:03,616 - INFO 🌐 OxyGent MAS Organization Structure Overview
2025-07-20 20:36:03,616 - INFO ================================================================
```
--------------------------------
### Oxygent Redis Client List Operations
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/databases/db_redis/jimdb_ap_redis.md
Provides comprehensive methods for manipulating lists in Redis, including left-pushing with truncation, popping elements, simulating blocking pops, retrieving ranges, removing elements, getting elements by index, getting list length, and trimming lists.
```Python
lpush(self, key, *values, ex=86400, max_size=1024, max_length=20240)
Left-push with value truncation, list trim, and TTL using a pipeline.
rpop(self, key)
Pop the last element of a list.
brpop(self, key, timeout=1)
Simulated blocking pop (rpop, sleep, re-rpop) for JimDB.
lrange(self, key, start=0, end=-1)
Return a slice of a list (LIFO due to lpush).
lrem(self, key, count, value)
Remove elements equal to value.
lindex(self, key, index)
Get list element by index.
llen(self, key)
Get list length.
ltrim(self, key, start, end)
Trim a list to the given range.
```
--------------------------------
### PlanAndSolve Class Initialization
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/flows/plan_and_solve.md
Demonstrates how to initialize the PlanAndSolve class with various parameters, including agent names, LLM model, replanning settings, and timeout.
```python
oxy.PlanAndSolve(
name="master_agent",
is_discard_react_memory=True,
llm_model="default_llm",
is_master=True,
planner_agent_name="planner_agent",
executor_agent_name="executor_agent",
enable_replanner=False,
timeout=100,
)
```
--------------------------------
### JavaScript Function to Get Node Plan Data
Source: https://github.com/jd-opensource/oxygent/blob/main/oxygent/web/node.html
Fetches detailed data for a specific node plan using its ID via an AJAX GET request. It updates UI elements, including navigation buttons, node images, and base information, based on the returned data. It also handles rendering of input parameters like class attributes.
```JavaScript
function get_plan(plan_id) {
$('.view1-node').each((i, ele) => {
$(ele).removeClass('checked');
});
$('.view1-container').each((i, ele) => {
$(ele).removeClass('checked');
});
$(`#${plan_id}`).addClass('checked');
$.ajax({
type: "GET",
url: "../node/",
data: { item_id: plan_id },
success: function (v) {
const data_range_map = v.data.data_range_map;
plan_data = v.data;
pre_id = plan_data.pre_id;
if (pre_id === "" || pre_id === undefined) {
$("#pre").prop("disabled", true);
} else {
$("#pre").prop("disabled", false);
}
next_id = plan_data.next_id;
if (next_id === "" || pre_id === undefined) {
$("#next").prop("disabled", true);
} else {
$("#next").prop("disabled", false);
}
// 展示图像
let img = '';
if (plan_data.node_type === 'agent' || plan_data.node_type === 'flow') {
const idx = agent_id_dict[plan_data.callee] % 16;
const cur = agentImgMap[idx];
img = ``;
} else {
img = ``;
}
$("#avatarEmojiId").append(img);
// 展示node base info
$("#node_caller").text(plan_data.caller);
$("#node_callee").text(plan_data.callee);
$("#node_create_time").text(plan_data.create_time);
$("#messages").empty();
// 展示参数class_attr 需要展示多个参数
if (plan_data.input.class_attr) {
Object.entries(plan_data.input.class_attr).forEach(([key, value]) => {
const typeValue = getType(value);
// 如果是字符串,直接渲染那
if (typeValue === "boolean") {
var numberHtml = value ? `
${key}:
` :`
${key}:
`
$('#classAttrId').append(numberHtml);
}
if (typeValue === "number") {
var numberHtml = `
`
$('#classAttrId').append(numberHtml);
}
if (typeValue === "string") {
var stringHtml = `
`
$('#classAttrId').append(stringHtml);
}
if (typeValue === "object") {
const prekey = key;
Object.entries(value).forEach(([key, value]) => {
var innerTypeValue = getType(value);
if (innerTypeValue === "number") {
var numberHtmlValue = `
`
$('#classAttrId').append
```
--------------------------------
### Fetching First Query and Input Handling
Source: https://github.com/jd-opensource/oxygent/blob/main/oxygent/web/index.html
Fetches the initial user query from the server and sets it in the message input field. It also adds an active class to the send button if the input has content.
```javascript
$.ajax({
type: "GET",
url: "../get_first_query",
success: function (response) {
// console.log('first_query', response);
$("#message_input").val(response.data.first_query);
if (response.data.first_query) {
$("#message_send").addClass('message_send_active'); // 有值时背景色为蓝色
}
}
});
```
--------------------------------
### SSEMCPClient Methods
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/development/api/tools/sse_mcp_client.md
Details the methods available for SSEMCPClient, including the asynchronous initialization method to establish the SSE connection and discover tools.
```APIDOC
SSEMCPClient:
Methods:
init() -> None (async):
Purpose: Initialize the SSE connection to the MCP server and discover available tools.
```
--------------------------------
### Integrating Custom Parser with ReActAgent
Source: https://github.com/jd-opensource/oxygent/blob/main/docs/docs_zh/8_2_handle_output.md
Example of how to pass a custom response parser function to the `oxy.ReActAgent` constructor.
```Python
oxy.ReActAgent(
name="json_agent",
desc="A tool that can convert plaintext into json text",
func_parse_llm_response=json_parser, # 关键方法
),
```