LightAgent is an extremely lightweight active Agentic Framework with memory (mem0), tools (Tools), and a tree of thought (ToT), and it is completely open source. It supports simpler multi-agent collaboration than OpenAI Swarm, allowing you to build self-learning agents in just one step, and supports connecting to the MCP protocol via stdio and sse. The underlying models support OpenAI, Zhiyuan ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen large models, and more. At the same time, LightAgent supports OpenAI streaming format API service output, seamlessly integrating with major mainstream Chat frameworks. 🌟
- Lightweight and Efficient 🚀: Minimalist design, quick deployment, suitable for various application scenarios. (No LangChain, No LlamaIndex) 100% Python implementation, no additional dependencies, core code is only 1000 lines, fully open source.
- Memory Support 🧠: Supports custom long-term memory for each user, natively supporting the
mem0memory module, automatically managing user personalized memory during conversations, making agents smarter. - Autonomous Learning 📚️: Each agent possesses autonomous learning capabilities, and admins with permissions can manage each agent.
- Tool Integration 🛠️: Support for custom tools (
Tools) and MCP tool integration, flexible expansion to meet diverse needs. - Complex Goals 🌳: Built-in Tree of Thought (
ToT) module with reflection, supporting complex task decomposition and multi-step reasoning, enhancing task processing capabilities. - Multi-Agent Collaboration 🤖: Simpler to implement multi-agent collaboration than Swarm, with built-in LightSwarm for intent recognition and task delegation, enabling smarter handling of user input and delegating tasks to other agents as needed.
- Independent Execution 🤖: Tasks and tool calls are completed autonomously without human intervention.
- Multi-Model Support 🔄: Compatible with OpenAI, Zhipu ChatGLM, Baichuan Large Model, StepFun, DeepSeek, Qwen series large models.
- Streaming API 🌊: Supports OpenAI streaming format API service output, seamlessly integrates with mainstream chat frameworks, enhancing user experience.
- Tool Generator 🚀: Just provide your API documentation to the [Tool Generator], which will automatically create exclusive tools for you, allowing you to quickly build hundreds of personalized custom tools in just 1 hour to improve efficiency and unleash your creative potential.
- Agent Self-Learning 🧠️: Each agent has its own scene memory capabilities and the ability to self-learn from user conversations.
- Adaptive Tool Mechanism 🛠️: Supports adding an unlimited number of tools, allowing the large model to first select a candidate tool set from thousands of tools, filtering irrelevant tools before submitting context to the large model, significantly reducing token consumption.
If you are using LightSwarm or other multi-agent patterns and start seeing role drift, cross-agent memory issues or confusing logs, you can check the
Multi-agent failure map for a small symptom → mode → debug checklist.
This page is docs-only and does not change any framework code.
[2026-02-21] LightAgent v0.5.0 Released: Adds session-level toolset constraints for granular control, fixes tool call history in multi-turn conversations, and improves LightSwarm stability.
- [2026-01-20] LightAgent v0.4.8 Released: Introduces runtime toolset constraints for session-level control and enhanced debug settings.
- [2025-11-15] LightAgent v0.4.7 Released: Improved debug configuration and fixes for LightSwarm-related bugs.
- [2025-10-28] LightAgent v0.4.6 Released: Adds support for model extension parameters (e.g., Qwen3 thinking mode) and enhanced metadata handling.
- [2025-09-16] Our paper is now available as a preprint on arXiv: https://arxiv.org/pdf/2509.09292. We invite the research community to read and cite our work.
- [2025-06-12] We are pleased to announce the official release of LightAgent v0.4.0! This version upgrade brings architectural improvements, with significant enhancements in performance, stability, and maintainability.
- [2025-05-05] LightAgent v0.3.3 Released: Deep Langfuse Logging Integration, Enhanced Context Management and Tool Invocation Stability View
- [2025-04-21] LightAgent v0.3.2 adds an adaptive Tools mechanism, supports unlimited intelligent tool filtering, reduces Token consumption by 80%, and improves response speed by 52%! View
- [2025-04-01] LightAgent v0.3.0 Support browser interaction browser_use and fully supports the MCP protocol, enabling collaborative work with multiple models and tools to achieve more efficient handling of complex tasks.View MCP release introduction.>>
- [2025-02-19] LightAgent v0.2.7 supports deepseek-r1 model for tot now.Significantly enhances the multi-tool planning capability for complex tasks.
- [2025-02-06] LightAgent version 0.2.5 is released now.
- [2025-01-20] LightAgent version 0.2.0 is released now.
- [2025-01-05] LightAgent version 0.1.0 is released now.
- Agent Collaborative Communication 🛠️: Agents can also share information and transmit messages, achieving complex information communication and task collaboration.
- Agent Assessment 📊: Built-in agent assessment tool for conveniently evaluating and optimizing the agents you build, aligning with business scenarios, and continuously improving intelligence levels.
- Support for Agent Skills ✨: Provides plug-inable skill modules for intelligent agents, enabling rapid expansion of the agent's capability boundaries and supporting the development of custom skills as well as community sharing.
The Thought Flow method effectively addresses challenges in complex scenarios through systematic, structured, and flexible thinking processes. Here are the specific implementation steps:
Problem Definition: Clarify the core problems and objectives.
Information Collection: Systematically gather relevant information and data.
Problem Decomposition: Break down complex problems into multiple subproblems or modules.
Multi-dimensional Analysis: Analyze each subproblem from different angles and levels.
Establish Connections: Identify the relationships and dependencies between subproblems.
Generate Solutions: Propose possible solutions for each subproblem.
Evaluation and Selection: Assess the feasibility and impact of each solution, choosing the best one.
Implementation and Feedback: Implement the selected solution and adjust based on feedback.
- Open Source and Free 💖: Fully open source, community-driven, continuously updated, contributions are welcome!
- Easy to Get Started 🎯: Detailed documentation, rich examples, quick to get started, easy integration into your project.
- Community Support 👥: An active developer community ready to assist and provide answers at any time.
- High Performance ⚡: Optimized design, efficient operation, meeting high concurrency requirements.
pip install lightagent(Optional installation) Install the Mem0 package via pip:
pip install mem0aiAlternatively, you can use Mem0 on a hosted platform by clicking here.
from LightAgent import LightAgent
# Initialize Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
# Run Agent
response = agent.run("Hello, who are you?")
print(response)from LightAgent import LightAgent
# Initialize Agent
agent = LightAgent(
role="Please remember that you are LightAgent, a useful assistant that helps users use multiple tools.", # system role description
model="gpt-4.1", # Supported models: openai, chatglm, deepseek, qwen, etc.
api_key="your_api_key", # Replace with your large model provider API Key
base_url="your_base_url", # Replace with your large model provider api url
)
# Run Agent
response = agent.run("Who are you?")
print(response)from LightAgent import LightAgent
# Define Tool
def get_weather(city_name: str) -> str:
"""
Get the current weather for `city_name`
"""
return f"Query result: {city_name} is sunny."
# Define tool information inside the function
get_weather.tool_info = {
"tool_name": "get_weather",
"tool_description": "Get current weather information for the specified city.",
"tool_params": [
{"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True},
]
}
tools = [get_weather]
# Initialize Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url", tools=tools)
# Run Agent
response = agent.run("Please check the weather in Shanghai.")
print(response)Supports an unlimited number of customizable tools.
Multiple tool examples: tools = [search_news, get_weather, get_stock_realtime_data, get_stock_kline_data]
LightAgent supports external extensions of the mem0 memory module, automating context memory and historical record management without requiring developers to manually trigger memory addition and retrieval. With the memory module, the agent can maintain contextual consistency across multiple rounds of dialogue.
# Enable Memory Module
# Or use a custom memory module, here is an example with mem0 https://github.com/mem0ai/mem0/
from mem0 import Memory
from LightAgent import LightAgent
import os
from loguru import logger
class CustomMemory:
def __init__(self):
self.memories = []
os.environ["OPENAI_API_KEY"] = "your_api_key"
os.environ["OPENAI_API_BASE"] = "your_base_url"
# Initialize Mem0
config = {
"version": "v1.1"
}
# Use qdrant as a vector database for storing memories in mem0, change config to the code below
# config = {
# "vector_store": {
# "provider": "qdrant",
# "config": {
# "host": "localhost",
# "port": 6333,
# }
# },
# "version": "v1.1"
# }
self.m = Memory.from_config(config_dict=config)
def store(self, data: str, user_id):
"""Store memory. Developers can modify the internal implementation of the storage method; the current example is the mem0 method for adding memory."""
result = self.m.add(data, user_id=user_id)
return result
def retrieve(self, query: str, user_id):
"""Retrieve related memory. Developers can modify the internal implementation of the retrieval method; the current example is the mem0 method for searching memory."""
result = self.m.search(query, user_id=user_id)
return result
agent = LightAgent(
role="Please remember that you are LightAgent, a useful assistant to help users use multiple tools.", # system role description
model="gpt-4.1", # Supported models: openai, chatglm, deepseek, qwen, etc.
api_key="your_api_key", # Replace with your large model provider API Key
base_url="your_base_url", # Replace with your large model provider api url
memory=CustomMemory(), # Enable memory function
tree_of_thought=False, # Enable Chain of Thought
)
# Memory-enabled test & if tools need to be added, you can add tools to the agent for memory-enabled tool calls
user_id = "user_01"
logger.info("\n=========== next conversation ===========")
query = "Introduce me to the attractions in Sanya. Many of my friends have traveled to Sanya, and I want to visit too."
print(agent.run(query, stream=False, user_id=user_id))
logger.info("\n=========== next conversation ===========")
query = "Where should I travel?"
print(agent.run(query, stream=False, user_id=user_id))Output as follows:
=========== next conversation ===========
2025-01-01 21:55:15.886 | INFO | __main__:run_conversation:115 -
Starting to think about the question: Introduce me to the attractions in Sanya, many of my friends have traveled to Sanya, and I want to visit too.
2025-01-01 21:55:28.676 | INFO | __main__:run_conversation:118 - Final Reply:
Sanya is a popular tourist city in Hainan Province, China, known for its beautiful beaches, tropical climate, and rich tourist resources. Here are some attractions worth visiting in Sanya:
1. **Yalong Bay**: Known as the "Hawaii of the East," it has a long beach and clear waters, ideal for swimming, diving, and sunbathing.
2. **Tianya Haijiao**: This is a famous cultural landscape, attracting tourists with its magnificent sea view and romantic legends. The giant rocks here are inscribed with the words "Tianya" and "Haijiao," symbolizing eternal love.
3. **Nanshan Cultural Tourism Zone**: Here there is a 108-meter-tall Nanshan Sea Guanyin statue, the highest sea Guanyin statue in the world. Visitors can experience Buddhist culture and visit temples and gardens.
4. **Wuzhizhou Island**: This small island is known for its pristine natural scenery and rich water activities. Visitors can engage in diving, snorkeling, and sea fishing among other activities.
5. **Dadonghai**: This is a beach located in Sanya city, favored by tourists for its convenient transportation and vibrant nightlife.
6. **Sanya Bay**: It is a 22-kilometer long beach and a great place to watch the sunset. This beach is relatively quiet, suitable for visitors who enjoy tranquility.
7. **Ya Nui National Park**: This is a tropical rainforest park where visitors can experience the natural scenery of tropical rainforests and participate in various adventure activities.
8. **Luohuitou Park**: A park located on a mountaintop, offering a panoramic view of Sanya city and Sanya Bay. There is also a beautiful legend about a deer.
9. **Xidao**: This is a relatively pristine small island attracting tourists with its serene beaches and rich marine life.
10. **Sanya Ancient Love**: This is a large cultural theme park showcasing the history and culture of Hainan through performances and exhibitions.
In addition to the above attractions, Sanya has many other places worth exploring, such as tropical botanical gardens and seafood markets. The local cuisine, especially fresh seafood and tropical fruits, should not be missed. When planning a trip, it is advisable to check the weather forecast and attraction opening times in advance to ensure a pleasant travel experience.
2025-01-01 21:55:28.676 | INFO | __main__:<module>:191 -
=========== next conversation ===========
2025-01-01 21:55:28.676 | INFO | __main__:run_conversation:115 -
Starting to think about the question: Where should I travel?
Relevant memory found:
User wants to travel to Sanya
User's friends have traveled to Sanya.
2025-01-01 21:55:38.797 | INFO | __main__:run_conversation:118 - Final Reply:
Based on previously mentioned information, the user’s friends have already traveled to Sanya, and the user has also expressed interest in going there. Therefore, Sanya might be a suitable travel destination for the user. Here is some travel information about Sanya for the user’s reference:
### Recommended Travel Spots in Sanya:
1. **Yalong Bay**: Known as the "Hawaii of the East," it has beautiful beaches and clear waters, suitable for swimming and sunbathing.
2. **Tianya Haijiao**: This iconic site of Sanya attracts tourists with its unique rocks and romantic legends.
3. **Nanshan Cultural Tourism Area**: It features the famous Nanshan Temple and the 108-meter-high Sea Guanyin statue, an important Buddhist cultural site.
4. **Wuzhizhou Island**: Suitable for diving and marine sports, the island is home to a rich marine ecosystem and coral reefs.
5. **Dadonghai**: A beach within Sanya city, conveniently located and suitable for family and couple visits.
### Other Recommendations:
If the user is already familiar with Sanya or wishes to explore other destinations, here are some other popular travel places:
1. **Guilin**: Known for its unique karst landscape and Lijiang River scenery.
2. **Lijiang**: The ancient town and Jade Dragon Snow Mountain are its main attractions, suitable for those who enjoy history and natural scenery.
3. **Zhangjiajie**: Famous for its unique stone pillars and natural scenery, it is one of the shooting locations for the movie "Avatar."
Users can choose suitable travel destinations based on their interests and schedule. If the user needs more detailed information or assistance in planning the trip, feel free to let us know!Embrace personalized tool customization (Tools) and easily integrate your exclusive tools through the tools method. These tools can be any Python function and support parameter type annotations, ensuring flexibility and accuracy. Additionally, we provide an AI-driven tool generator to help you automatically build tools and unleash creativity.
import requests
from LightAgent import LightAgent
# Define Tool
def get_weather(
city_name: str
) -> str:
"""
Get weather information for a city
:param city_name: Name of the city
:return: Weather information
"""
if not isinstance(city_name, str):
raise TypeError("City name must be a string")
key_selection = {
"current_condition": ["temp_C", "FeelsLikeC", "humidity", "weatherDesc", "observation_time"],
}
try:
resp = requests.get(f"https://wttr.in/{city_name}?format=j1")
resp.raise_for_status()
resp = resp.json()
ret = {k: {_v: resp[k][0][_v] for _v in v} for k, v in key_selection.items()}
except:
import traceback
ret = "Error encountered while fetching weather data!\n" + traceback.format_exc()
return str(ret)
# Define tool information inside the function
get_weather.tool_info = {
"tool_name": "get_weather",
"tool_title": "get weather",
"tool_description": "Get current weather information for the specified city.",
"tool_params": [
{"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True},
]
}
def search_news(
keyword: str,
max_results: int = 5
) -> str:
"""
Search news based on keywords
:param keyword: Search keyword
:param max_results: Maximum number of results to return, default is 5
:return: News search results
"""
results = f"By searching for {keyword}, I've found {max_results} related pieces of information."
return str(results)
# Define tool information inside the function
search_news.tool_info = {
"tool_name": "search_news",
"tool_title": "search news",
"tool_description": "Search news based on keywords.",
"tool_params": [
{"name": "keyword", "description": "Search keyword", "type": "string", "required": True},
{"name": "max_results", "description": "Maximum number of results to return", "type": "int", "required": False},
]
}
def get_user_info(
user_id: str
) -> str:
"""
Get user information
:param user_id: User ID
:return: User information
"""
if not isinstance(user_id, str):
raise TypeError("User ID must be a string")
try:
# Assume using a user info API; this is a sample URL
url = f"https://api.example.com/users/{user_id}"
response = requests.get(url)
response.raise_for_status()
user_data = response.json()
user_info = {
"name": user_data.get("name"),
"email": user_data.get("email"),
"created_at": user_data.get("created_at")
}
except:
import traceback
user_info = "Error encountered while fetching user data!\n" + traceback.format_exc()
return str(user_info)
# Define tool information inside the function
get_user_info.tool_info = {
"tool_name": "get_user_info",
"tool_description": "Retrieve information for the specified user.",
"tool_params": [
{"name": "user_id", "description": "User ID", "type": "string", "required": True},
]
}
# Custom Tools
tools = [get_weather, search_news, get_user_info] # including all tools
# Initialize Agent
# Replace with your model parameters, API key, and base URL
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url", tools=tools)
query = "How is the weather in Sanya today?"
response = agent.run(query, stream=False) # Use agent to run the query
print(response)The Tool Generator is a module for automatically generating tool code. It can create the corresponding tool code based on the text description provided by users and save it to the specified directory. This functionality is particularly useful for quickly generating API call tools, data processing tools, and more.
Usage example
Here is an example code using the Tool Generator:
| Version | Changes | Urgency | Date |
|---|---|---|---|
| v0.5.0 | # LightAgent v0.5.0 Release Notes We are pleased to announce the official release of LightAgent v0.5.0. ## 📦 Upgrade Guide Dependency Changes: ```bash pip install --upgrade lightagent>=0.5.0 ``` ## 🆕 New Features - **Runtime Toolset Constraint**: Added support for passing `tool` parameter during `run` execution to limit the available toolset for the current session, enabling more granular control and security. - **Improved Debug Configuration**: Enhanced debug settings for bet | Low | 2/21/2026 |


