Skip to main content

LightAgent: Lightweight AI agent framework with memory, tools & tree-of-thought. Supports multi-agent collaboration, self-learning, and major LLMs (OpenAI/DeepSeek/Qwen). Open-source with MCP/SSE protocol integration.

Project description

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀 – small footprint, big potential. 🌟(Open-source Agentic framework)

LightAgent is an ultra‑lightweight, open‑source framework that now natively supports Skills — letting you compose reusable capabilities with persistent memory, tool use, and tree‑of‑thought reasoning. It streamlines multi‑agent collaboration (build self‑learning agents in one step), connects to MCP over stdio and SSE, runs on any modern LLM (OpenAI, DeepSeek, Qwen, and more), and outputs OpenAI‑compatible streaming APIs for instant drop‑in with any chat interface. Small, modular, and skill‑ready — spin it up in five minutes.


News

  • new[2026-06-24] LightAgent v0.9.0 Development: Adds checkpointed LightFlow workflows with resume/rerun support, approval nodes, richer step status and trace metadata, reusable Guardrails templates, stronger MemoryPolicy controls, and the first SharedMemoryPool prototype.
  • new[2026-06-14] LightAgent v0.8.1 Development: Adds MemoryScope metadata conventions, stricter MemoryPolicy provenance filters, and guidance for separating trace, user memory, self-reflection memory, and LightSwarm delegation state.
  • [2026-06-02] LightAgent v0.8.0 Development: Adds initial LightFlow workflow orchestration for deterministic multi-step agent execution with DAG dependencies, step output passing, retries, and flow trace events.
  • [2026-05-29] LightAgent v0.7.0 Development: Adds opt-in trace observability with structured run/model/tool/error events, agent.export_trace(), and prompt-safe model request summaries for production debugging.
  • [2026-05-28] LightAgent v0.6.5 Released: Adds opt-in structured run results, structured streaming events, catchable LightAgent errors, and tool argument validation while keeping legacy agent.run() and stream=True behavior compatible.
  • [2026-05-27] LightAgent v0.6.4 Released: Improves runtime tool dispatch reliability, adds structured error codes and troubleshooting guidance, expands OpenAI-compatible provider documentation for OpenRouter and local models, and updates browser-use integration examples.

Older release notes are available on GitHub Releases.


lightswarm_demo_en.png

✨ Features

  • Lightweight and Efficient 🚀: Minimalist design, quick deployment, suitable for various application scenarios. (No LangChain, No LlamaIndex) The core framework stays small, modular, and fully open source while using focused dependencies for provider, MCP, memory, and tracing integrations.
  • Memory Support 🧠: Supports custom long-term memory for each user, natively supporting the mem0 memory 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.
  • Workflow Orchestration 🔁: LightFlow chains agents into deterministic multi-step workflows with explicit dependencies, step output passing, retries, checkpointed run records, resume/rerun support, approval nodes, fallback agents, and traceable execution.
  • Shared Memory Prototype 🧠: SharedMemoryPool provides append-first in-memory shared memory with provenance metadata, scoped retrieval, and MemoryPolicy-compatible results for multi-agent experiments.
  • Independent Execution 🤖: Tasks and tool calls are completed autonomously without human intervention.
  • Multi-Model Support 🔄: Compatible with OpenAI-style providers such as OpenAI, OpenRouter, Zhipu ChatGLM, Baichuan, StepFun, DeepSeek, Qwen, vLLM, llama.cpp, and other OpenAI-compatible endpoints.
  • Streaming API 🌊: Supports OpenAI streaming format API service output, seamlessly integrates with mainstream chat frameworks, enhancing user experience.
  • Trace Observability 🔎: Opt-in trace=True run traces record structured run lifecycle, model request summaries, tool calls, tool results, and errors without changing the default string return value.
  • Runtime Hooks 🧩: Ordered hooks=[...] middleware can observe, replace, or block run, model, tool, memory, and LightFlow step phases while recording hook decisions in trace events.
  • Guardrails Templates 🛡️: Reusable input/tool/output guardrail templates help block private data, require confirmation for sensitive tools, validate high-risk parameters, and redact sensitive output.
  • 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.

🧭 Architecture At A Glance

Layer Main API Use it when you need
Single agent runtime LightAgent One agent with model calls, tools, memory, streaming, trace, and guardrails.
Multi-agent routing LightSwarm Role-based delegation across specialized agents.
Deterministic workflow LightFlow Ordered DAG workflows, retries, checkpoints, approvals, resume, and rerun.
Tools and integrations tools, ToolRegistry, MCP Python tools, generated tools, runtime tool loading, or MCP tool servers.
Memory boundary MemoryPolicy, MemoryScope Tenant isolation, provenance, trust, expiration, and write admission controls.
Shared memory prototype SharedMemoryPool In-memory shared memory experiments across agents.
Safety controls input_guardrails, tool_guardrails, output_guardrails Privacy blocking, sensitive tool confirmation, high-risk parameter checks, and output redaction.
Runtime hooks hooks, HookContext, HookDecision Policy, audit, redaction, routing, and payload mutation at lifecycle boundaries.
Observability trace=True, agent.export_trace() Structured run, model, tool, error, and workflow trace events.

Core Usage Patterns

LightAgent keeps the default call path simple while allowing production controls to be added incrementally.

Pattern Minimal call Notes
Basic response agent.run(query) Returns a string by default.
Streaming agent.run(query, stream=True) Returns OpenAI-compatible streaming chunks.
Structured result agent.run(query, result_format="object") Returns content plus structured metadata.
Trace agent.run(query, trace=True) Records events without changing the default string return.
User memory agent.run(query, user_id="alice") Uses the configured memory backend and memory policy.
Tools LightAgent(..., tools=[fn]) Functions should expose tool_info metadata.
Guardrails LightAgent(..., input_guardrails=[...]) Add input, tool, and output policies per agent.
Runtime hooks LightAgent(..., hooks=[fn]) Observe, replace, or block lifecycle payloads.
Workflow LightFlow().step(...).run(query) Use for deterministic multi-step execution.

🧩 Multi-agent troubleshooting (failure map)

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.

📋 FAQ

For common installation, model provider, tool, memory, MCP, Skills, streaming, and LightSwarm questions, see FAQ.

For deterministic multi-step workflows, checkpointed run records, resume/rerun, approval nodes, fallback agents, and step status tracking, see LightFlow.

For custom tool creation, runtime tools, ToolRegistry, ToolLoader, AsyncToolDispatcher, and MCP tool integration, see Tools Guide.

For shared long-term memory or graph memory deployments, review the Memory Security Guidance.

For lightweight shared memory experiments, see SharedMemoryPool.

For memory write admission, expiration-aware retrieval, and low-quality memory write blocking, see Memory Admission And Mutation Controls.

For separating trace, user memory, self-reflection memory, and LightSwarm delegation state, see Memory, Trace, And Swarm Boundaries.

For input, tool, and output safety policies, see Guardrails.

For runtime middleware that can observe, replace, or block lifecycle payloads, see Runtime Hooks.

For OpenRouter, local LLM, and OpenAI-compatible provider setup, see Model Provider Configuration.

For structured error codes and troubleshooting hints, see Error Handling.

For v0.7.0 trace observability, see Trace Observability.

For browser-use integration with recent browser-use versions, see browser-use Integration.


🚧 Coming Soon

  • 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.

🌟 Why Choose LightAgent?

  • 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.

🛠️ Quick Start

Install the latest version of LightAgent

pip install lightagent

(Optional installation) Install the Mem0 package via pip:

pip install mem0ai

Alternatively, you can use Mem0 on a hosted platform by clicking here.

Hello World Example Code

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)

Inspect a Run Trace (v0.7.0)

Tracing is opt-in and keeps the default agent.run() behavior backward compatible.

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Checkpoint a LightFlow Run (v0.9.0)

LightFlow can persist workflow checkpoints and resume failed runs without starting from the first step again.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

Use SharedMemoryPool (v0.9.0)

SharedMemoryPool is a lightweight in-memory prototype for multi-agent shared memory experiments.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Set Model Self-Perception via System Prompt

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)

Tool Example Code

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]


Function Details

README keeps the core usage model in one place. Longer examples, adapter-specific setup, and production guidance live in the dedicated docs pages.

1. Detachable Memory Module (mem0)

LightAgent accepts any memory backend that provides store(data, user_id) and retrieve(query, user_id). This keeps memory detachable: you can start with a simple custom class, use mem0, or plug in a vector/graph memory adapter without changing agent code.

Use user_id to isolate conversations, and use MemoryPolicy when memory is shared across users, tenants, agents, or traces.

from LightAgent import LightAgent, MemoryPolicy

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=your_memory_backend,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allowed_sources=("user", "reflection"),
        allowed_scopes=("user", "agent"),
        reject_duplicate_writes=True,
        min_write_length=8,
    ),
)

response = agent.run("Remember that I prefer concise reports.", user_id="alice")

See Memory Security Guidance, Memory Admission And Mutation Controls, and Memory, Trace, And Swarm Boundaries.

2. Tool Integration

Use Python functions with tool_info metadata to expose controlled capabilities to an agent. LightAgent can also work with runtime tools, ToolRegistry, ToolLoader, AsyncToolDispatcher, generated tools, and MCP tools.

from LightAgent import LightAgent

def get_order_status(order_id: str) -> str:
    return f"Order {order_id} is being processed."

get_order_status.tool_info = {
    "tool_name": "get_order_status",
    "tool_description": "Get the status of an order.",
    "tool_params": [
        {"name": "order_id", "description": "Order ID", "type": "string", "required": True},
    ],
}

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    tools=[get_order_status],
)

For advanced tool loading, generated tools, async dispatch, and MCP integration, see Tools Guide.

3. Tool Generator

agent.create_tool() can generate tool code from API documentation or natural-language descriptions. It is useful when converting an internal API document into callable Python tools.

Keep generated tools in a reviewed tools directory, test them before production use, and avoid committing generated or experimental local tools unless they are part of the public package.

agent.create_tool(
    "Create a tool that calls the internal order status API.",
    tools_directory="tools",
)

4. Tree of Thought (ToT)

Enable tree_of_thought=True when a task needs explicit planning and reflection before tool use or final response generation. ToT is best for complex multi-step reasoning, tool selection, and tasks where the agent should inspect its plan before acting.

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    tree_of_thought=True,
    tot_model="gpt-4.1",
    tot_api_key="your_api_key",
    tot_base_url="your_base_url",
)

5. Multi-Agent Collaboration

LightSwarm routes work across specialized agents for role-based delegation and multi-agent task handling. Use it when one front-facing agent should delegate to domain agents such as support, HR, finance, research, or data analysis.

Keep each agent's role narrow, give each agent clear boundaries, and avoid letting delegated agents write unrelated long-term memory unless the memory policy allows it.

from LightAgent import LightAgent, LightSwarm

frontdesk = LightAgent(name="frontdesk", role="Route requests to the right specialist.")
finance = LightAgent(name="finance", role="Answer finance approval questions.")

swarm = LightSwarm()
swarm.register_agent(frontdesk, finance)
result = swarm.run(agent=frontdesk, query="How do I approve a vendor payment?")

For debugging role drift or cross-agent memory issues, see Multi-agent failure map.

6. Streaming API

agent.run(query, stream=True) returns OpenAI-compatible streaming chunks and remains backward compatible with existing integrations. Use it for chat UIs, long responses, and agent services that should start sending output before the full answer is complete.

for chunk in agent.run("Write a short report about AI agents.", stream=True):
    print(chunk)

7. Agent Self-Learning

Self-learning can be combined with a memory backend so an agent can retain scenario-specific knowledge across users or sessions. In production, pair self-learning with MemoryPolicy so low-quality, private, expired, or unrelated content does not enter long-term memory.

Recommended production controls:

  • Use namespace to separate tenants or environments.
  • Use allowed_sources, allowed_scopes, and allowed_agent_names to limit retrieved memory.
  • Use memory_write_admission, reject_write_patterns, min_write_length, and reject_duplicate_writes to control writes.
  • Use enforce_expires_at=True when memory records carry expiration metadata.

8. Langfuse Log Tracking

LightAgent can send trace data to Langfuse through tracetools configuration. For most local debugging, start with built-in trace events:

result = agent.run("Debug this workflow.", result_format="object", trace=True)
print(result.trace_id)
print(agent.export_trace())

See Trace Observability for event shapes and production debugging guidance.

9. Agent Assessment

Agent assessment is planned for future versions and will focus on evaluating agent behavior against business scenarios.

10. LightFlow Workflows

LightFlow is the deterministic workflow layer. Use it when a task should run through known steps instead of relying on free-form agent planning.

Key v0.9.0 workflow controls:

  • Step states: pending, running, success, failed, skipped, waiting_approval.
  • DAG validation: flow.validate(strict=True) checks unknown dependencies, cycles, and isolated steps.
  • Step controls: timeout, max_retry, cancel_if, fallback_agent, requires_approval, and approval_handler.
  • Persistence: JsonLightFlowStore stores run records and checkpoints.
  • Recovery: flow.resume(run_id) continues incomplete runs; flow.rerun_step(run_id, step_name) reruns one step and downstream steps.
  • Inspection: flow.get_run(run_id) and flow.list_runs() expose workflow state for UIs.
from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

store = JsonLightFlowStore(".lightflow_runs")
draft_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
review_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
backup_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

def approve(step, context):
    return {"approved": True, "reason": "Approved by policy."}

flow = (
    LightFlow(store=store)
    .step("draft", agent=draft_agent, timeout=30, max_retry=2)
    .step(
        "review",
        agent=review_agent,
        depends_on=["draft"],
        requires_approval=True,
        approval_handler=approve,
        fallback_agent=backup_agent,
    )
)

validation = flow.validate(strict=True)
if validation["errors"]:
    raise ValueError(validation["errors"])

result = flow.run("Prepare a customer support summary.", run_id="case-001", trace=True)
record = flow.get_run("case-001")

See LightFlow for complete workflow examples.

11. Guardrails

Guardrails are lightweight policy hooks around agent execution:

  • Input guardrails inspect the user query before model execution.
  • Tool guardrails inspect tool calls before execution.
  • Output guardrails inspect or redact final non-streaming output.
from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({
            "amount": lambda value: value is not None and float(value) <= 1000,
        }),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Use default guardrail templates for privacy-sensitive input, sensitive tool confirmation, high-risk parameter validation, and output redaction. See Guardrails.

12. Runtime Hooks

Runtime hooks are ordered middleware for production policies that need to observe, replace, or block lifecycle payloads without changing the default agent.run() behavior.

from LightAgent import HookDecision, LightAgent


def redact_before_model(ctx):
    if ctx.phase != "before_model_request":
        return None

    params = dict(ctx.payload["params"])
    messages = list(params["messages"])
    messages[-1] = {
        **messages[-1],
        "content": messages[-1]["content"].replace("secret-token", "[REDACTED]"),
    }
    params["messages"] = messages
    return HookDecision.replace({"params": params})


def block_dangerous_tool(ctx):
    if ctx.phase == "before_tool_call" and ctx.payload["tool_name"] == "delete_file":
        return HookDecision.block("delete_file requires manual approval")
    return None


agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    hooks=[redact_before_model, block_dangerous_tool],
)

result = agent.run("Summarize this secret-token safely.", result_format="object", trace=True)
print(result.content)
print(result.trace)

Hooks can target before_run, before_model_request, after_model_response, before_tool_call, after_tool_result, before_memory_write, and after_memory_write. LightFlow(hooks=[...]) also supports step lifecycle hooks such as before_flow_step, after_flow_step, on_approval_required, on_resume, and on_rerun. See Runtime Hooks.

13. SharedMemoryPool

SharedMemoryPool is an in-memory shared memory prototype for multi-agent experiments. It is append-first and keeps provenance metadata, making it useful for testing how multiple agents share information before adopting a durable vector or graph memory backend.

Use it with MemoryPolicy so each agent retrieves only memory that matches the expected namespace, source, scope, trust, confidence, or agent name.

Mainstream Agent Model Support

LightAgent works with OpenAI-compatible chat completion endpoints, including OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama-compatible endpoints, and self-hosted gateways.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.


Use Cases

  • Intelligent Customer Service: Provide efficient customer support through multi-turn dialogue and tool integration.
  • Data Analysis: Use Tree of Thought and multi-agent collaboration to handle complex data analysis tasks.
  • Automated Tools: Quickly build customized tools through automated tool generation.
  • Educational Assistance: Provide personalized learning experiences using memory modules and streaming API.

🛠️ Contribution Guidelines

We welcome any form of contribution! Whether it's code, documentation, tests, or feedback, it's a tremendous help to the project. If you have great ideas or find bugs, please submit an Issue or Pull Request. Here are the contribution steps:

  1. Fork this project: Click the Fork button at the top right corner to copy the project to your GitHub repository.
  2. Create a branch: Create your development branch locally:
    git checkout -b feature/YourFeature
    
  3. Submit changes: After finishing development, submit your changes:
    git commit -m 'Add some feature'
    
  4. Push the branch: Push the branch to your remote repository:
    git push origin feature/YourFeature
    
  5. Submit Pull Request: Submit a Pull Request on GitHub and describe your changes.

We will review your contributions promptly. Thank you for your support! ❤️


🙏 Acknowledgments

Shanghai Wanxing AI and Professor Zhang Liwen's research group from the School of Statistics and Data Science at Shanghai University of Finance and Economics have jointly open-sourced a new generation intelligent agent framework called LightAgent.The development and implementation of LightAgent owe much to the inspiration and support from the following open-source projects, especially the outstanding projects and teams:

  • MCP: Thanks to mcp for providing the Model Context Protocol (MCP), which offers a standardized infrastructure for the dynamic tool integration of LightAgent.
  • mem0: Thanks to mem0 for providing the memory module, which offers strong support for LightAgent's context management.
  • Swarm: Thanks to Swarm for designing ideas for multi-agent collaboration, laying the groundwork for LightAgent's multi-agent features.
  • ChatGLM3: Thanks to ChatGLM3 for providing high-performance Chinese large model support and design inspiration.
  • Qwen: Thanks to Qwen for providing high-performance Chinese large model support.
  • DeepSeek-V3: Thanks to DeepSeek-V3 for providing high-performance Chinese large model support.
  • StepFun: Thanks to step for providing high-performance Chinese large model support.

📄 License

LightAgent is licensed under the Apache 2.0 License. You can freely use, modify, and distribute this project, but please adhere to the terms of the license.


📬 Contact Us

If you have any questions or suggestions, please feel free to contact Wanxing AI or Professor Zhang Liwen from the School of Statistics and Data Science at Shanghai University of Finance and Economics:

We look forward to your feedback and work together to make LightAgent even stronger! 🚀


LightAgent - Making intelligence lighter, making the future simpler. 🌈

LightAgent —— A lightweight, flexible, and powerful active Agent framework that assists you in quickly building intelligent applications!

Star History

Star History Chart

Paper

@misc{2509.09292,
Author = {Weige Cai and Tong Zhu and Jinyi Niu and Ruiqi Hu and Lingyao Li and Tenglong Wang and Xiaowu Dai and Weining Shen and Liwen Zhang},
Title = {LightAgent: Production-level Open-source Agentic AI Framework},
Year = {2025},
Eprint = {arXiv:2509.09292},
Eprinttype = {arXiv},
Eprintclass = {cs.AI},
Url = {https://arxiv.org/abs/2509.09292},
Doi = {10.48550/arXiv.2509.09292},
Note = {Submitted on 11 Sep 2025}
}

Security

MseeP.ai Security Assessment Badge

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀 超轻量、可“成长”的智能体框架,现已原生支持Skill

🚀 LightAgent 不再只是“聊天”,而是真正的“完成任务”。LightAgent 把记忆(mem0)、工具(Tools)、思维树(ToT)和多智能体协作融合进一个极简的包中,而你只需 一行代码 就能构建一个能自我学习、按需加载Skill的智能体 —— 就像给大模型装上“招式库”与“执行大脑”。

🔥 为什么开发者会爱上它?

  • Skill 原生支持:像管理代码一样管理 AI 能力。把 PDF 处理、代码审查、SOP 流程打包成可复用的 Skill,Agent 按需调用 —— 告别 prompt 堆积,迎接工程化 AI。
  • 比 OpenAI Swarm 更简易的多智能体协作:无需复杂编排,轻松构建“Agent 小分队”,并行拆解复杂任务。
  • MCP 协议(stdio/sse)开箱即连:无缝接入外部数据源与工具,Agent 的“手”从此无限延伸。
  • 零成本切换底层模型:OpenAI、智谱 ChatGLM、DeepSeek、阶跃星辰、通义千问…… 想用哪个用哪个。
  • 开箱即用的 API 服务:标准 OpenAI 流式输出格式,可直接接入主流 Chat 前端(如 NextChat、LobeChat),秒变生产级应用。

🌟 LightAgent = 轻 + 灵 + 可扩展
从个人脚本到企业级 Workflow,它帮你把“聪明的模型”变成“可靠的员工”。
Star 我们,尝试你的第一个 Skill 驱动的 Agent —— 改动几行代码,见证 AI 真正“动手做事”。


新闻

  • new[2026-06-24] LightAgent v0.9.0 开发版:新增可持久化 LightFlow checkpoint、resume/rerun、审批节点、更清晰的步骤状态和 trace 元数据,同时补充 Guardrails 模板、MemoryPolicy 控制和 SharedMemoryPool 原型。
  • new[2026-06-14] LightAgent v0.8.1 开发版:新增 MemoryScope 元数据约定、MemoryPolicy 来源/范围/可信度过滤,并补充 Trace、用户记忆、自我反思记忆和 LightSwarm 委托状态的边界说明。
  • [2026-06-02] LightAgent v0.8.0 开发版:新增 LightFlow 工作流编排能力,支持确定性多步骤 Agent 执行、DAG 依赖、步骤输出传递、重试和 flow trace 事件。
  • [2026-05-29] LightAgent v0.7.0 开发版:新增可选的结构化 Trace 可观测能力,支持记录运行生命周期、模型请求摘要、工具调用、工具结果和错误事件,并提供 agent.export_trace() 便于生产调试。
  • [2026-05-28] LightAgent v0.6.5 正式发布:新增可选结构化运行结果、结构化流式事件、可捕获的 LightAgent 错误和工具参数校验,同时保持默认 agent.run()stream=True 行为兼容。
  • [2026-05-27] LightAgent v0.6.4 正式发布:提升运行时工具调度可靠性,新增结构化错误码和排查文档,扩展 OpenAI 兼容模型配置说明。

历史版本说明请查看 GitHub Releases


lightswarm_demo_cn.png

✨ 特性

  • 轻量高效 🚀:极简设计,快速部署,适合各种规模的应用场景。(No LangChain, No LlamaIndex)核心框架保持小而清晰,按需使用模型、MCP、记忆和可观测相关依赖,完全开源。
  • 记忆支持 🧠:支持为每个用户自定义长期记忆,原生支持 mem0 记忆模块,实现对话过程中自动管理用户个性化记忆,让 Agent 更智能。
  • 自主学习 📚️:每个agent拥有自主学习能力,并且拥有权限的管理员可以管理每个agent。
  • 工具集成 🛠️:支持自定义工具(Tools)和MCP工具集成,灵活扩展,满足多样化需求。
  • 复杂目标 🌳:内置带反思的思维树(ToT)模块,支持复杂任务分解和多步推理,提升任务处理能力。
  • 多智能体协同 🤖:比Swarm更简单的多智能体协同,内置的LightSwarm实现意图判断和任务转移功能,能够更智能地处理用户输入,并根据需要将任务转移给其他代理。
  • 独立执行 🤖:无人为干预自主完成任务工具调用。
  • 多模型支持 🔄:兼容 OpenAI、智谱 ChatGLM、百川大模型、阶跃星辰、DeepSeek、Qwen 系列大模型。
  • 流式 API输出 🌊:支持 OpenAI 流格式 API 服务输出,无缝接入主流 Chat 框架,提升用户体验。
  • Trace 可观测性 🔎:通过 trace=True 可选开启结构化运行轨迹,记录运行开始/结束、模型请求摘要、工具调用、工具结果和错误,同时保持默认字符串返回行为不变。
  • Runtime Hooks 🧩:通过有序 hooks=[...] 中间件观察、替换或阻断运行、模型、工具、记忆和 LightFlow 步骤阶段,并将 hook 决策写入 trace。
  • Tools工具生成器 🚀:只需将您的API文档交给[Tools工具生成器],它将自动化地为您打造专属的tools,助您在短短1小时内快速构建数百个个性化的自定义工具,提升效率,释放您的创新潜能。
  • agent自我学习 🧠️:每个agent拥有自己的场景记忆能力,拥有从用户的对话中进行自我学习能力。
  • 自适应tools机制 🛠️:支持添加无限量tools,在上万个工具中让大模型过滤无关工具后再发送给大模型,可大幅度降低Token消耗。
  • 工作流编排 🔁:LightFlow 将多个 Agent 编排为确定性多步骤工作流,支持显式依赖、步骤输出传递、重试、checkpoint、resume/rerun、审批节点、fallback agent 和可追踪执行。
  • 共享记忆原型 🧠:SharedMemoryPool 提供带来源元数据和范围检索的追加式内存共享记忆,适合多 Agent 实验。
  • Guardrails 模板 🛡️:可复用的输入、工具和输出安全策略模板,可用于隐私拦截、敏感工具确认、高风险参数校验和输出脱敏。

🧭 架构速览

层级 主要 API 适用场景
单 Agent 运行时 LightAgent 一个 Agent 的模型调用、工具、记忆、流式输出、trace 和 guardrails。
多 Agent 路由 LightSwarm 在多个专业 Agent 之间进行角色化委托。
确定性工作流 LightFlow DAG 工作流、重试、checkpoint、审批、resume 和 rerun。
工具与集成 toolsToolRegistry、MCP Python 工具、生成工具、运行时加载工具或 MCP 工具服务。
记忆边界 MemoryPolicyMemoryScope 租户隔离、来源、可信度、过期和写入准入控制。
共享记忆原型 SharedMemoryPool 多 Agent 共享记忆实验。
安全控制 input_guardrailstool_guardrailsoutput_guardrails 隐私拦截、敏感工具确认、高风险参数校验和输出脱敏。
Runtime Hooks hooksHookContextHookDecision 在生命周期边界实现策略、审计、脱敏、路由和 payload 改写。
可观测性 trace=Trueagent.export_trace() 结构化运行、模型、工具、错误和工作流事件。

核心使用模式

LightAgent 保持默认调用路径简单,同时允许逐步加入生产级控制。

模式 最小调用 说明
基础响应 agent.run(query) 默认返回字符串。
流式输出 agent.run(query, stream=True) 返回 OpenAI 兼容的流式 chunk。
结构化结果 agent.run(query, result_format="object") 返回内容和结构化元数据。
Trace agent.run(query, trace=True) 记录事件,不改变默认字符串返回。
用户记忆 agent.run(query, user_id="alice") 使用配置的记忆后端和 MemoryPolicy。
工具 LightAgent(..., tools=[fn]) 函数应提供 tool_info 元数据。
Guardrails LightAgent(..., input_guardrails=[...]) 为 Agent 添加输入、工具和输出策略。
Runtime Hooks LightAgent(..., hooks=[fn]) 观察、替换或阻断生命周期 payload。
工作流 LightFlow().step(...).run(query) 用于确定性多步骤执行。

📋 文档

  • 常见安装、模型、工具、记忆、MCP、Skills、流式输出和 LightSwarm 问题,请查看 FAQ
  • 确定性多步骤工作流、checkpoint、resume/rerun、审批节点、fallback agent 和步骤状态,请查看 LightFlow
  • 自定义工具、运行时工具、ToolRegistry、ToolLoader、AsyncToolDispatcher 和 MCP 工具集成,请查看 Tools Guide
  • 共享长期记忆或图记忆部署,请查看 Memory Security Guidance
  • SharedMemoryPool 原型请查看 SharedMemoryPool
  • 记忆写入准入、过期检索和低质量写入拦截,请查看 Memory Admission And Mutation Controls
  • 输入、工具和输出安全策略,请查看 Guardrails
  • 运行期中间件和生命周期 payload 改写,请查看 Runtime Hooks
  • OpenRouter、本地模型和 OpenAI 兼容配置,请查看 Model Provider Configuration
  • Trace 可观测能力请查看 Trace Observability

🚧 即将推出

  • 智能体协同通讯 🛠️:智能体之间还可以共享信息和传递消息,实现复杂的信息通讯和任务协同。
  • Agent 测评 📊:内置 Agent 测评工具,方便评估和优化你构建的Agent,对齐业务场景,持续提升智能水平。

🌟 为什么选择 LightAgent?

  • 开源免费 💖:完全开源,社区驱动,持续更新,欢迎贡献!
  • 易于上手 🎯:文档详尽,示例丰富,快速上手,轻松集成到你的项目中。
  • 社区支持 👥:活跃的开发者社区,随时为你提供帮助和解答。
  • 高性能 ⚡:优化设计,高效运行,满足高并发场景需求。

🛠️ 快速开始

安装LightAgent最新版本

pip install lightagent

(可选安装)通过 pip 安装 Mem0 包:

pip install mem0ai

或者,您可以通过一键点击在托管平台上使用 Mem0,点击这里

Hello world 示例代码

from LightAgent import LightAgent

# 初始化 Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url= "your_base_url")

# 运行 Agent
response = agent.run("你好,你是谁?")
print(response)

查看运行 Trace(v0.7.0)

Trace 默认关闭,需要显式传入 trace=True,不会改变原有 agent.run() 默认返回字符串的兼容行为。

from LightAgent import LightAgent

# 初始化 Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url= "your_base_url")

# 以结构化对象形式查看运行轨迹
result = agent.run("你好,你是谁?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

通过system提示词设定模型自我认知

from LightAgent import LightAgent

# 初始化 Agent
agent = LightAgent(
     role="请记住你是LightAgent,一个可以帮助用户完成多工具使用的有用助手。",  # system角色描述
     model="gpt-4.1",  # 支持的模型:openai, chatglm, deepseek, qwen 等
     api_key="your_api_key",  # 替换为你的大模型服务商 API Key
     base_url="your_base_url",  # 替换为你的大模型服务商 api url
 )
# 运行 Agent
response = agent.run("请问你是谁?")
print(response)

使用工具示例代码

from LightAgent import LightAgent


# 定义工具
def get_weather(city_name: str) -> str:
    """
    Get the current weather for `city_name`
    """
    return f"查询结果: {city_name} 天气晴"
# 在函数内部定义工具信息
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "获取指定城市的当前天气信息",
    "tool_params": [
        {"name": "city_name", "description": "要查询的城市名称", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# 初始化 Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# 运行 Agent
response = agent.run("请帮我查询一下上海的天气情况")
print(response)

支持自定义无限数量的工具。

多个工具示例: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


功能详解

README 保留核心使用模型;更长的示例、适配器配置和生产实践放在专门文档中。

1. 可拆卸记忆模块(mem0

LightAgent 接受任何提供 store(data, user_id)retrieve(query, user_id) 的记忆后端。使用 user_id 隔离对话;当记忆跨用户、租户、Agent 或 trace 共享时,应配置 MemoryPolicy

2. 工具集成

使用带 tool_info 元数据的 Python 函数向 Agent 暴露受控能力。高级运行时工具、ToolRegistry、ToolLoader、AsyncToolDispatcher 和 MCP 请查看 Tools Guide

3. Tools 工具生成器

agent.create_tool() 可以根据 API 文档或自然语言描述生成工具代码。生成工具应放在可审查的 tools 目录中,并在生产使用前测试。

4. 思维树(ToT)

当任务需要显式规划、反思和多工具选择时,启用 tree_of_thought=True

5. 多智能体协同

LightSwarm 用于在专业 Agent 之间进行角色化委托。保持每个 Agent 角色清晰,并用记忆策略约束跨 Agent 记忆写入。

6. 流式 API

agent.run(query, stream=True) 返回 OpenAI 兼容流式 chunk,适合聊天 UI 和长输出。

7. Agent 自我学习

自我学习应与记忆后端和 MemoryPolicy 配合使用,避免低质量、隐私、过期或无关内容进入长期记忆。

8. Trace 与 Langfuse

LightAgent 可通过内置 trace 或 Langfuse 配置观察运行过程。

9. Agent 测评

Agent 测评将在后续版本中围绕业务场景评估 Agent 行为。

10. LightFlow 工作流

LightFlow 是确定性工作流层,适合让任务按已知步骤执行,而不是完全依赖自由形式规划。

  • 步骤状态:pendingrunningsuccessfailedskippedwaiting_approval
  • DAG 校验:flow.validate(strict=True)
  • 步骤控制:timeoutmax_retrycancel_iffallback_agentrequires_approvalapproval_handler
  • 持久化与恢复:JsonLightFlowStoreflow.resume(run_id)flow.rerun_step(run_id, step_name)flow.get_run(run_id)flow.list_runs()

请查看 LightFlow

11. Guardrails

Guardrails 是围绕 Agent 执行的轻量策略钩子:输入策略检查用户问题,工具策略检查工具调用,输出策略检查或脱敏最终输出。

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

请查看 Guardrails

12. SharedMemoryPool

SharedMemoryPool 是多 Agent 共享记忆实验的内存原型,建议与 MemoryPolicy 配合控制 namespace、source、scope、trust、confidence 和 agent name。

主流Agent模型支持

LightAgent 兼容 OpenAI 风格 chat completion endpoint,包括 OpenAI、OpenRouter、智谱 ChatGLM、DeepSeek、Qwen、StepFun、Moonshot/Kimi、MiniMax、vLLM、llama.cpp、Ollama 兼容接口和自托管网关。

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

使用场景

  • 智能客服:通过多轮对话和工具集成,提供高效的客户支持。
  • 数据分析:利用思维树和多智能体协同,处理复杂的数据分析任务。
  • 自动化工具:通过自动化工具生成,快速构建定制化工具。
  • 教育辅助:通过记忆模块和流式 API,提供个性化的学习体验。

🛠️ 贡献指南

我们欢迎任何形式的贡献!无论是代码、文档、测试还是反馈,都是对项目的巨大帮助。如果您有好的想法或发现 Bug,请提交 Issue 或 Pull Request。以下是贡献步骤:

  1. Fork 本项目:点击右上角的 Fork 按钮,将项目复制到您的 GitHub 仓库。
  2. 创建分支:在本地创建您的开发分支:
    git checkout -b feature/YourFeature
    
  3. 提交更改:完成开发后,提交您的更改:
    git commit -m 'Add some feature'
    
  4. 推送分支:将分支推送到您的远程仓库:
    git push origin feature/YourFeature
    
  5. 提交 Pull Request:在 GitHub 上提交 Pull Request,并描述您的更改内容。

我们会在第一时间审核您的贡献,感谢您的支持!❤️


🙏 致谢

上海万行AI与上海财经大学统计与数据科学学院张立文教授课题组联合开源了新一代智能体框架 LightAgent。LightAgent 的开发和实现离不开以下开源项目的启发和支持,特别感谢这些优秀的项目和团队:

  • MCP:感谢 mcp 提供的模型上下文协议(MCP),为 LightAgent 的动态工具集成提供了标准化基础设施。
  • mem0:感谢 mem0 提供的记忆模块,为 LightAgent 的上下文管理提供了强大支持。
  • Swarm:感谢 Swarm 提供的多智能体协同设计思路,为 LightAgent 的多智能体功能奠定了基础。
  • ChatGLM3:感谢 ChatGLM3 提供的高性能中文大模型支持和设计灵感。
  • Qwen:感谢 Qwen 提供的高性能中文大模型支持。
  • DeepSeek-V3:感谢 DeepSeek-V3 提供的高性能中文大模型支持。
  • 阶跃星辰:感谢 step 提供的高性能中文大模型支持。

📄 许可证

LightAgent 采用 Apache 2.0 许可证。您可以自由使用、修改和分发本项目,但请遵守许可证条款。


📬 联系我们

如有任何问题或建议,欢迎随时联系万行AI或上海财经大学统计与数据科学学院张立文教授联系:

我们期待您的反馈,一起让 LightAgent 变得更强大!🚀


LightAgent - 让智能更轻量,让未来更简单。 🌈

LightAgent —— 轻量、灵活、强大的主动式 Agent 框架,助您快速构建智能应用!

Star History

Star History Chart

论文

@misc{2509.09292,
Author = {Weige Cai and Tong Zhu and Jinyi Niu and Ruiqi Hu and Lingyao Li and Tenglong Wang and Xiaowu Dai and Weining Shen and Liwen Zhang},
Title = {LightAgent: Production-level Open-source Agentic AI Framework},
Year = {2025},
Eprint = {arXiv:2509.09292},
Eprinttype = {arXiv},
Eprintclass = {cs.AI},
Url = {https://arxiv.org/abs/2509.09292},
Doi = {10.48550/arXiv.2509.09292},
Note = {Submitted on 11 Sep 2025}
}

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀(Próximo marco de IA Agentic)

LightAgent es un marco de trabajo activo y autónomo extremadamente ligero que cuenta con memoria (mem0), herramientas (Tools) y un árbol de pensamiento (ToT), y es completamente de código abierto. Soporta una colaboración multiagente más simple que OpenAI Swarm, permitiendo construir agentes con capacidad de autoaprendizaje en un solo paso, y admite la conexión al protocolo MCP a través de stdio y sse. El modelo subyacente es compatible con OpenAI, Zhiyu ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen y otros grandes modelos. Al mismo tiempo, LightAgent admite la salida de servicios API en formato de flujo de OpenAI, integrándose sin problemas con los principales marcos de Chat. 🌟


Noticias

  • new[2026-06-24] LightAgent v0.9.0: añade workflows LightFlow con checkpoints, resume/rerun, nodos de aprobación, estados de paso más claros, metadatos de trace, plantillas Guardrails, controles MemoryPolicy y el prototipo SharedMemoryPool.
  • [2026-06-14] LightAgent v0.8.1: añade convenciones MemoryScope y filtros MemoryPolicy por procedencia, alcance y confianza.
  • [2026-06-02] LightAgent v0.8.0: introduce LightFlow para workflows deterministas de varios pasos.

Las notas históricas están en GitHub Releases.


✨ Características

  • Ligero y eficiente 🚀: Diseño minimalista, implementación rápida, adecuado para diversas escalas de aplicaciones. (Sin LangChain, Sin LlamaIndex) 100% implementado en Python, sin dependencias adicionales, con solo 1000 líneas de código central, completamente de código abierto.
  • Soporte de memoria 🧠: Permite a cada usuario personalizar su memoria a largo plazo, soportando nativamente el módulo de memoria mem0, gestionando automáticamente la memoria personalizada del usuario durante el diálogo, haciendo que el agente sea más inteligente.
  • Aprendizaje autónomo 📚️: Cada agente tiene la capacidad de aprender de manera autónoma, y los administradores con permiso pueden gestionar cada agente.
  • Integración de herramientas 🛠️: Permite herramientas personalizadas (Tools), generación automática de herramientas y expansión flexible, satisfaciendo diversas necesidades.
  • Objetivos complejos 🌳: Módulo de árbol de pensamiento (ToT) integrado, que soporta la descomposición de tareas complejas y razonamiento de múltiples pasos, mejorando la capacidad de procesamiento de tareas.
  • Colaboración multi-agente 🤖: Colaboración multi-agente de implementación más sencilla que Swarm, con LightSwarm integrado para juzgar intenciones y transferir tareas, procesando entradas de usuario más inteligentemente y transferiendo tareas a otros agentes según sea necesario.
  • Ejecución independiente 🤖: Ejecución autónoma de llamadas a herramientas sin intervención humana.
  • Soporte para múltiples modelos 🔄: Compatible con OpenAI, ChatGLM de Zhiyun, modelos de Baichuan, DeepSeek, la serie Qwen.
  • API en flujo 🌊: Soporta salida de servicios API en formato de flujo de OpenAI, integrándose sin problemas en las principales plataformas de chat, mejorando la experiencia del usuario.
  • Generador de herramientas Tools 🚀: Simplemente proporciona tu documentación de API al [Generador de herramientas Tools] y se construirá automáticamente para ti, permitiéndote crear rápidamente cientos de herramientas personalizadas en solo una hora, aumentando la eficiencia y liberando tu potencial innovador.
  • Auto-aprendizaje del agente 🧠️: Cada agente tiene capacidad para recordar sus propios escenarios y aprender de él mismo a partir de la conversación del usuario.
  • Mecanismo de herramientas adaptativas 🛠️: Soporta añadir herramientas ilimitadas, seleccionando primero un conjunto de herramientas candidato entre miles antes de enviar el contexto al modelo de Big Data, lo que puede reducir significativamente el consumo de tokens.
  • Orquestación de workflows 🔁: LightFlow encadena agentes en workflows deterministas con dependencias explícitas, paso de salidas, reintentos, checkpoints, resume/rerun, aprobaciones, agentes fallback y trazabilidad.
  • Prototipo de memoria compartida 🧠: SharedMemoryPool ofrece memoria compartida en memoria con metadatos de procedencia, recuperación por alcance y resultados compatibles con MemoryPolicy.
  • Plantillas Guardrails 🛡️: Políticas reutilizables de entrada, herramientas y salida para bloquear datos privados, confirmar herramientas sensibles, validar parámetros de alto riesgo y redactar salidas.
  • Runtime Hooks 🧩: Middleware ordenado hooks=[...] para observar, reemplazar o bloquear fases de ejecución, modelo, herramienta, memoria y pasos LightFlow.

🧭 Arquitectura de un vistazo

Capa API principal Úsalo cuando necesites
Runtime de un agente LightAgent Un agente con modelo, herramientas, memoria, streaming, trace y guardrails.
Enrutamiento multiagente LightSwarm Delegación por roles entre agentes especializados.
Workflow determinista LightFlow DAG, reintentos, checkpoints, aprobaciones, resume y rerun.
Herramientas e integraciones tools, ToolRegistry, MCP Herramientas Python, generadas, carga en runtime o servidores MCP.
Límite de memoria MemoryPolicy, MemoryScope Aislamiento de tenants, procedencia, confianza, expiración y admisión de escritura.
Memoria compartida SharedMemoryPool Experimentos de memoria compartida entre agentes.
Seguridad input_guardrails, tool_guardrails, output_guardrails Privacidad, confirmación de herramientas, parámetros de riesgo y redacción de salida.
Runtime hooks hooks, HookContext, HookDecision Políticas, auditoría, redacción, routing y mutación de payloads en límites del ciclo de vida.
Observabilidad trace=True, agent.export_trace() Eventos estructurados de ejecución, modelo, herramienta, error y workflow.

Patrones principales de uso

LightAgent mantiene simple la llamada por defecto y permite añadir controles de producción de forma incremental.

Patrón Llamada mínima Notas
Respuesta básica agent.run(query) Devuelve string por defecto.
Streaming agent.run(query, stream=True) Devuelve chunks compatibles con OpenAI.
Resultado estructurado agent.run(query, result_format="object") Devuelve contenido y metadatos.
Trace agent.run(query, trace=True) Registra eventos sin cambiar el string por defecto.
Memoria de usuario agent.run(query, user_id="alice") Usa el backend de memoria y MemoryPolicy configurados.
Herramientas LightAgent(..., tools=[fn]) Las funciones deben exponer tool_info.
Guardrails LightAgent(..., input_guardrails=[...]) Añade políticas de entrada, herramienta y salida.
Runtime hooks LightAgent(..., hooks=[fn]) Observa, reemplaza o bloquea payloads del ciclo de vida.
Workflow LightFlow().step(...).run(query) Para ejecución determinista multi-etapa.

📋 Documentación

  • Para instalación, modelos, herramientas, memoria, MCP, Skills, streaming y LightSwarm, consulta FAQ.
  • Para workflows deterministas, checkpoints, resume/rerun, aprobaciones, fallback agents y estados de paso, consulta LightFlow.
  • Para herramientas personalizadas, ToolRegistry, ToolLoader, AsyncToolDispatcher y MCP, consulta Tools Guide.
  • Para memoria compartida o memoria de grafo, consulta Memory Security Guidance.
  • Para SharedMemoryPool, consulta SharedMemoryPool.
  • Para admisión de escritura de memoria y expiración, consulta Memory Admission And Mutation Controls.
  • Para seguridad de entrada, herramientas y salida, consulta Guardrails.
  • Para middleware runtime que observa, reemplaza o bloquea payloads, consulta Runtime Hooks.
  • Para OpenRouter, modelos locales y proveedores compatibles con OpenAI, consulta Model Provider Configuration.
  • Para trazas estructuradas, consulta Trace Observability.

🚧 Próximamente

  • Comunicación colaborativa de agentes 🛠️: Los agentes también pueden compartir información y transmitir mensajes entre sí, logrando una comunicación de información compleja y colaboración en tareas.
  • Evaluación de Agentes 📊: Herramienta de evaluación de agentes integrada, facilitando la evaluación y optimización del agente que construyas, alineándose con el escenario empresarial y mejorando continuamente su inteligencia.

🌟 ¿Por qué elegir LightAgent?

  • Código abierto y gratuito 💖: Completamente de código abierto, impulsado por la comunidad, actualizaciones continuas, ¡contribuciones bienvenidas!
  • Fácil de usar 🎯: Documentación detallada, ejemplos abundantes, integración rápida y sencilla en tu proyecto.
  • Soporte comunitario 👥: Comunidad activa de desarrolladores, lista para ayudarte y responder a tus preguntas.
  • Alto rendimiento ⚡: Diseño optimizado, funcionamiento eficiente, capaz de satisfacer demandas de alta concurrencia.

🛠️ Comenzar rápido

Instalar la última versión de LightAgent

pip install lightagent

(Instalación opcional) Instalar el paquete Mem0 a través de pip:

pip install mem0ai

O puedes utilizar Mem0 con un solo clic en la plataforma de alojamiento, haz clic aquí.

Ejemplo de código Hello world

from LightAgent import LightAgent

# Inicializar el Agente
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url= "your_base_url")

# Ejecutar el Agente
response = agent.run("Hola, ¿quién eres?")
print(response)

Inspeccionar un trace de ejecución (v0.7.0)

Trace es opcional y mantiene compatible el comportamiento por defecto de agent.run().

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Guardar checkpoint de una ejecución LightFlow (v0.9.0)

LightFlow puede persistir checkpoints y reanudar ejecuciones fallidas sin empezar desde el primer paso.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

Usar SharedMemoryPool (v0.9.0)

SharedMemoryPool es un prototipo ligero en memoria para experimentos de memoria compartida multiagente.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Establecer la auto-consciencia del modelo mediante el prompt del sistema

from LightAgent import LightAgent

# Inicializar el Agente
agent = LightAgent(
     role="Por favor recuerda que eres LightAgent, un asistente útil que puede ayudar a los usuarios a utilizar múltiples herramientas.",  # descripción del rol del sistema
     model="deepseek-chat",  # Modelos soportados: openai, chatglm, deepseek, qwen, etc.
     api_key="your_api_key",  # reemplazar por tu API Key del proveedor del modelo
     base_url="your_base_url",  # reemplazar por la URL API de tu proveedor del modelo
 )
# Ejecutar el Agente
response = agent.run("¿Quién eres?")
print(response)

Ejemplo de código utilizando herramientas

from LightAgent import LightAgent

# Definir herramienta
def get_weather(city_name: str) -> str:
    """
    Obtener el clima actual para `city_name`
    """
    return f"Resultado de consulta: El clima en {city_name} es soleado"
# Definir información de la herramienta dentro de la función
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Obtener información climática actual para la ciudad especificada",
    "tool_params": [
        {"name": "city_name", "description": "Nombre de la ciudad a consultar", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Inicializar el Agente
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# Ejecutar el Agente
response = agent.run("Ayúdame a consultar sobre el clima en Shanghái")
print(response)

Soporta una cantidad ilimitada de herramientas personalizadas.

Ejemplo de múltiples herramientas: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


Detalle de funciones

README conserva el modelo de uso central; los ejemplos largos, configuración de adaptadores y prácticas de producción viven en la documentación dedicada.

1. Módulo de memoria desmontable (mem0)

LightAgent acepta cualquier backend de memoria que implemente store(data, user_id) y retrieve(query, user_id). Usa user_id para aislar conversaciones y MemoryPolicy cuando la memoria se comparte entre usuarios, tenants, agentes o traces.

2. Integración de herramientas

Usa funciones Python con metadatos tool_info para exponer capacidades controladas al agente. Para runtime tools, ToolRegistry, ToolLoader, AsyncToolDispatcher y MCP, consulta Tools Guide.

3. Generador de herramientas

agent.create_tool() puede generar código de herramientas desde documentación de API o descripciones naturales. Revisa y prueba las herramientas antes de producción.

4. Árbol de Pensamiento (ToT)

Activa tree_of_thought=True cuando una tarea requiere planificación explícita, reflexión y selección de herramientas.

5. Colaboración multiagente

LightSwarm delega trabajo entre agentes especializados. Mantén roles claros y limita escrituras de memoria entre agentes con políticas.

6. API streaming

agent.run(query, stream=True) devuelve chunks compatibles con OpenAI para interfaces de chat y respuestas largas.

7. Autoaprendizaje del agente

El autoaprendizaje debe combinarse con memoria y MemoryPolicy para evitar contenido privado, vencido o irrelevante.

8. Trace y Langfuse

LightAgent permite observar la ejecución con traces internos o configuración Langfuse.

9. Evaluación de agentes

La evaluación de agentes se centrará en medir comportamiento frente a escenarios de negocio.

10. Workflows LightFlow

LightFlow es la capa de workflow determinista para ejecutar tareas por pasos conocidos.

  • Estados de paso: pending, running, success, failed, skipped, waiting_approval.
  • Validación DAG: flow.validate(strict=True).
  • Controles de paso: timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • Persistencia y recuperación: JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

Consulta LightFlow.

11. Guardrails

Guardrails son hooks ligeros alrededor de la ejecución: entrada, herramientas y salida.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Consulta Guardrails.

12. SharedMemoryPool

SharedMemoryPool es un prototipo en memoria para memoria compartida multiagente; combínalo con MemoryPolicy.

Soporte para modelos de agentes principales

LightAgent funciona con endpoints chat completion compatibles con OpenAI: OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama y gateways propios.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

Casos de uso

  • Atención al cliente inteligente: A través de conversaciones múltiples y la integración de herramientas, ofrecer soporte eficiente al cliente.
  • Análisis de datos: Utilizando árboles de pensamiento y colaboración multi-agente para manejar tareas complejas de análisis de datos.
  • Herramientas automatizadas: A través de la generación automática de herramientas, construir rápidamente herramientas personalizadas.
  • Asistencia educativa: A través de módulos de memoria y API en flujo, proporcionar experiencias de aprendizaje personalizadas.

🛠️ Guía de contribuciones

¡Damos la bienvenida a cualquier forma de contribución! Ya sea código, documentación, pruebas o comentarios, ¡cada aportación es de gran ayuda para el proyecto! Si tienes buenas ideas o encuentras errores, por favor presenta un Issue o un Pull Request. A continuación se presentan los pasos para contribuir:

  1. Fork este proyecto: Haz clic en el botón Fork en la parte superior derecha para copiar el proyecto a tu repositorio de GitHub.
  2. Crear una rama: Crea tu rama de desarrollo local:
    git checkout -b feature/TuCaracterística
    
  3. Enviar cambios: Después de completar el desarrollo, envía tus cambios:
    git commit -m 'Agregar alguna característica'
    
  4. Enviar la rama: Envía tu rama a tu repositorio remoto:
    git push origin feature/TuCaracterística
    
  5. Enviar Pull Request: En GitHub, envía un Pull Request y describe los cambios realizados.

Revisaremos tu contribución a la mayor brevedad posible, ¡gracias por tu apoyo!❤️


🙏 Agradecimientos

El desarrollo e implementación de LightAgent no hubiera sido posible sin la inspiración y apoyo de los siguientes proyectos de código abierto, agradecimientos especiales a estos excepcionales proyectos y equipos:

  • mem0: Agradecimientos a mem0 por proporcionar el módulo de memoria que soporta fuertemente la gestión del contexto de LightAgent.
  • Swarm: Agradecimientos a Swarm por la idea de diseño de colaboración multi-agente que establece la base de la funcionalidad multi-agente en LightAgent.
  • ChatGLM3: Agradecimientos a ChatGLM3 por el apoyo en modelos grandes de alto rendimiento en chino y la inspiración en el diseño.
  • Qwen: Agradecimientos a Qwen por el soporte en modelos grandes de alto rendimiento en chino.
  • DeepSeek-V3: Agradecimientos a DeepSeek-V3 por el soporte en modelos grandes de alto rendimiento en chino.
  • StepFun: Agradecimientos a step por el soporte en modelos grandes de alto rendimiento en chino.

📄 Licencia

LightAgent utiliza la Licencia Apache 2.0. Puedes usar, modificar y distribuir este proyecto libremente, pero asegúrate de cumplir con los términos de la licencia.


📬 Contáctanos

Si tienes alguna pregunta o sugerencia, no dudes en contactarnos:

Esperamos tus comentarios para hacer de LightAgent un proyecto aún más fuerte.🚀

  • Más herramientas 🛠️: Integrando continuamente más herramientas útiles para satisfacer más necesidades.
  • Más soporte de modelos 🔄: Ampliando continuamente el soporte para más grandes modelos para más escenarios de aplicación.
  • Más funcionalidades 🎯: Más funciones útiles, actualizaciones continuas, ¡mantente atento!
  • Más documentación 📚: Documentación detallada y ejemplos abundantes, fácil integración en tu proyecto.
  • Más soporte comunitario 👥: Comunidad activa de desarrolladores, lista para ayudarte y responder a tus preguntas.
  • Más optimización de rendimiento ⚡: Continuamente optimizando el rendimiento para satisfacer las demandas de alta concurrencia.
  • Más contribuciones de código abierto 🌟: Bienvenidas las contribuciones de código, ¡unámonos para crear un mejor LightAgent!

LightAgent - Hace que la inteligencia sea más ligera y el futuro más simple. 🌈

LightAgent —— Un marco Agentic ligero, flexible y potente, ¡te ayuda a construir aplicaciones inteligentes rápidamente!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀 (Next Generation Agentic AI Framework)

LightAgent est un cadre agentique actif extrêmement léger avec mémoire (mem0), outils (Tools), et arbre de pensée (ToT), et il est entièrement open source. Il prend en charge une collaboration multi-agents plus simple que OpenAI Swarm, permettant de construire en un seul pas des agents capables d'apprentissage autonome, et prend en charge l'accès au protocole MCP via stdio et sse. Le modèle sous-jacent prend en charge OpenAI, Zhiyu ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen et d'autres grands modèles. De plus, LightAgent prend en charge la sortie de service API au format de flux OpenAI, s'intégrant sans couture aux principaux cadres de chat. 🌟


Actualités

  • new[2026-06-24] LightAgent v0.9.0 : ajoute des workflows LightFlow avec checkpoints, reprise/rerun, nœuds d'approbation, états d'étapes plus clairs, métadonnées de trace, modèles Guardrails, contrôles MemoryPolicy et prototype SharedMemoryPool.
  • [2026-06-14] LightAgent v0.8.1 : ajoute MemoryScope et les filtres MemoryPolicy par provenance, portée et confiance.
  • [2026-06-02] LightAgent v0.8.0 : introduit LightFlow pour les workflows déterministes multi-étapes.

Les anciennes notes sont disponibles dans GitHub Releases.


✨ Features

  • Light and Efficient 🚀: Minimalist design, rapid deployment, suitable for various application scenarios. (No LangChain, No LlamaIndex) 100% implemented in Python, with no extra dependencies, core code only 1000 lines, completely open source.
  • Memory Support 🧠: Supports user-customizable long-term memory for each user, natively supporting mem0 memory module, automatically managing personalized memory during conversations to make agents smarter.
  • Autonomous Learning 📚️: Each agent has independent learning capabilities, and authorized administrators can manage each agent.
  • Tool Integration 🛠️: Supports customizable tools (Tools), automated tool generation, and flexible expansion to meet diverse needs.
  • Complex Goals 🌳: Built-in reflective Tree of Thought (ToT) module supports complex task decomposition and multi-step reasoning, enhancing task processing capabilities.
  • Multi-agent Collaboration 🤖: Multi-agent cooperation that is easier to implement than Swarm, with built-in LightSwarm for intent recognition and task transfer capabilities, intelligently handling user input and transferring tasks to other agents as needed.
  • Independent Execution 🤖: Tasks are completed autonomously without human intervention.
  • Multi-model Support 🔄: Compatible with OpenAI, Zhiyu ChatGLM, Baichuan large models, Jumpshop Star, DeepSeek, Qwen series large models.
  • Streaming API 🌊: Supports OpenAI streaming API service output, seamlessly integrating with mainstream chat frameworks, enhancing user experience.
  • Tools Generator 🚀: Just hand over your API documentation to the [Tools Generator], and it will automatically create your exclusive tools, helping you quickly build hundreds of personalized custom tools in just one hour, enhancing efficiency and unleashing your creative potential.
  • Agent Self-Learning 🧠️: Each agent has its own contextual memory capability, enabling self-learning from user conversations.
  • Adaptive Tools Mechanism 🛠️: Support for adding unlimited tools, allowing the large model to first select a candidate tool set from tens of thousands of tools, filtering out irrelevant tools before submitting context to the large model, significantly reducing token consumption.
  • Orchestration de workflows 🔁 : LightFlow chaîne des agents dans des workflows déterministes avec dépendances explicites, passage de sorties, retries, checkpoints, reprise/rerun, approbations, agents fallback et traçabilité.
  • Prototype de mémoire partagée 🧠 : SharedMemoryPool fournit une mémoire partagée en mémoire avec métadonnées de provenance, récupération par portée et résultats compatibles MemoryPolicy.
  • Modèles Guardrails 🛡️ : règles réutilisables d'entrée, d'outil et de sortie pour bloquer les données privées, confirmer les outils sensibles, valider les paramètres à risque et masquer les sorties.
  • Runtime Hooks 🧩 : middleware ordonné hooks=[...] pour observer, remplacer ou bloquer les phases run, modèle, outil, mémoire et étapes LightFlow.

🧭 Vue d'ensemble de l'architecture

Couche API principale À utiliser pour
Runtime mono-agent LightAgent Un agent avec modèle, outils, mémoire, streaming, trace et guardrails.
Routage multi-agent LightSwarm Délégation par rôle entre agents spécialisés.
Workflow déterministe LightFlow DAG, retries, checkpoints, approbations, reprise et rerun.
Outils et intégrations tools, ToolRegistry, MCP Outils Python, générés, chargement runtime ou serveurs MCP.
Frontière mémoire MemoryPolicy, MemoryScope Isolation de tenant, provenance, confiance, expiration et admission d’écriture.
Mémoire partagée SharedMemoryPool Expériences de mémoire partagée entre agents.
Sécurité input_guardrails, tool_guardrails, output_guardrails Vie privée, confirmation d’outils, paramètres à risque et redaction de sortie.
Runtime hooks hooks, HookContext, HookDecision Politique, audit, masquage, routage et mutation des payloads aux limites du cycle de vie.
Observabilité trace=True, agent.export_trace() Événements structurés de run, modèle, outil, erreur et workflow.

Modes d'utilisation principaux

LightAgent garde le chemin d’appel par défaut simple et permet d’ajouter progressivement des contrôles de production.

Mode Appel minimal Notes
Réponse simple agent.run(query) Retourne une chaîne par défaut.
Streaming agent.run(query, stream=True) Retourne des chunks compatibles OpenAI.
Résultat structuré agent.run(query, result_format="object") Retourne contenu et métadonnées.
Trace agent.run(query, trace=True) Enregistre les événements sans changer le retour par défaut.
Mémoire utilisateur agent.run(query, user_id="alice") Utilise le backend mémoire et MemoryPolicy configurés.
Outils LightAgent(..., tools=[fn]) Les fonctions doivent exposer tool_info.
Guardrails LightAgent(..., input_guardrails=[...]) Ajoute des politiques d’entrée, outil et sortie.
Runtime hooks LightAgent(..., hooks=[fn]) Observe, remplace ou bloque les payloads du cycle de vie.
Workflow LightFlow().step(...).run(query) Pour l’exécution déterministe multi-étapes.

📋 Documentation

  • Pour l'installation, les modèles, outils, mémoire, MCP, Skills, streaming et LightSwarm, consultez FAQ.
  • Pour les workflows déterministes, checkpoints, reprise/rerun, approbations, agents fallback et états d'étape, consultez LightFlow.
  • Pour les outils personnalisés, ToolRegistry, ToolLoader, AsyncToolDispatcher et MCP, consultez Tools Guide.
  • Pour la mémoire partagée ou graphe, consultez Memory Security Guidance.
  • Pour SharedMemoryPool, consultez SharedMemoryPool.
  • Pour l'admission d'écriture mémoire et l'expiration, consultez Memory Admission And Mutation Controls.
  • Pour les politiques de sécurité d'entrée, outil et sortie, consultez Guardrails.
  • Pour le middleware runtime qui observe, remplace ou bloque les payloads, consultez Runtime Hooks.
  • Pour OpenRouter, modèles locaux et fournisseurs compatibles OpenAI, consultez Model Provider Configuration.
  • Pour les traces structurées, consultez Trace Observability.

🚧 Coming Soon

  • Communication collaborative des agents 🛠️ : Les agents peuvent également partager des informations et transmettre des messages, réalisant ainsi une communication complexe des informations et une collaboration sur les tâches.
  • Agent Evaluation 📊: Built-in Agent evaluation tools for assessing and optimizing the agents you build, aligning with business scenarios, and continuously improving intelligence.

🌟 Why Choose LightAgent?

  • Open Source and Free 💖: Completely open source, community-driven, continuously updated, contributions welcomed!
  • Easy to Get Started 🎯: Detailed documentation, abundant examples, quick to start, and easy to integrate into your projects.
  • Community Support 👥: An active developer community ready to assist and answer your questions.
  • High Performance ⚡: Optimized design for efficient operation, meeting high concurrency scenario demands.

🛠️ Quick Start

Install the Latest Version of LightAgent

pip install lightagent

(Optional installation) Install the Mem0 package via pip:

pip install mem0ai

Alternatively, you can use Mem0 on a hosting platform with one-click click here.

Hello World Sample Code

from LightAgent import LightAgent

# Initialize the Agent
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url="your_base_url")

# Run the Agent
response = agent.run("Hello, who are you?")
print(response)

Inspecter une trace d’exécution (v0.7.0)

La trace est optionnelle et conserve le comportement par défaut de agent.run().

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Checkpoint d’une exécution LightFlow (v0.9.0)

LightFlow peut persister des checkpoints et reprendre une exécution échouée sans repartir du premier pas.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

Utiliser SharedMemoryPool (v0.9.0)

SharedMemoryPool est un prototype léger en mémoire pour les expériences de mémoire partagée multi-agent.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Set Agent Self-Recognition Through System Prompts

from LightAgent import LightAgent

# Initialize the Agent
agent = LightAgent(
     role="Please remember you are LightAgent, a helpful assistant that can help users utilize multiple tools.",  # system role description
     model="deepseek-chat",  # Supported models: openai, chatglm, deepseek, qwen, etc.
     api_key="your_api_key",  # Replace with your large model service provider API Key
     base_url="your_base_url",  # Replace with your large model service provider api url
 )
# Run the Agent
response = agent.run("May I ask who you are?")
print(response)

Tool Usage Sample Code

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} Weather is clear"
# Define tool information within the function
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Get the current weather information for a specified city",
    "tool_params": [
        {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Initialize the Agent
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url="your_base_url", tools=tools)

# Run the Agent
response = agent.run("Please help me check the weather condition in Shanghai")
print(response)

Supports custom tools in unlimited quantities.

Multiple tool examples: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


Detailed Function Descriptions

Le README garde le modèle d’utilisation principal ; les exemples longs, réglages d’adaptateurs et pratiques de production sont dans les docs dédiées.

1. Module mémoire détachable (mem0)

LightAgent accepte tout backend mémoire avec store(data, user_id) et retrieve(query, user_id). Utilisez user_id pour isoler les conversations et MemoryPolicy quand la mémoire est partagée.

2. Intégration d’outils

Utilisez des fonctions Python avec métadonnées tool_info pour exposer des capacités contrôlées. Pour ToolRegistry, ToolLoader, AsyncToolDispatcher et MCP, consultez Tools Guide.

3. Générateur d’outils

agent.create_tool() peut générer du code d’outil depuis une documentation API ou une description naturelle. Relisez et testez avant production.

4. Tree of Thought (ToT)

Activez tree_of_thought=True pour les tâches nécessitant planification explicite, réflexion et sélection d’outils.

5. Collaboration multi-agent

LightSwarm délègue le travail entre agents spécialisés. Gardez des rôles étroits et contrôlez les écritures mémoire.

6. API streaming

agent.run(query, stream=True) retourne des chunks compatibles OpenAI pour UI chat et longues sorties.

7. Auto-apprentissage de l’agent

L’auto-apprentissage doit être combiné à MemoryPolicy pour éviter les contenus privés, expirés ou non pertinents.

8. Trace et Langfuse

LightAgent permet d’observer l’exécution via trace intégrée ou Langfuse.

9. Évaluation des agents

L’évaluation des agents mesurera le comportement face à des scénarios métier.

10. Workflows LightFlow

LightFlow est la couche workflow déterministe pour exécuter des étapes connues.

  • États d’étape : pending, running, success, failed, skipped, waiting_approval.
  • Validation DAG : flow.validate(strict=True).
  • Contrôles d’étape : timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • Persistance et reprise : JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

Consultez LightFlow.

11. Guardrails

Les Guardrails sont des hooks légers autour de l’exécution : entrée, outils et sortie.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Consultez Guardrails.

12. SharedMemoryPool

SharedMemoryPool est un prototype en mémoire pour mémoire partagée multi-agent, à combiner avec MemoryPolicy.

Supported Mainstream Agent Models

LightAgent fonctionne avec les endpoints chat completion compatibles OpenAI : OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama et passerelles auto-hébergées.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

Use Cases

  • Intelligent Customer Service: Provide efficient customer support through multi-turn conversations and tool integration.
  • Data Analysis: Use Tree of Thought and multi-agent collaboration to process complex data analysis tasks.
  • Automated Tools: Quickly build customized tools through automated tool generation.
  • Educational Assistance: Provide personalized learning experiences through memory modules and streaming APIs.

🛠️ Contribution Guidelines

We welcome contributions of any form! Whether it's code, documentation, testing, or feedback, every bit helps the project immensely. If you have good ideas or find bugs, please submit an issue or pull request. Here are the contribution steps:

  1. Fork This Project: Click the Fork button in the upper right corner to copy the project to your GitHub repository.
  2. Create a Branch: Create your development branch locally:
    git checkout -b feature/YourFeature
    
  3. Submit Changes: After completing the development, submit your changes:
    git commit -m 'Add some feature'
    
  4. Push Branch: Push the branch to your remote repository:
    git push origin feature/YourFeature
    
  5. Submit Pull Request: Submit a pull request on GitHub and describe your changes.

We will review your contributions as soon as possible. Thank you for your support! ❤️


🙏 Acknowledgments

The development and implementation of LightAgent would not have been possible without the inspiration and support from the following open-source projects, especially the excellent teams behind them:

  • mem0: Thanks to mem0 for providing the memory module, which offers strong support for contextual management in LightAgent.
  • Swarm: Thanks to Swarm for the multi-agent collaborative design ideas that underpin the multi-agent functionality of LightAgent.
  • ChatGLM3: Thanks to ChatGLM3 for high-performance Chinese large model support and design inspiration.
  • Qwen: Thanks to Qwen for high-performance Chinese large model support.
  • DeepSeek-V3: Thanks to DeepSeek-V3 for high-performance Chinese large model support.
  • StepFun: Thanks to step for high-performance Chinese large model support.

📄 License

LightAgent is licensed under the Apache 2.0 License. You are free to use, modify, and distribute this project, but please comply with the terms of the license.


📬 Contact Us

For any questions or suggestions, feel free to contact us:

We look forward to your feedback to make LightAgent stronger! 🚀


LightAgent - Make intelligence lighter and the future simpler. 🌈

LightAgent —— A lightweight, flexible, and powerful proactive Agent framework to help you quickly build intelligent applications!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀(Nächste Generation des Agentic AI-Frameworks)

LightAgent ist ein extrem leichtgewichtiges, speicherfähiges (mem0), werkzeugbasiertes (Tools), denkbaumgestütztes (ToT) aktives Agenten-Framework, das vollständig Open Source ist. Es unterstützt eine einfachere Multi-Agenten-Kollaboration als OpenAI Swarm, ermöglicht es, in einem Schritt Agenten mit Selbstlernfähigkeiten zu erstellen, und unterstützt die Anbindung an das MCP-Protokoll über stdio und sse. Das zugrunde liegende Modell unterstützt OpenAI, Zhiyu ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen große Modelle usw. Gleichzeitig unterstützt LightAgent die Ausgabe von OpenAI Stream-Format-API-Diensten und ermöglicht eine nahtlose Integration in alle gängigen Chat-Frameworks. 🌟


Neuigkeiten

  • new[2026-06-24] LightAgent v0.9.0: ergänzt persistente LightFlow-Checkpoints, Resume/Rerun, Freigabeknoten, klarere Schrittzustände, Trace-Metadaten, Guardrails-Vorlagen, MemoryPolicy-Kontrollen und den SharedMemoryPool-Prototyp.
  • [2026-06-14] LightAgent v0.8.1: ergänzt MemoryScope-Konventionen und MemoryPolicy-Filter nach Herkunft, Umfang und Vertrauen.
  • [2026-06-02] LightAgent v0.8.0: führt LightFlow für deterministische mehrstufige Workflows ein.

Ältere Hinweise finden Sie in den GitHub Releases.


✨ Eigenschaften

  • Leicht und effizient 🚀: Minimalistisches Design, schnelle Bereitstellung, geeignet für verschiedene Anwendungsfälle. (Kein LangChain, Kein LlamaIndex) 100% Python-Implementierung, keine zusätzlichen Abhängigkeiten, der Kerncode umfasst nur 1000 Zeilen und ist vollständig Open Source.
  • Speicherunterstützung 🧠: Unterstützt benutzerdefinierte Langzeitgedächtnisse für jeden Benutzer, native Unterstützung des mem0-Speichermoduls, das die personalisierte Erinnerung des Benutzers während des Gesprächs automatisch verwaltet und den Agenten intelligenter macht.
  • Selbstlernen 📚️: Jeder Agent hat die Fähigkeit zum selbstständigen Lernen, und berechtigte Administratoren können jeden Agenten verwalten.
  • Werkzeugintegration 🛠️: Unterstützt benutzerdefinierte Werkzeuge (Tools), automatisierte Werkzeuggenerierung, flexible Erweiterung zur Erfüllung vielfältiger Anforderungen.
  • Komplexe Ziele 🌳: Integriertes, reflektierendes Denkbaum-Modul (ToT), das komplexe Aufgabenzerlegungen und mehrstufiges Denken unterstützt, um die Aufgabenbearbeitungsfähigkeit zu verbessern.
  • Multi-Agenten-Kooperation 🤖: Einfachere Implementierung der Multi-Agenten-Kooperation als Swarm, integrierte LightSwarm-Funktion zur Absichtserkennung und Aufgabenübertragung, die es ermöglicht, Benutzereingaben intelligenter zu verarbeiten und Aufgaben bei Bedarf an andere Agenten zu übertragen.
  • Unabhängige Ausführung 🤖: Selbstständige Durchführung von Aufgaben ohne menschliches Eingreifen.
  • Unterstützung mehrerer Modelle 🔄: Kompatibel mit OpenAI, Zhiyu ChatGLM, Baichuan große Modelle, StepFun, DeepSeek, Qwen-Serie große Modelle.
  • Stream-API 🌊: Unterstützt die Ausgabe von OpenAI Stream-Format-API-Diensten, nahtlose Integration in gängige Chat-Frameworks zur Verbesserung der Benutzererfahrung.
  • Werkzeuggenerator 🚀: Geben Sie einfach Ihre API-Dokumentation an den [Werkzeuggenerator] weiter, und er wird automatisch Ihre maßgeschneiderten Werkzeuge erstellen, sodass Sie in nur einer Stunde Hunderte von personalisierten benutzerdefinierten Werkzeugen schnell erstellen können, um die Effizienz zu steigern und Ihr kreatives Potenzial freizusetzen.
  • Selbstlernender Agent 🧠️: Jeder Agent hat die Fähigkeit, seine eigene Szenarienerinnerung zu entwickeln und aus den Gesprächen mit Benutzern zu lernen.
  • Adaptive Werkzeugmechanismen 🛠️: Unterstützung für die Hinzufügung unbegrenzter Werkzeuge, Auswahl von Kandidatenwerkzeugen aus Tausenden von Werkzeugen durch das große Modell, Filtern irrelevanter Werkzeuge und anschließende Einreichung des Kontexts an das große Modell, was den Token-Verbrauch erheblich senken kann.
  • Workflow-Orchestrierung 🔁: LightFlow verkettet Agenten zu deterministischen Workflows mit expliziten Abhängigkeiten, Ausgabeübergabe, Wiederholungen, Checkpoints, Resume/Rerun, Freigaben, Fallback-Agenten und nachvollziehbarer Ausführung.
  • Shared-Memory-Prototyp 🧠: SharedMemoryPool bietet gemeinsam genutzten In-Memory-Speicher mit Herkunftsmetadaten, bereichsbezogener Suche und MemoryPolicy-kompatiblen Ergebnissen.
  • Guardrails-Vorlagen 🛡️: Wiederverwendbare Eingabe-, Werkzeug- und Ausgabe-Regeln blockieren private Daten, bestätigen sensible Tools, prüfen riskante Parameter und redigieren Ausgaben.
  • Runtime Hooks 🧩: Geordnetes hooks=[...]-Middleware-System zum Beobachten, Ersetzen oder Blockieren von Run-, Modell-, Tool-, Memory- und LightFlow-Schrittphasen.

🧭 Architektur auf einen Blick

Ebene Haupt-API Nutzen Sie sie für
Einzel-Agent-Runtime LightAgent Einen Agenten mit Modell, Tools, Speicher, Streaming, Trace und Guardrails.
Multi-Agent-Routing LightSwarm Rollenbasierte Delegation zwischen spezialisierten Agenten.
Deterministischer Workflow LightFlow DAG, Wiederholungen, Checkpoints, Freigaben, Resume und Rerun.
Tools und Integrationen tools, ToolRegistry, MCP Python-Tools, generierte Tools, Runtime-Laden oder MCP-Server.
Speichergrenze MemoryPolicy, MemoryScope Tenant-Isolation, Herkunft, Vertrauen, Ablauf und Schreibzulassung.
Gemeinsamer Speicher SharedMemoryPool Experimente mit gemeinsamem Speicher zwischen Agenten.
Sicherheit input_guardrails, tool_guardrails, output_guardrails Datenschutz, Tool-Bestätigung, riskante Parameter und Ausgaberedaktion.
Runtime Hooks hooks, HookContext, HookDecision Policy, Audit, Redaktion, Routing und Payload-Mutation an Lifecycle-Grenzen.
Beobachtbarkeit trace=True, agent.export_trace() Strukturierte Run-, Modell-, Tool-, Fehler- und Workflow-Ereignisse.

Zentrale Nutzungsmuster

LightAgent hält den Standardaufruf einfach und erlaubt Produktionskontrollen schrittweise.

Muster Minimaler Aufruf Hinweise
Basisantwort agent.run(query) Gibt standardmäßig einen String zurück.
Streaming agent.run(query, stream=True) Gibt OpenAI-kompatible Chunks zurück.
Strukturiertes Ergebnis agent.run(query, result_format="object") Gibt Inhalt und Metadaten zurück.
Trace agent.run(query, trace=True) Zeichnet Ereignisse auf, ohne den Standard-String zu ändern.
Benutzerspeicher agent.run(query, user_id="alice") Nutzt konfigurierten Speicher und MemoryPolicy.
Tools LightAgent(..., tools=[fn]) Funktionen sollten tool_info bereitstellen.
Guardrails LightAgent(..., input_guardrails=[...]) Fügt Eingabe-, Tool- und Ausgabe-Policies hinzu.
Runtime Hooks LightAgent(..., hooks=[fn]) Beobachtet, ersetzt oder blockiert Lifecycle-Payloads.
Workflow LightFlow().step(...).run(query) Für deterministische mehrstufige Ausführung.

📋 Dokumentation

🚧 Bald verfügbar

  • Agent-Kooperation Kommunikation 🛠️: Agenten können Informationen austauschen und Nachrichten übermitteln, um komplexe Informationskommunikation und Aufgabenkoordination zu realisieren.
  • Agentenbewertung 📊: Integriertes Agentenbewertungstool zur einfachen Bewertung und Optimierung Ihrer erstellten Agenten, um sie an Geschäftsszenarien anzupassen und das Intelligenzniveau kontinuierlich zu verbessern.

🌟 Warum LightAgent wählen?

  • Open Source und kostenlos 💖: Vollständig Open Source, gemeinschaftsgetrieben, kontinuierliche Updates, Beiträge sind willkommen!
  • Einfach zu bedienen 🎯: Ausführliche Dokumentation, reichhaltige Beispiele, schnelle Einarbeitung, einfache Integration in Ihr Projekt.
  • Gemeinschaftsunterstützung 👥: Aktive Entwicklergemeinschaft, die Ihnen jederzeit Hilfe und Antworten bietet.
  • Hohe Leistung ⚡: Optimiertes Design, effiziente Ausführung, erfüllt die Anforderungen an hochgradige Parallelität.

🛠️ Schnellstart

Installation der neuesten Version von LightAgent

pip install lightagent

(Optional) Installieren Sie das Mem0-Paket über pip:

pip install mem0ai

Oder Sie können Mem0 mit einem Klick auf einer Hosting-Plattform verwenden, klicken Sie hier.

Hello World Beispielcode

from LightAgent import LightAgent

# Initialisieren des Agenten
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url= "your_base_url")

# Ausführen des Agenten
response = agent.run("Hallo, wer bist du?")
print(response)

Einen Run-Trace prüfen (v0.7.0)

Tracing ist optional und hält das Standardverhalten von agent.run() kompatibel.

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Einen LightFlow-Run checkpointen (v0.9.0)

LightFlow kann Workflow-Checkpoints speichern und fehlgeschlagene Runs fortsetzen, ohne beim ersten Schritt neu zu starten.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

SharedMemoryPool verwenden (v0.9.0)

SharedMemoryPool ist ein leichter In-Memory-Prototyp für gemeinsame Multi-Agent-Speicherexperimente.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Festlegen des Selbstbewusstseins des Modells durch System-Prompt

from LightAgent import LightAgent

# Initialisieren des Agenten
agent = LightAgent(
     role="Bitte erinnere dich, dass du LightAgent bist, ein nützlicher Assistent, der den Benutzern hilft, mehrere Werkzeuge zu verwenden.",  # Systemrollenbeschreibung
     model="deepseek-chat",  # Unterstützte Modelle: openai, chatglm, deepseek, qwen usw.
     api_key="your_api_key",  # Ersetzen Sie durch Ihren API-Schlüssel des großen Modells
     base_url="your_base_url",  # Ersetzen Sie durch die API-URL Ihres großen Modells
 )
# Ausführen des Agenten
response = agent.run("Darf ich fragen, wer du bist?")
print(response)

Beispielcode zur Verwendung von Werkzeugen

from LightAgent import LightAgent


# Definieren des Werkzeugs
def get_weather(city_name: str) -> str:
    """
    Holen Sie sich das aktuelle Wetter für `city_name`
    """
    return f"Suchergebnis: {city_name} Wetter ist klar"
# Definieren Sie die Werkzeuginformationen innerhalb der Funktion
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Holen Sie sich die aktuellen Wetterinformationen für die angegebene Stadt",
    "tool_params": [
        {"name": "city_name", "description": "Der Name der Stadt, die abgefragt werden soll", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Initialisieren des Agenten
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# Ausführen des Agenten
response = agent.run("Bitte helfen Sie mir, das Wetter in Shanghai zu überprüfen")
print(response)

Unterstützt die benutzerdefinierte Erstellung einer unbegrenzten Anzahl von Werkzeugen.

Beispiele für mehrere Werkzeuge: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


Funktionale Details

README enthält das zentrale Nutzungsmodell; längere Beispiele, Adapter-Setup und Produktionspraxis stehen in den Spezialdokumenten.

1. Abnehmbares Speichermodul (mem0)

LightAgent akzeptiert jedes Speicher-Backend mit store(data, user_id) und retrieve(query, user_id). Verwenden Sie user_id zur Isolation und MemoryPolicy bei gemeinsamem Speicher.

2. Tool-Integration

Python-Funktionen mit tool_info stellen kontrollierte Fähigkeiten bereit. Für ToolRegistry, ToolLoader, AsyncToolDispatcher und MCP siehe Tools Guide.

3. Tool-Generator

agent.create_tool() erzeugt Tool-Code aus API-Dokumentation oder natürlicher Sprache. Prüfen und testen Sie generierte Tools vor Produktion.

4. Denkbaum (ToT)

Aktivieren Sie tree_of_thought=True für Aufgaben mit expliziter Planung, Reflexion und Tool-Auswahl.

5. Multi-Agenten-Kooperation

LightSwarm delegiert Arbeit zwischen spezialisierten Agenten. Rollen sollten eng und Speicherzugriffe kontrolliert sein.

6. Streaming-API

agent.run(query, stream=True) gibt OpenAI-kompatible Chunks für Chat-UIs und lange Antworten zurück.

7. Selbstlernen des Agenten

Selbstlernen sollte mit MemoryPolicy kombiniert werden, um private, abgelaufene oder irrelevante Inhalte zu vermeiden.

8. Trace und Langfuse

LightAgent macht Ausführung über integrierte Traces oder Langfuse sichtbar.

9. Agentenbewertung

Agentenbewertung wird Verhalten anhand von Geschäftsszenarien messen.

10. LightFlow-Workflows

LightFlow ist die deterministische Workflow-Schicht für bekannte Ausführungsschritte.

  • Schrittzustände: pending, running, success, failed, skipped, waiting_approval.
  • DAG-Validierung: flow.validate(strict=True).
  • Schrittsteuerung: timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • Persistenz und Wiederaufnahme: JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

Siehe LightFlow.

11. Guardrails

Guardrails sind leichte Hooks um Eingabe, Werkzeugaufrufe und Ausgabe.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Siehe Guardrails.

12. SharedMemoryPool

SharedMemoryPool ist ein In-Memory-Prototyp für gemeinsamen Multi-Agent-Speicher und sollte mit MemoryPolicy genutzt werden.

Unterstützung für gängige Agentenmodelle

LightAgent arbeitet mit OpenAI-kompatiblen Chat-Completion-Endpunkten: OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama und eigene Gateways.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

Anwendungsszenarien

  • Intelligenter Kundenservice: Bereitstellung effizienter Kundenunterstützung durch mehrstufige Dialoge und Werkzeugintegration.
  • Datenanalyse: Verarbeitung komplexer Datenanalyseaufgaben mithilfe von Denkbaum und Multi-Agenten-Kooperation.
  • Automatisierte Werkzeuge: Schnelles Erstellen maßgeschneiderter Werkzeuge durch automatisierte Werkzeuggenerierung.
  • Bildungsunterstützung: Bereitstellung personalisierter Lernerfahrungen durch Gedächtnismodule und Stream-APIs.

🛠️ Beitragshinweise

Wir begrüßen alle Arten von Beiträgen! Egal ob Code, Dokumentation, Tests oder Feedback, alles ist eine große Hilfe für das Projekt. Wenn Sie gute Ideen haben oder einen Fehler finden, reichen Sie bitte ein Issue oder einen Pull Request ein. Hier sind die Schritte zur Mitwirkung:

  1. Forken Sie dieses Projekt: Klicken Sie auf die Schaltfläche Fork in der oberen rechten Ecke, um das Projekt in Ihr GitHub-Repository zu kopieren.
  2. Erstellen Sie einen Branch: Erstellen Sie lokal Ihren Entwicklungsbranch:
    git checkout -b feature/YourFeature
    
  3. Änderungen einreichen: Nach Abschluss der Entwicklung Ihre Änderungen einreichen:
    git commit -m 'Fügen Sie eine Funktion hinzu'
    
  4. Branch pushen: Pushen Sie den Branch in Ihr Remote-Repository:
    git push origin feature/YourFeature
    
  5. Pull Request einreichen: Reichen Sie einen Pull Request auf GitHub ein und beschreiben Sie Ihre Änderungen.

Wir werden Ihren Beitrag so schnell wie möglich überprüfen. Vielen Dank für Ihre Unterstützung!❤️


🙏 Danksagung

Die Entwicklung und Implementierung von LightAgent wäre ohne die Inspiration und Unterstützung folgender Open-Source-Projekte nicht möglich gewesen. Ein besonderer Dank geht an diese hervorragenden Projekte und Teams:

  • mem0: Vielen Dank an mem0 für das bereitgestellte Gedächtnismodul, das LightAgent eine starke Unterstützung für das Kontextmanagement bietet.
  • Swarm: Vielen Dank an Swarm für die Designideen zur Multi-Agenten-Kooperation, die die Grundlage für die Multi-Agenten-Funktionalität von LightAgent bilden.
  • ChatGLM3: Vielen Dank an ChatGLM3 für die Unterstützung leistungsstarker chinesischer großer Modelle und die Designinspiration.
  • Qwen: Vielen Dank an Qwen für die Unterstützung leistungsstarker chinesischer großer Modelle.
  • DeepSeek-V3: Vielen Dank an DeepSeek-V3 für die Unterstützung leistungsstarker chinesischer großer Modelle.
  • StepFun: Vielen Dank an step für die Unterstützung leistungsstarker chinesischer großer Modelle.

📄 Lizenz

LightAgent verwendet die Apache 2.0 Lizenz. Sie können dieses Projekt frei verwenden, ändern und verteilen, müssen jedoch die Lizenzbedingungen einhalten.


📬 Kontaktieren Sie uns

Bei Fragen oder Anregungen können Sie uns jederzeit kontaktieren:

Wir freuen uns auf Ihr Feedback, um LightAgent noch leistungsfähiger zu machen!🚀

  • Weitere Werkzeuge 🛠️: Kontinuierliche Integration weiterer nützlicher Werkzeuge zur Erfüllung zusätzlicher Anwendungsanforderungen.
  • Weitere Modellunterstützung 🔄: Kontinuierliche Erweiterung der Unterstützung für weitere große Modelle zur Erfüllung zusätzlicher Anwendungsszenarien.
  • Weitere Funktionen 🎯: Weitere nützliche Funktionen, kontinuierliche Updates, bleiben Sie dran!
  • Weitere Dokumentation 📚: Ausführliche Dokumentation, reichhaltige Beispiele, schnelle Einarbeitung, einfache Integration in Ihr Projekt.
  • Weitere Gemeinschaftsunterstützung 👥: Aktive Entwicklergemeinschaft, die Ihnen jederzeit Hilfe und Antworten bietet.
  • Weitere Leistungsoptimierung ⚡: Kontinuierliche Optimierung der Leistung zur Erfüllung der Anforderungen an hochgradige Parallelität.
  • Weitere Open-Source-Beiträge 🌟: Beiträge zum Code sind willkommen, um LightAgent gemeinsam zu verbessern!

LightAgent - Machen Sie Intelligenz leichter, machen Sie die Zukunft einfacher. 🌈

LightAgent —— Ein leichtgewichtiges, flexibles und leistungsstarkes aktives Agent-Framework, das Ihnen hilft, intelligente Anwendungen schnell zu erstellen!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀(次世代エージェンティックAIフレームワーク)

LightAgent は、記憶(mem0)、ツール(Tools)、思考ツリー(ToT)を備えた非常に軽量な能動的エージェントフレームワークであり、完全にオープンソースです。これは、OpenAI Swarm よりも簡単なマルチエージェント協調をサポートし、自己学習能力を持つエージェントを簡単に構築でき、stdio および sse 方式で MCP プロトコルに接続できます。基盤モデルは、OpenAI、智谱 ChatGLM、DeepSeek、階跃星辰、Qwen通义千问大モデルなどをサポートしています。同時に、LightAgent は OpenAI ストリーム形式 API サービス出力をサポートし、主要なチャットフレームワークにシームレスに接続できます。🌟


ニュース

  • new[2026-06-24] LightAgent v0.9.0:永続化 LightFlow checkpoint、resume/rerun、承認ノード、明確なステップ状態、trace メタデータ、Guardrails テンプレート、MemoryPolicy 制御、SharedMemoryPool プロトタイプを追加。
  • [2026-06-14] LightAgent v0.8.1:MemoryScope 規約と MemoryPolicy の出所・範囲・信頼度フィルタを追加。
  • [2026-06-02] LightAgent v0.8.0:決定的な複数ステップ workflow のための LightFlow を導入。

過去のリリースノートは GitHub Releases を参照してください。


✨ 特徴

  • 軽量で効率的 🚀:極限のシンプル設計で迅速なデプロイが可能、あらゆるスケールのアプリケーションシーンに適しています。(No LangChain, No LlamaIndex)100% Pythonで実装され、追加の依存関係は不要、コアコードはわずか1000行、完全にオープンソースです。
  • メモリサポート 🧠:各ユーザーのためにカスタマイズ可能な長期メモリをサポートし、対話の過程でユーザーの個性に応じたメモリを自動管理することにより、エージェントをより賢くします。
  • 自主学習 📚️:各エージェントは自ら学ぶ能力を持ち、アクセス権を持つ管理者はそれぞれのエージェントを管理できます。
  • ツール統合 🛠️:カスタマイズ可能なツール(Tools)をサポートし、自動ツール生成が可能で、多様なニーズに応えます。
  • 複雑な目標 🌳:反省を伴う思考ツリーモジュール(ToT)を内蔵しており、複雑なタスクの分解と多段階推論をサポートし、タスク処理能力を向上させます。
  • マルチエージェント協調 🤖:Swarmよりも簡単に実現できるマルチエージェント協調作業をサポートし、内蔵のLightSwarmが意図の判断とタスクの移転機能を実装し、より賢くユーザー入力を処理できます。
  • 独立した実行 🤖:人的介入なしに自律的にタスクツールを呼び出して完了します。
  • 多モデルサポート 🔄:OpenAI、智谱ChatGLM、百川大モデル、StepFun、DeepSeek、Qwenシリーズの大モデルと互換性があります。
  • ストリームAPI 🌊:OpenAIストリーム形式のAPIサービス出力をサポートしており、主流のチャットフレームワークとのシームレスな統合により、ユーザー体験を向上させます。
  • Toolsツールジェネレーター 🚀:APIドキュメントを[Toolsツールジェネレーター]に渡すだけで、数百のカスタマイズツールを短時間で自動生成し、効率を向上させ、創造的な可能性を解放します。
  • エージェントの自己学習 🧠️:各エージェントは自身のシーンメモリ機能を持ち、ユーザーの対話から自己学習する能力を備えています。
  • 適応型ツールメカニズム 🛠️:無限のツールを追加可能、大量のツールの中から大モデルが候補ツールの集合を選び、無関係なツールをフィルタリングした後、文脈を再び大モデルに提出することによって、トークン消費を大幅に削減できます。
  • ワークフロー編成 🔁:LightFlow は明示的な依存関係、出力受け渡し、リトライ、checkpoint、resume/rerun、承認ノード、fallback agent、追跡可能な実行を備えた決定的 workflow を構成します。
  • 共有メモリプロトタイプ 🧠:SharedMemoryPool は出所メタデータ、スコープ付き検索、MemoryPolicy 互換結果を備えたインメモリ共有メモリを提供します。
  • Guardrails テンプレート 🛡️:入力、ツール、出力の再利用可能な安全ポリシーにより、個人情報の遮断、機密ツールの確認、高リスク引数の検証、出力のマスキングを行えます。
  • Runtime Hooks 🧩:順序付き hooks=[...] ミドルウェアで、run、モデル、ツール、メモリ、LightFlow ステップの各フェーズを監視、置換、ブロックできます。

🧭 アーキテクチャ概要

レイヤー 主な API 用途
単一 Agent 実行 LightAgent モデル呼び出し、ツール、メモリ、ストリーミング、trace、guardrails。
マルチ Agent ルーティング LightSwarm 専門 Agent 間の役割ベース委譲。
決定的 workflow LightFlow DAG、リトライ、checkpoint、承認、resume、rerun。
ツールと統合 toolsToolRegistry、MCP Python ツール、生成ツール、実行時ロード、MCP サーバー。
メモリ境界 MemoryPolicyMemoryScope テナント分離、出所、信頼、期限、書き込み許可。
共有メモリ SharedMemoryPool Agent 間の共有メモリ実験。
安全制御 input_guardrailstool_guardrailsoutput_guardrails プライバシー、ツール確認、リスク引数、出力マスキング。
Runtime hooks hooksHookContextHookDecision ライフサイクル境界でのポリシー、監査、マスキング、ルーティング、payload 変更。
可観測性 trace=Trueagent.export_trace() 実行、モデル、ツール、エラー、workflow の構造化イベント。

主要な利用パターン

LightAgent はデフォルトの呼び出しを簡単に保ちつつ、本番向け制御を段階的に追加できます。

パターン 最小呼び出し 説明
基本応答 agent.run(query) デフォルトで文字列を返します。
ストリーミング agent.run(query, stream=True) OpenAI 互換 chunk を返します。
構造化結果 agent.run(query, result_format="object") 内容とメタデータを返します。
Trace agent.run(query, trace=True) デフォルトの文字列返却を変えずにイベントを記録します。
ユーザーメモリ agent.run(query, user_id="alice") 設定済みメモリ backend と MemoryPolicy を使います。
ツール LightAgent(..., tools=[fn]) 関数は tool_info を持つべきです。
Guardrails LightAgent(..., input_guardrails=[...]) 入力、ツール、出力ポリシーを追加します。
Runtime hooks LightAgent(..., hooks=[fn]) ライフサイクル payload を監視、置換、ブロックします。
Workflow LightFlow().step(...).run(query) 決定的な多段階実行に使います。

📋 ドキュメント

  • インストール、モデル、ツール、メモリ、MCP、Skills、ストリーミング、LightSwarm については FAQ を参照してください。
  • 決定的 workflow、checkpoint、resume/rerun、承認、fallback agent、ステップ状態については LightFlow を参照してください。
  • カスタムツール、ToolRegistry、ToolLoader、AsyncToolDispatcher、MCP については Tools Guide を参照してください。
  • 共有長期メモリまたはグラフメモリについては Memory Security Guidance を参照してください。
  • SharedMemoryPool については SharedMemoryPool を参照してください。
  • メモリ書き込みの受け入れ制御と期限については Memory Admission And Mutation Controls を参照してください。
  • 入力、ツール、出力の安全ポリシーについては Guardrails を参照してください。
  • payload を監視、置換、ブロックする runtime middleware については Runtime Hooks を参照してください。
  • OpenRouter、ローカルモデル、OpenAI 互換プロバイダーについては Model Provider Configuration を参照してください。
  • 構造化 trace については Trace Observability を参照してください。

🚧 近日公開

  • エージェント協調通信 🛠️:エージェント間で情報を共有し、メッセージを伝達することができ、複雑な情報通信とタスク協調を実現します。
  • エージェント評価 📊:エージェントの評価ツールを内蔵しており、構築したエージェントを評価および最適化し、ビジネスシーンに直結し、知能レベルを継続的に向上させます。

🌟 なぜLightAgentを選ぶのか?

  • オープンソースで無料 💖:完全にオープンソース、コミュニティ主導で継続的に更新されています。貢献を歓迎します!
  • 簡単に始められる 🎯:文書が詳細で、サンプルが豊富で、迅速に始められ、プロジェクトに簡単に組み込むことが可能です。
  • コミュニティサポート 👥:活発な開発者コミュニティがあり、いつでも支援と解答を提供します。
  • 高性能 ⚡:最適化された設計で高効率に実行され、高い同時実行性のシーンのニーズに応えます。

🛠️ クイックスタート

LightAgent最新バージョンのインストール

pip install lightagent

(オプションでMem0パッケージをインストール):

pip install mem0ai

または、ホスティングプラットフォーム上でMem0をワンボタンで使用できます。こちらをクリック

Hello worldのサンプルコード

from LightAgent import LightAgent

# エージェントの初期化
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url="your_base_url")

# エージェントを実行
response = agent.run("こんにちは、あなたは誰ですか?")
print(response)

実行 Trace を確認する(v0.7.0)

Trace は opt-in で、agent.run() のデフォルト動作との互換性を保ちます。

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

LightFlow 実行を checkpoint する(v0.9.0)

LightFlow は workflow checkpoint を永続化し、失敗した実行を最初からではなく途中から再開できます。

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

SharedMemoryPool を使う(v0.9.0)

SharedMemoryPool はマルチ Agent 共有メモリ実験向けの軽量インメモリプロトタイプです。

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

systemプロンプトを使ってモデルの自己認識を設定する

from LightAgent import LightAgent

# エージェントの初期化
agent = LightAgent(
     role="あなたはLightAgentです、ユーザーが多くのツールを使用するのを助ける役立つアシスタントです。",  # systemロールの説明
     model="deepseek-chat",  # 対応モデル:openai、chatglm、deepseek、qwenなど
     api_key="your_api_key",  # あなたの大モデルサービスプロバイダAPIキーに置き換えます
     base_url="your_base_url",  # あなたの大モデルサービスプロバイダapi urlに置き換えます
 )
# エージェントを実行
response = agent.run("あなたは誰ですか?")
print(response)

ツール使用のサンプルコード

from LightAgent import LightAgent

# ツールを定義
def get_weather(city_name: str) -> str:
    """
    `city_name`の現在の天気を取得
    """
    return f"問い合わせ結果: {city_name} は晴れです"
# 関数内部でツール情報を定義
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "指定された都市の現在の天気情報を取得",
    "tool_params": [
        {"name": "city_name", "description": "問い合わせる都市名", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# エージェントの初期化
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url="your_base_url", tools=tools)

# エージェントを実行
response = agent.run("上海の天気を教えてください")
print(response)

無限のカスタマイズ可能なツールのサポート。

複数のツールの例: tools = ["search_news", "get_weather", "get_stock_realtime_data", "get_stock_kline_data"]


機能詳細

README には中核的な利用モデルを残し、長い例、アダプタ設定、本番運用の詳細は専用ドキュメントに置いています。

1. 分離可能なメモリモジュール(mem0

LightAgent は store(data, user_id)retrieve(query, user_id) を持つ任意のメモリ backend を受け付けます。会話分離には user_id、共有メモリには MemoryPolicy を使います。

2. ツール統合

tool_info メタデータを持つ Python 関数で Agent に制御された能力を公開します。ToolRegistry、ToolLoader、AsyncToolDispatcher、MCP は Tools Guide を参照してください。

3. ツール生成器

agent.create_tool() は API 文書や自然言語説明からツールコードを生成できます。本番前にレビューとテストを行ってください。

4. 思考ツリー(ToT)

明示的な計画、反省、ツール選択が必要な場合は tree_of_thought=True を有効にします。

5. マルチ Agent 協調

LightSwarm は専門 Agent 間で作業を委譲します。役割を狭く保ち、メモリ書き込みをポリシーで制御してください。

6. ストリーミング API

agent.run(query, stream=True) はチャット UI や長文出力向けに OpenAI 互換 chunk を返します。

7. Agent 自己学習

自己学習は MemoryPolicy と組み合わせ、個人情報、期限切れ、無関係な内容を避けるべきです。

8. Trace と Langfuse

LightAgent は組み込み trace または Langfuse で実行を観測できます。

9. Agent 評価

Agent 評価は業務シナリオに対する振る舞いを測定する予定です。

10. LightFlow Workflow

LightFlow は既知の手順で実行するための決定的 workflow 層です。

  • ステップ状態:pendingrunningsuccessfailedskippedwaiting_approval
  • DAG 検証:flow.validate(strict=True)
  • ステップ制御:timeoutmax_retrycancel_iffallback_agentrequires_approvalapproval_handler
  • 永続化と復旧:JsonLightFlowStoreflow.resume(run_id)flow.rerun_step(run_id, step_name)flow.get_run(run_id)flow.list_runs()

LightFlow を参照してください。

11. Guardrails

Guardrails は入力、ツール呼び出し、出力を検査する軽量 hook です。

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Guardrails を参照してください。

12. SharedMemoryPool

SharedMemoryPool はマルチ Agent 共有メモリ実験用のインメモリプロトタイプで、MemoryPolicy と併用します。

主流エージェントモデルサポート

LightAgent は OpenAI 互換 chat completion endpoint に対応します:OpenAI、OpenRouter、Zhipu ChatGLM、DeepSeek、Qwen、StepFun、Moonshot/Kimi、MiniMax、vLLM、llama.cpp、Ollama、自ホスト gateway。

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

使用シーン

  • スマートカスタマーサービス:多段階の対話とツール統合により、高効率な顧客サポートを提供します。
  • データ分析:思考ツリーとマルチエージェント協調を利用して、複雑なデータ分析タスクを処理します。
  • 自動化ツール:自動ツール生成により、カスタマイズツールを迅速に構築します。
  • 教育支援:メモリモジュールとストリームAPIを用いて、個別的な学習体験を提供します。

🛠️ 貢献ガイドライン

私たちは、あらゆる形態の貢献を歓迎します!コード、ドキュメント、テスト、フィードバックいずれも、プロジェクトに対する大きな助けとなります。良いアイデアやバグを発見した場合は、IssueまたはPull Requestを提出してください。以下は貢献のステップです:

  1. このプロジェクトをフォーク:右上のForkボタンをクリックして、プロジェクトをGitHubリポジトリにコピーします。
  2. ブランチを作成:ローカルに開発ブランチを作成します:
    git checkout -b feature/YourFeature
    
  3. 変更をコミット:開発を完了したら、変更をコミットします:
    git commit -m 'Add some feature'
    
  4. ブランチをプッシュ:ブランチをリモートリポジトリにプッシュします:
    git push origin feature/YourFeature
    
  5. プルリクエストを提出:GitHub上でプルリクエストを提出し、変更内容を説明します。

私たちは迅速にあなたの貢献をレビューします!ご支援ありがとうございます!❤️


🙏 謝辞

LightAgentの開発と実現は、以下のオープンソースプロジェクトのインスピレーションとサポートに寄っています。特に以下の優れたプロジェクトとチームに感謝します:

  • mem0:メモリモジュールを提供してくれたmem0に感謝します。
  • Swarm:マルチエージェント協調設計のアイデアを提供してくれたSwarmに感謝します。
  • ChatGLM3:高性能な中国語大モデルのサポートとデザインのインスピレーションを提供してくれたChatGLM3に感謝します。
  • Qwen:高性能な中国語大モデルのサポートを提供してくれたQwenに感謝します。
  • DeepSeek-V3:高性能な中国語大モデルのサポートを提供してくれたDeepSeek-V3に感謝します。
  • StepFun:高性能な中国語大モデルのサポートを提供してくれたstepに感謝します。

📄 ライセンス

LightAgentはApache 2.0ライセンスの下で使用されます。本プロジェクトは自由に使用、変更、配布できますが、ライセンスの条項を遵守してください。


📬 お問い合わせ

何か問題や提案がある場合は、いつでもお問い合わせください:

あなたのフィードバックをお待ちしております。一緒にLightAgentを強化しましょう!🚀

  • さらに多くのツール 🛠️:実用的なツールを継続的に統合し、多くのシーンのニーズに応えます。
  • モデルサポートの拡張 🔄:さらに多くの大モデルをサポートするように継続的に拡張します。
  • 機能の追加 🎯:実用的な機能をさらに追加し、続々と更新を予定していますのでご期待ください!
  • さらなるドキュメント 📚:詳細なドキュメントがあり、豊富なサンプルで迅速に始められ、プロジェクトに簡単に統合できます。
  • さらなるコミュニティサポート 👥:活発な開発者コミュニティがあり、いつでも支援を提供します。
  • さらなるパフォーマンス最適化 ⚡:継続的にパフォーマンスを最適化し、同時運用のシーンのニーズに応えます。
  • さらなるオープンソース貢献 🌟:コードの貢献を歓迎し、より優れたLightAgentの構築に取り組みましょう!

LightAgent - インテリジェンスを軽量化し、未来をシンプルに。 🌈

LightAgent —— 軽量で柔軟、強力な能動的エージェントフレームワークで、迅速にインテリジェントなアプリケーションを構築します!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀(차세대 Agentic AI 프레임워크)

LightAgent는 기억(mem0), 도구(Tools), 사고 트리(ToT)를 갖춘 극히 경량의 능동형 에이전틱 프레임워크로, 완전 오픈 소스입니다. 이는 OpenAI Swarm보다 더 간단한 다중 에이전트 협업을 지원하며, 단 한 단계로 자기 학습 능력을 갖춘 에이전트를 구축할 수 있고, stdio 및 sse 방식으로 MCP 프로토콜에 접속할 수 있습니다. 기본 모델은 OpenAI, 지프 ChatGLM, DeepSeek, 계단별 별, Qwen 통의 천문 대모델 등을 지원합니다. 또한, LightAgent는 OpenAI 스트림 형식 API 서비스 출력을 지원하여 주요 Chat 프레임워크에 원활하게 접속할 수 있습니다.🌟


뉴스

  • new[2026-06-24] LightAgent v0.9.0: 영속 LightFlow checkpoint, resume/rerun, 승인 노드, 명확한 단계 상태, trace 메타데이터, Guardrails 템플릿, MemoryPolicy 제어, SharedMemoryPool 프로토타입을 추가했습니다.
  • [2026-06-14] LightAgent v0.8.1: MemoryScope 규약과 MemoryPolicy 출처/범위/신뢰도 필터를 추가했습니다.
  • [2026-06-02] LightAgent v0.8.0: 결정적 다단계 workflow를 위한 LightFlow를 도입했습니다.

이전 릴리스 노트는 GitHub Releases를 참고하세요.


✨ 특징

  • 경량 및 효율성 🚀: 극단적으로 간단한 디자인, 빠른 배포, 다양한 규모의 애플리케이션에 적합합니다. (No LangChain, No LlamaIndex) 100% 파이썬으로 구현되어 추가 의존성이 필요 없으며, 핵심 코드는 단 1000줄이며 완전히 오픈 소스입니다.
  • 기억 지원 🧠: 각 사용자에 대한 맞춤형 장기 기억을 지원하며, 기본적으로 mem0 기억 모듈을 지원하여 대화 과정에서 사용자 맞춤 기억을 자동으로 관리하여 에이전트를 더욱 스마트하게 만듭니다.
  • 자율 학습 📚️: 각 에이전트는 자율 학습 능력을 가지며 권한이 있는 관리자는 각 에이전트를 관리할 수 있습니다.
  • 도구 통합 🛠️: 사용자 정의 도구(Tools)를 지원하며, 자동화 도구 생성을 통해 유연하게 확장 가능하며 다양한 요구를 충족합니다.
  • 복잡한 목표 🌳: 반성적 사고가 가능한 사고 트리(ToT) 모듈이 내장되어 복잡한 작업 분해 및 다단계 추론을 지원하여 작업 처리 능력을 향상시킵니다.
  • 다중 에이전트 협업 🤖: 스웜보다 더 간단하게 구현할 수 있는 다중 에이전트 협업 시스템으로, 내장된 LightSwarm을 통해 의도 판단 및 작업 전송 기능을 제공하여 사용자 입력을 보다 스마트하게 처리하고 필요에 따라 작업을 다른 에이전트에게 전송할 수 있습니다.
  • 독립 실행 🤖: 인위적 개입 없이 자율적으로 작업 도구 호출을 완료합니다.
  • 다양한 모델 지원 🔄: OpenAI, Zhiyun ChatGLM, Baichuan 대모델, StepFun, DeepSeek, Qwen 시리즈 대모델을 호환합니다.
  • 스트리밍 API 🌊: OpenAI 스트리밍 형식 API 서비스 출력을 지원하여 주요 채팅 프레임워크와 원활하게 통합되어 사용자 경험을 향상시킵니다.
  • Tools 도구 생성기 🚀: API 문서만 제공하면 [Tools 도구 생성기]가 자동으로 귀하만의 도구를 만들고, 단 1시간 내에 수백 개의 맞춤형 도구를 신속하게 구축하여 효율성을 높이고 혁신 잠재력을 발휘할 수 있습니다.
  • 에이전트 자기 학습 🧠️: 각 에이전트는 사용자 대화에서 자기 학습 능력을 가진 장면 기억 능력을 가지고 있습니다.
  • 적응형 도구 메커니즘 🛠️: 무제한 도구 추가를 지원하며, 수천 개의 도구 중에서 대모델이 후보 도구 집합을 선택한 후 관련 없는 도구를 필터링하여 대모델에 문맥을 제출하여 Token 소비를 대폭 줄일 수 있습니다.
  • 워크플로 오케스트레이션 🔁: LightFlow는 명시적 의존성, 출력 전달, 재시도, checkpoint, resume/rerun, 승인 노드, fallback agent, 추적 가능한 실행을 갖춘 결정적 workflow를 구성합니다.
  • 공유 메모리 프로토타입 🧠: SharedMemoryPool은 출처 메타데이터, 범위 기반 검색, MemoryPolicy 호환 결과를 제공하는 인메모리 공유 기억입니다.
  • Guardrails 템플릿 🛡️: 입력, 도구, 출력에 대한 재사용 가능한 안전 정책으로 개인정보 차단, 민감 도구 확인, 고위험 인자 검증, 출력 마스킹을 수행합니다.
  • Runtime Hooks 🧩: 정렬된 hooks=[...] 미들웨어로 run, 모델, 도구, 메모리, LightFlow 단계 payload를 관찰, 교체, 차단할 수 있습니다.

🧭 아키텍처 한눈에 보기

계층 주요 API 사용 시점
단일 Agent 런타임 LightAgent 모델 호출, 도구, 메모리, 스트리밍, trace, guardrails가 필요한 경우.
다중 Agent 라우팅 LightSwarm 전문 Agent 간 역할 기반 위임.
결정적 workflow LightFlow DAG, 재시도, checkpoint, 승인, resume, rerun.
도구와 통합 tools, ToolRegistry, MCP Python 도구, 생성 도구, 런타임 로딩, MCP 서버.
메모리 경계 MemoryPolicy, MemoryScope 테넌트 격리, 출처, 신뢰, 만료, 쓰기 승인.
공유 메모리 SharedMemoryPool Agent 간 공유 기억 실험.
안전 제어 input_guardrails, tool_guardrails, output_guardrails 개인정보, 도구 확인, 위험 인자, 출력 마스킹.
Runtime hooks hooks, HookContext, HookDecision 생명주기 경계의 정책, 감사, 마스킹, 라우팅, payload 변경.
관측성 trace=True, agent.export_trace() 실행, 모델, 도구, 오류, workflow 구조화 이벤트.

핵심 사용 패턴

LightAgent는 기본 호출 경로를 단순하게 유지하면서 운영 제어를 단계적으로 추가할 수 있습니다.

패턴 최소 호출 설명
기본 응답 agent.run(query) 기본적으로 문자열을 반환합니다.
스트리밍 agent.run(query, stream=True) OpenAI 호환 chunk를 반환합니다.
구조화 결과 agent.run(query, result_format="object") 내용과 메타데이터를 반환합니다.
Trace agent.run(query, trace=True) 기본 문자열 반환을 바꾸지 않고 이벤트를 기록합니다.
사용자 메모리 agent.run(query, user_id="alice") 설정된 메모리 backend와 MemoryPolicy를 사용합니다.
도구 LightAgent(..., tools=[fn]) 함수는 tool_info를 제공해야 합니다.
Guardrails LightAgent(..., input_guardrails=[...]) 입력, 도구, 출력 정책을 추가합니다.
Runtime hooks LightAgent(..., hooks=[fn]) 생명주기 payload를 관찰, 교체, 차단합니다.
Workflow LightFlow().step(...).run(query) 결정적 다단계 실행에 사용합니다.

📋 문서

  • 설치, 모델, 도구, 메모리, MCP, Skills, 스트리밍, LightSwarm은 FAQ를 참고하세요.
  • 결정적 workflow, checkpoint, resume/rerun, 승인, fallback agent, 단계 상태는 LightFlow를 참고하세요.
  • 사용자 정의 도구, ToolRegistry, ToolLoader, AsyncToolDispatcher, MCP는 Tools Guide를 참고하세요.
  • 공유 장기 기억 또는 그래프 기억은 Memory Security Guidance를 참고하세요.
  • SharedMemoryPool은 SharedMemoryPool를 참고하세요.
  • 메모리 쓰기 승인과 만료 제어는 Memory Admission And Mutation Controls를 참고하세요.
  • 입력, 도구, 출력 안전 정책은 Guardrails를 참고하세요.
  • payload를 관찰, 교체, 차단하는 runtime middleware는 Runtime Hooks를 참고하세요.
  • OpenRouter, 로컬 모델, OpenAI 호환 공급자는 Model Provider Configuration를 참고하세요.
  • 구조화 trace는 Trace Observability를 참고하세요.

🚧 곧 출시 예정

  • 지능형 에이전트 협동 통신 🛠️: 지능형 에이전트 간에 정보를 공유하고 메시지를 전달하여 복잡한 정보 통신 및 작업 협동을 실현할 수 있습니다.
  • 에이전트 평가 📊: 내장된 에이전트 평가 도구로 귀하가 구축한 에이전트를 평가하고 최적화하여 비즈니스 장면에 맞춰 지속적으로 스마트 수준을 향상시킬 수 있습니다.

🌟 왜 LightAgent를 선택해야 하나요?

  • 오픈 소스 무료 💖: 완전 오픈 소스이며, 커뮤니티 주도로 지속적으로 업데이트되며 기여를 환영합니다!
  • 손쉬운 사용 🎯: 문서가 자세하고 예시가 풍부하여 빠르게 배우고 쉽게 프로젝트에 통합할 수 있습니다.
  • 커뮤니티 지원 👥: 활발한 개발자 커뮤니티가 언제든지 도움과 답변을 제공합니다.
  • 고성능 ⚡: 최적화된 설계로 고효율로 실행되며 고병렬 요구를 충족합니다.

🛠️ 빠른 시작

LightAgent 최신 버전 설치

pip install lightagent

(선택 설치) pip를 통해 Mem0 패키지 설치:

pip install mem0ai

또는 호스팅 플랫폼에서 Mem0을 한 번 클릭하여 사용할 수 있습니다. 여기 클릭.

Hello world 예제 코드

from LightAgent import LightAgent

# 에이전트 초기화
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url= "your_base_url")

# 에이전트 실행
response = agent.run("안녕하세요, 당신은 누구인가요?")
print(response)

실행 Trace 확인 (v0.7.0)

Trace는 선택 기능이며 기본 agent.run() 동작과 호환됩니다.

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

LightFlow 실행 checkpoint 저장 (v0.9.0)

LightFlow는 workflow checkpoint를 저장하고 실패한 실행을 첫 단계부터 다시 시작하지 않고 재개할 수 있습니다.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

SharedMemoryPool 사용 (v0.9.0)

SharedMemoryPool은 다중 Agent 공유 기억 실험을 위한 가벼운 인메모리 프로토타입입니다.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

시스템 프롬프트로 모델 자기 인식 설정

from LightAgent import LightAgent

# 에이전트 초기화
agent = LightAgent(
     role="당신은 LightAgent로, 사용자에게 여러 도구 사용을 돕는 유용한 도우미임을 기억하세요.",  # 시스템 역할 설명
     model="deepseek-chat",  # 지원 모델: openai, chatglm, deepseek, qwen 등
     api_key="your_api_key",  # 당신의 대형 모델 서비스 제공자가 사용하는 API Key로 교체
     base_url="your_base_url",  # 당신의 대형 모델 서비스 제공자의 api url로 교체
 )
# 에이전트 실행
response = agent.run("당신은 누구인가요?")
print(response)

도구 사용 예제 코드

from LightAgent import LightAgent


# 도구 정의
def get_weather(city_name: str) -> str:
    """
    `city_name`의 현재 날씨를 가져옵니다.
    """
    return f"조회 결과: {city_name} 날씨 맑음"
# 함수 내부에서 도구 정보를 정의
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "지정된 도시의 현재 날씨 정보를 가져옵니다.",
    "tool_params": [
        {"name": "city_name", "description": "조회할 도시 이름", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# 에이전트 초기화
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# 에이전트 실행
response = agent.run("상하이의 날씨를 확인해 주세요")
print(response)

무제한 수의 사용자 정의 도구를 지원합니다.

여러 도구 예제: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


기능 상세 설명

README는 핵심 사용 모델을 유지하고, 긴 예제와 어댑터 설정, 운영 지침은 전용 문서에 둡니다.

1. 분리 가능한 메모리 모듈(mem0)

LightAgent는 store(data, user_id)retrieve(query, user_id)를 제공하는 모든 메모리 backend를 받을 수 있습니다. 대화 격리는 user_id, 공유 메모리는 MemoryPolicy를 사용합니다.

2. 도구 통합

tool_info 메타데이터가 있는 Python 함수로 Agent에 제어된 기능을 제공합니다. ToolRegistry, ToolLoader, AsyncToolDispatcher, MCP는 Tools Guide를 참고하세요.

3. 도구 생성기

agent.create_tool()는 API 문서나 자연어 설명에서 도구 코드를 생성할 수 있습니다. 운영 전 리뷰와 테스트가 필요합니다.

4. 사고 트리(ToT)

명시적 계획, 성찰, 도구 선택이 필요한 작업에는 tree_of_thought=True를 사용합니다.

5. 다중 Agent 협업

LightSwarm은 전문 Agent 사이에 작업을 위임합니다. 역할은 좁게 유지하고 메모리 쓰기는 정책으로 제한하세요.

6. 스트리밍 API

agent.run(query, stream=True)는 채팅 UI와 긴 응답을 위해 OpenAI 호환 chunk를 반환합니다.

7. Agent 자기 학습

자기 학습은 MemoryPolicy와 함께 사용해 개인정보, 만료, 무관한 내용을 장기 기억에 넣지 않도록 해야 합니다.

8. Trace와 Langfuse

LightAgent는 내장 trace 또는 Langfuse로 실행을 관측할 수 있습니다.

9. Agent 평가

Agent 평가는 업무 시나리오에 대한 동작 측정을 목표로 합니다.

10. LightFlow Workflow

LightFlow는 알려진 단계대로 실행하기 위한 결정적 workflow 계층입니다.

  • 단계 상태: pending, running, success, failed, skipped, waiting_approval.
  • DAG 검증: flow.validate(strict=True).
  • 단계 제어: timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • 영속화와 복구: JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

LightFlow를 참고하세요.

11. Guardrails

Guardrails는 입력, 도구 호출, 출력을 검사하는 가벼운 hook입니다.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Guardrails를 참고하세요.

12. SharedMemoryPool

SharedMemoryPool은 다중 Agent 공유 기억 실험용 인메모리 프로토타입이며 MemoryPolicy와 함께 사용합니다.

주요 에이전트 모델 지원

LightAgent는 OpenAI 호환 chat completion endpoint와 동작합니다: OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama, 자체 gateway.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

사용 사례

  • 스마트 고객 서비스: 다중 회화 및 도구 통합을 통해 효과적인 고객 지원을 제공합니다.
  • 데이터 분석: 사고 트리 및 다중 에이전트 협업을 활용하여 복잡한 데이터 분석 작업을 처리합니다.
  • 자동화 도구: 자동화 도구 생성을 통해 맞춤형 도구를 신속하게 구축합니다.
  • 교육 지원: 기억 모듈 및 스트리밍 API를 통해 개인화된 학습 경험을 제공합니다.

🛠️ 기여 안내

우리는 어떤 형태의 기여든 환영합니다! 코드, 문서, 테스트 또는 피드백은 모두 프로젝트에 큰 도움이 됩니다. 좋은 아이디어가 있거나 버그를 발견한 경우, Issue 또는 Pull Request를 제출해 주십시오. 기여 방법은 다음과 같습니다:

  1. 이 프로젝트 포크하기: 오른쪽 상단의 Fork 버튼을 클릭하여 프로젝트를 귀하의 GitHub 리포지토리로 복사합니다.
  2. 브랜치 생성: 로컬에서 개발 브랜치를 생성합니다:
    git checkout -b feature/YourFeature
    
  3. 변경 내역 제출: 개발을 완료한 후 변경 사항을 제출합니다:
    git commit -m 'Add some feature'
    
  4. 브랜치 푸시: 브랜치를 귀하의 원격 리포지토리에 푸시합니다:
    git push origin feature/YourFeature
    
  5. Pull Request 제출: GitHub에서 Pull Request를 제출하고 변경 사항에 대해 설명합니다.

우리는 귀하의 기여를 즉시 검토할 것이며, 귀하의 지원에 감사드립니다!❤️


🙏 감사의 말씀

LightAgent의 개발 및 구현은 다음 오픈 소스 프로젝트의 영감과 지원에 힘입었습니다. 특히 이러한 뛰어난 프로젝트와 팀에 감사를 드립니다:

  • mem0: mem0에서 제공하는 기억 모듈에 감사드립니다. LightAgent의 문맥 관리에 강력한 지원을 제공했습니다.
  • Swarm: Swarm에서 제공한 다중 에이전트 협업 디자인 아이디어에 감사드립니다. LightAgent의 다중 에이전트 기능의 기본을 마련했습니다.
  • ChatGLM3: ChatGLM3에서 제공하는 고성능 중국어 대형 모델 지원과 디자인 영감에 감사드립니다.
  • Qwen: Qwen에서 제공하는 고성능 중국어 대형 모델 지원에 감사드립니다.
  • DeepSeek-V3: DeepSeek-V3에서 제공하는 고성능 중국어 대형 모델 지원에 감사드립니다.
  • 阶跃星辰: step에서 제공하는 고성능 중국어 대형 모델 지원에 감사드립니다.

📄 라이센스

LightAgent는 Apache 2.0 라이센스를 따릅니다. 본 프로젝트는 자유롭게 사용, 수정 및 배포할 수 있지만 라이센스 조건을 준수해야 합니다.


📬 문의하기

질문이나 제안이 있는 경우 언제든지 문의해 주십시오:

우리는 귀하의 피드백을 기대하며 함께 LightAgent를 더 강력하게 만들어 갑시다!🚀

  • 더 많은 도구 🛠️: 사용 사례 요구를 충족하기 위해 더 많은 유용한 도구를 지속적으로 통합합니다.
  • 더 많은 모델 지원 🔄: 더 많은 대형 모델을 지속적으로 지원하여 더 다양한 응용 사례를 충족합니다.
  • 더 많은 기능 🎯: 더 많은 유용한 기능이 지속적으로 업데이트됩니다. 기대해 주세요!
  • 더 많은 문서 📚: 자세한 문서와 풍부한 예시로 빠르게 배워 프로젝트에 쉽게 통합할 수 있습니다.
  • 더 많은 커뮤니티 지원 👥: 활발한 개발자 커뮤니티가 언제든지 도움과 해답을 제공합니다.
  • 더 많은 성능 최적화 ⚡: 고병렬 요구를 충족하기 위해 성능을 지속적으로 최적화합니다.
  • 더 많은 오픈 소스 기여 🌟: 기여 코드를 환영하며 함께 더 나은 LightAgent를 만들어 갑시다!

LightAgent - 스마트함을 더 가볍게, 미래를 더 단순하게 만듭니다. 🌈

LightAgent —— 경량화, 유연성, 강력한 능동적 에이전트 프레임워크로, 스마트 애플리케이션을 신속하게 구축합니다!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent🚀(Próxima geração de estrutura de IA Agentic)

LightAgent é uma estrutura ativa e autônoma extremamente leve com memória (mem0), ferramentas (Tools) e árvore de pensamento (ToT), e é totalmente de código aberto. Ele suporta uma colaboração multiagente mais simples do que o OpenAI Swarm, permitindo a construção de agentes com capacidade de autoaprendizado em um único passo, e suporta a conexão ao protocolo MCP via stdio e sse. O modelo subjacente suporta OpenAI, Zhiyu ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen e outros grandes modelos. Além disso, o LightAgent suporta a saída de serviços de API em formato de fluxo da OpenAI, integrando-se perfeitamente a várias estruturas de chat populares. 🌟


Notícias

  • new[2026-06-24] LightAgent v0.9.0: adiciona workflows LightFlow com checkpoints, resume/rerun, nós de aprovação, estados de etapa mais claros, metadados de trace, modelos Guardrails, controles MemoryPolicy e o protótipo SharedMemoryPool.
  • [2026-06-14] LightAgent v0.8.1: adiciona convenções MemoryScope e filtros MemoryPolicy por origem, escopo e confiança.
  • [2026-06-02] LightAgent v0.8.0: introduz LightFlow para workflows determinísticos de várias etapas.

Notas antigas estão em GitHub Releases.


✨ Funcionalidades

  • Leve e eficiente 🚀: Design minimalista, implementação rápida, adequado para vários cenários de aplicação. (Sem LangChain, Sem LlamaIndex) Implementação 100% em Python, sem dependências adicionais, com apenas 1000 linhas de código principal, totalmente open source.
  • Suporte a memória 🧠: Suporte a customização de memória de longo prazo para cada usuário, com o módulo de memória mem0, gerenciando automaticamente memórias personalizadas do usuário durante o diálogo, tornando o agente mais inteligente.
  • Aprendizado autônomo 📚️: Cada agente tem a capacidade de aprender de forma autônoma, enquanto administradores com permissões podem gerenciar cada agente.
  • Integração de ferramentas 🛠️: Suporte a ferramentas personalizadas (Tools), geração automatizada de ferramentas, flexibilidade para atender a diversas necessidades.
  • Objetivos complexos 🌳: Módulo de árvore de raciocínio (ToT) incorporado, suportando decomposição de tarefas complexas e raciocínio em múltiplos passos, aprimorando a capacidade de lidar com tarefas.
  • Colaboração multiagente 🤖: Colaboração multiagente mais simples de implementar do que o Swarm, com LightSwarm incorporado para avaliação de intenções e transferência de tarefas, capaz de processar entradas de usuário de forma mais inteligente e transferir tarefas para outros agentes conforme necessário.
  • Execução independente 🤖: Conclusão autônoma da chamada de ferramentas sem intervenção humana.
  • Suporte a múltiplos modelos 🔄: Compatível com OpenAI, ChatGLM, Baichuan, DeepSeek e séries de modelos Qwen.
  • API em tempo real 🌊: Suporte à saída de serviços de API em formato de fluxo OpenAI, integrado perfeitamente aos principais frameworks de chat, melhorando a experiência do usuário.
  • Gerador de ferramentas 🚀: Basta fornecer sua documentação de API ao [gerador de ferramentas], que ele criará automaticamente suas ferramentas personalizadas, permitindo a construção rápida de centenas de ferramentas personalizadas em apenas 1 hora, aumentando a eficiência e liberando seu potencial criativo.
  • Auto-aprendizado de agentes 🧠️: Cada agente terá sua própria capacidade de memória de cenário, permitindo o aprendizado autônomo a partir das interações do usuário.
  • Mecanismo adaptativo de ferramentas 🛠️: Suporte à adição de ferramentas em quantidade ilimitada, permitindo que o modelo grande selecione um conjunto de ferramentas candidatas entre milhares de opções, filtrando as irrelevantes antes de enviar o contexto para o modelo grande, reduzindo significativamente o consumo de tokens.
  • Orquestração de workflows 🔁: LightFlow encadeia agentes em workflows determinísticos com dependências explícitas, passagem de saídas, retentativas, checkpoints, resume/rerun, aprovações, agentes fallback e execução rastreável.
  • Protótipo de memória compartilhada 🧠: SharedMemoryPool fornece memória compartilhada em memória com metadados de procedência, recuperação por escopo e resultados compatíveis com MemoryPolicy.
  • Modelos Guardrails 🛡️: Políticas reutilizáveis de entrada, ferramentas e saída bloqueiam dados privados, confirmam ferramentas sensíveis, validam parâmetros de alto risco e redigem saídas.
  • Runtime Hooks 🧩: Middleware ordenado hooks=[...] para observar, substituir ou bloquear fases de execução, modelo, ferramenta, memória e etapas LightFlow.

🧭 Arquitetura em resumo

Camada API principal Use quando precisar
Runtime de agente único LightAgent Um agente com modelo, ferramentas, memória, streaming, trace e guardrails.
Roteamento multiagente LightSwarm Delegação por papéis entre agentes especializados.
Workflow determinístico LightFlow DAG, retentativas, checkpoints, aprovações, resume e rerun.
Ferramentas e integrações tools, ToolRegistry, MCP Ferramentas Python, geradas, carregamento em runtime ou servidores MCP.
Limite de memória MemoryPolicy, MemoryScope Isolamento de tenants, procedência, confiança, expiração e admissão de escrita.
Memória compartilhada SharedMemoryPool Experimentos de memória compartilhada entre agentes.
Segurança input_guardrails, tool_guardrails, output_guardrails Privacidade, confirmação de ferramentas, parâmetros de risco e redação de saída.
Runtime hooks hooks, HookContext, HookDecision Política, auditoria, redação, roteamento e mutação de payloads nas fronteiras do ciclo de vida.
Observabilidade trace=True, agent.export_trace() Eventos estruturados de execução, modelo, ferramenta, erro e workflow.

Padrões principais de uso

LightAgent mantém a chamada padrão simples e permite adicionar controles de produção gradualmente.

Padrão Chamada mínima Notas
Resposta básica agent.run(query) Retorna string por padrão.
Streaming agent.run(query, stream=True) Retorna chunks compatíveis com OpenAI.
Resultado estruturado agent.run(query, result_format="object") Retorna conteúdo e metadados.
Trace agent.run(query, trace=True) Registra eventos sem mudar a string padrão.
Memória de usuário agent.run(query, user_id="alice") Usa backend de memória e MemoryPolicy configurados.
Ferramentas LightAgent(..., tools=[fn]) Funções devem expor tool_info.
Guardrails LightAgent(..., input_guardrails=[...]) Adiciona políticas de entrada, ferramenta e saída.
Runtime hooks LightAgent(..., hooks=[fn]) Observa, substitui ou bloqueia payloads do ciclo de vida.
Workflow LightFlow().step(...).run(query) Para execução determinística multi-etapa.

📋 Documentação

  • Para instalação, modelos, ferramentas, memória, MCP, Skills, streaming e LightSwarm, consulte FAQ.
  • Para workflows determinísticos, checkpoints, resume/rerun, aprovações, agentes fallback e estados de etapa, consulte LightFlow.
  • Para ferramentas customizadas, ToolRegistry, ToolLoader, AsyncToolDispatcher e MCP, consulte Tools Guide.
  • Para memória compartilhada ou memória em grafo, consulte Memory Security Guidance.
  • Para SharedMemoryPool, consulte SharedMemoryPool.
  • Para admissão de escrita de memória e expiração, consulte Memory Admission And Mutation Controls.
  • Para segurança de entrada, ferramentas e saída, consulte Guardrails.
  • Para middleware runtime que observa, substitui ou bloqueia payloads, consulte Runtime Hooks.
  • Para OpenRouter, modelos locais e provedores compatíveis com OpenAI, consulte Model Provider Configuration.
  • Para traces estruturados, consulte Trace Observability.

🚧 Em breve

  • Comunicação colaborativa entre agentes 🛠️: Os agentes também podem compartilhar informações e transmitir mensagens, realizando comunicações complexas de informações e colaboração em tarefas.
  • Avaliação de agentes 📊: Ferramenta de avaliação de agentes embutida, facilitando a avaliação e otimização do agente que você criou, alinhando-se aos cenários de negócios e melhorando continuamente o nível de inteligência.

🌟 Por que escolher o LightAgent?

  • Open source e gratuito 💖: Totalmente open source, dirigido pela comunidade, atualizações contínuas, contribuições são bem-vindas!
  • Fácil de usar 🎯: Documentação detalhada, exemplos ricos, fácil integração ao seu projeto.
  • Suporte da comunidade 👥: Comunidade de desenvolvedores ativa, pronta para ajudar e responder a suas perguntas.
  • Alto desempenho ⚡: Design otimizado, operação eficiente, atendendo a necessidades de alto tráfego.

🛠️ Começando rapidamente

Instale a versão mais recente do LightAgent

pip install lightagent

(Instalação opcional) Instale o pacote Mem0 via pip:

pip install mem0ai

Ou você pode usar o Mem0 em uma plataforma de hospedagem clicando aqui.

Exemplo de código Hello world

from LightAgent import LightAgent

# Inicializa o Agente
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url= "your_base_url")

# Executa o Agente
response = agent.run("Olá, quem é você?")
print(response)

Inspecionar um trace de execução (v0.7.0)

Trace é opcional e mantém compatível o comportamento padrão de agent.run().

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Criar checkpoint de uma execução LightFlow (v0.9.0)

LightFlow pode persistir checkpoints e retomar execuções com falha sem reiniciar do primeiro passo.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

Usar SharedMemoryPool (v0.9.0)

SharedMemoryPool é um protótipo leve em memória para experimentos de memória compartilhada multiagente.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Definindo a auto-percepção do modelo através do sistema de prompt

from LightAgent import LightAgent

# Inicializa o Agente
agent = LightAgent(
     role="Por favor, lembre-se de que você é o LightAgent, um assistente útil que pode ajudar os usuários com o uso de múltiplas ferramentas.",  # descrição do papel do sistema
     model="deepseek-chat",  # modelos suportados: openai, chatglm, deepseek, qwen, etc.
     api_key="your_api_key",  # substitua pela chave de API de seu fornecedor de modelo grande
     base_url="your_base_url",  # substitua pela URL API de seu fornecedor de modelo grande
 )
# Executa o Agente
response = agent.run("Quem é você?")
print(response)

Exemplo de código usando ferramentas

from LightAgent import LightAgent


# Define a ferramenta
def get_weather(city_name: str) -> str:
    """
    Obtém o clima atual para `city_name`
    """
    return f"Resultado da consulta: O clima em {city_name} está ensolarado."
# Informações de ferramenta definidas dentro da função
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Obtém as informações climáticas atuais para a cidade especificada",
    "tool_params": [
        {"name": "city_name", "description": "Nome da cidade a ser consultada", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Inicializa o Agente
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# Executa o Agente
response = agent.run("Por favor, verifique a situação do clima em Xangai.")
print(response)

Suporte a um número ilimitado de ferramentas personalizadas.

Exemplos de múltiplas ferramentas: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


Explicação das funcionalidades

README mantém o modelo central de uso; exemplos longos, configuração de adaptadores e práticas de produção ficam nos docs dedicados.

1. Módulo de memória destacável (mem0)

LightAgent aceita qualquer backend de memória com store(data, user_id) e retrieve(query, user_id). Use user_id para isolar conversas e MemoryPolicy quando a memória for compartilhada.

2. Integração de ferramentas

Use funções Python com metadados tool_info para expor capacidades controladas. Para ToolRegistry, ToolLoader, AsyncToolDispatcher e MCP, consulte Tools Guide.

3. Gerador de ferramentas

agent.create_tool() pode gerar código de ferramentas a partir de documentação de API ou descrições naturais. Revise e teste antes de produção.

4. Árvore de Pensamento (ToT)

Ative tree_of_thought=True quando a tarefa exigir planejamento explícito, reflexão e seleção de ferramentas.

5. Colaboração multiagente

LightSwarm delega trabalho entre agentes especializados. Mantenha papéis claros e controle escritas de memória.

6. API streaming

agent.run(query, stream=True) retorna chunks compatíveis com OpenAI para chat UIs e respostas longas.

7. Autoaprendizado do agente

Autoaprendizado deve ser combinado com MemoryPolicy para evitar conteúdo privado, expirado ou irrelevante.

8. Trace e Langfuse

LightAgent permite observar execução por trace integrado ou Langfuse.

9. Avaliação de agentes

A avaliação de agentes medirá comportamento em cenários de negócio.

10. Workflows LightFlow

LightFlow é a camada de workflow determinística para executar etapas conhecidas.

  • Estados de etapa: pending, running, success, failed, skipped, waiting_approval.
  • Validação DAG: flow.validate(strict=True).
  • Controles de etapa: timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • Persistência e recuperação: JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

Consulte LightFlow.

11. Guardrails

Guardrails são hooks leves para entrada, chamadas de ferramenta e saída.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

Consulte Guardrails.

12. SharedMemoryPool

SharedMemoryPool é um protótipo em memória para memória compartilhada multiagente, usado com MemoryPolicy.

Modelos principais de Agentes suportados

LightAgent funciona com endpoints chat completion compatíveis com OpenAI: OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama e gateways próprios.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

Cenários de uso

  • Atendimento ao cliente inteligente: Através de diálogos multironda e integração de ferramentas, proporcionando suporte ao cliente eficiente.
  • Análise de dados: Utilizando árvores de raciocínio e colaboração multiagente, lidando com tarefas de análise de dados complexas.
  • Ferramentas automatizadas: Usando geração automatizada de ferramentas, construindo rapidamente ferramentas personalizadas.
  • Assistência educacional: Oferecendo experiências de aprendizagem personalizadas por meio de módulos de memória e API em tempo real.

🛠️ Guias de contribuição

Agradecemos qualquer forma de contribuição! Seja código, documentação, testes ou feedback, todos são de grande ajuda para o projeto. Se você tiver boas ideias ou encontrar Bugs, por favor, apresente um Issue ou Pull Request. Aqui estão as etapas para contribuir:

  1. Fork este projeto: Clique no botão Fork no canto superior direito para copiar o projeto para seu repositório GitHub.
  2. Crie uma branch: Crie uma branch de desenvolvimento local:
    git checkout -b feature/SuaFuncionalidade
    
  3. Submeta suas alterações: Após a conclusão do desenvolvimento, submeta suas alterações:
    git commit -m 'Adicionando nova funcionalidade'
    
  4. Envie a branch: Envie a branch para o seu repositório remoto:
    git push origin feature/SuaFuncionalidade
    
  5. Submeta um Pull Request: Apresente um Pull Request no GitHub, descrevendo o que você alterou.

Revisaremos sua contribuição assim que possível, agradecemos seu apoio!❤️


🙏 Agradecimentos

O desenvolvimento e implementação do LightAgent não seriam possíveis sem a inspiração e apoio dos seguintes projetos open source, com um agradecimento especial a estas incríveis equipes:

  • mem0: Agradecimentos ao mem0 pelo fornecimento do módulo de memória, que oferece suporte robusto para gerenciamento de contexto no LightAgent.
  • Swarm: Agradecimentos ao Swarm pela concepção de colaboração multiagente, que serve como base para as funcionalidades multiagente do LightAgent.
  • ChatGLM3: Agradecimentos ao ChatGLM3 pelo suporte de modelos grandes de alto desempenho em chinês e por inspirar o design.
  • Qwen: Agradecimentos ao Qwen pelo suporte de modelos grandes de alto desempenho em chinês.
  • DeepSeek-V3: Agradecimentos ao DeepSeek-V3 pelo suporte de modelos grandes de alto desempenho em chinês.
  • StepFun: Agradecimentos à step pelo suporte de modelos grandes de alto desempenho em chinês.

📄 Licença

LightAgent usa a Licença Apache 2.0. Você pode usar, modificar e distribuir este projeto livremente, mas deve respeitar os termos da licença.


📬 Contate-nos

Para qualquer dúvida ou sugestão, não hesite em entrar em contato conosco:

Aguardamos seu feedback para tornar o LightAgent ainda mais poderoso!🚀

  • Mais ferramentas 🛠️: Integração contínua de mais ferramentas úteis para atender a mais necessidades de cenários.
  • Mais suporte a modelos 🔄: Expansão contínua para suportar mais modelos grandes, atendendo a mais casos de uso.
  • Mais funcionalidades 🎯: Mais funcionalidades úteis, atualizações contínuas, fique atento para mais novidades!
  • Mais documentação 📚: Documentação expansiva, exemplos muitos, fácil implementação nos seus projetos.
  • Mais apoio da comunidade 👥: Comunidade de desenvolvedores ativa, disponível para ajudá-lo a qualquer momento.
  • Mais otimizações de desempenho ⚡: Otimizações contínuas para atender a necessidades de cenários de alta concorrência.
  • Mais contribuições open source 🌟: Contribuições de código são bem-vindas, vamos criar um LightAgent ainda melhor juntos!

LightAgent - Reduzindo a complexidade da inteligência, simplificando o futuro. 🌈

LightAgent —— Estrutura de agente leve, flexível e poderosa para ajudá-lo a construir aplicações inteligentes rapidamente!

LightAgent Banner

License GitHub release GitHub issues GitHub stars GitHub forks GitHub contributors Docs PyPI Downloads Python Version Code Style

LightAgent является крайне легковесным активным агентным фреймворком с памятью (mem0), инструментами (Tools) и деревом мышления (ToT), полностью с открытым исходным кодом. Он поддерживает более простую многослойную координацию агентов, чем OpenAI Swarm, и позволяет в один шаг создать агента с возможностью самообучения, а также поддерживает подключение к протоколу MCP через stdio и sse. Базовая модель поддерживает OpenAI, Zhiyu ChatGLM, DeepSeek, Jieyue Xingchen, Qwen Tongyi Qianwen и другие крупные модели. В то же время, LightAgent поддерживает вывод API-сервиса в формате OpenAI Stream, бесшовно интегрируясь с основными чат-фреймворками.🌟


Новости

  • new[2026-06-24] LightAgent v0.9.0: добавлены сохраняемые checkpoint для LightFlow, resume/rerun, узлы утверждения, более ясные состояния шагов, trace-метаданные, шаблоны Guardrails, управление MemoryPolicy и прототип SharedMemoryPool.
  • [2026-06-14] LightAgent v0.8.1: добавлены соглашения MemoryScope и фильтры MemoryPolicy по источнику, области и уровню доверия.
  • [2026-06-02] LightAgent v0.8.0: представлен LightFlow для детерминированных многошаговых workflow.

История релизов доступна в GitHub Releases.


✨ Особенности

  • Легковесность и эффективность 🚀: ультра-упрощённый дизайн, быстрая настройка, подходит для приложений любого размера. (Нет LangChain, Нет LlamaIndex) 100% реализация на Python, без дополнительных зависимостей, основная кодовая база составляет всего 1000 строк, полностью открытый исходный код.
  • Поддержка памяти 🧠: поддержка пользовательской долгосрочной памяти для каждого пользователя, нативная поддержка модуля памяти mem0, позволяющая автоматически управлять персонализированной памятью пользователя в процессе диалога, делая агента более умным.
  • Автономное обучение 📚️: каждый агент обладает способностью самостоятельно обучаться, а администраторы с соответствующими правами могут управлять каждым агентом.
  • Интеграция инструментов 🛠️: поддержка пользовательских инструментов (Tools), автоматическая генерация инструментов, гибкое расширение для удовлетворения разнообразных потребностей.
  • Сложные цели 🌳: встроенный модуль дерева мышления с рефлексией (ToT), поддержка декомпозиции сложных задач и многошагового вывода, повышение эффективности обработки задач.
  • Многослойное взаимодействие агентов 🤖: более простая реализация многослойного взаимодействия агентов, встроенный LightSwarm для определения намерений и переноса задач, что позволяет более умно обрабатывать ввод пользователя и при необходимости передавать задачи другим агентам.
  • Автономное выполнение 🤖: выполнение вызовов инструментов без человеческого вмешательства.
  • Поддержка множества моделей 🔄: совместимость с OpenAI, ChatGLM от Zhipu, Baichuan и другим.
  • Потоковый API 🌊: поддержка вывода сервисов API в потоковом формате OpenAI, бесшовная интеграция с основными чат-фреймворками, улучшение пользовательского опыта.
  • Генератор инструментов Tools 🚀: просто передайте вашу документацию API [генератору инструментов Tools], и он автоматически создаст для вас индивидуальные инструменты, позволяя вам быстро создать сотни персонализированных инструментов всего за час, повысив производительность и освободив ваши творческие возможности.
  • Самообучение агентов 🧠️: каждый агент обладает способностью запоминать информацию о сценах и самообучаться на основе разговоров с пользователями.
  • Адаптивный механизм инструментов 🛠️: поддержка неограниченного количества инструментов, выбор кандидатов из десятков тысяч инструментов крупной моделью, фильтрация нерелевантных инструментов и передача контекста крупной модели, что может значительно снизить потребление токенов.
  • Оркестрация workflow 🔁: LightFlow связывает агентов в детерминированные workflow с явными зависимостями, передачей результатов, повторами, checkpoint, resume/rerun, утверждениями, fallback-agent и трассировкой.
  • Прототип общей памяти 🧠: SharedMemoryPool предоставляет общую память в памяти процесса с метаданными происхождения, выборкой по области и результатами, совместимыми с MemoryPolicy.
  • Шаблоны Guardrails 🛡️: Переиспользуемые политики ввода, инструментов и вывода блокируют приватные данные, требуют подтверждения чувствительных инструментов, проверяют рискованные параметры и редактируют вывод.
  • Runtime Hooks 🧩: Упорядоченное middleware hooks=[...] для наблюдения, замены или блокировки фаз run, модели, инструментов, памяти и шагов LightFlow.

🧭 Архитектура кратко

Слой Основной API Когда использовать
Runtime одного агента LightAgent Один агент с моделью, инструментами, памятью, streaming, trace и guardrails.
Маршрутизация агентов LightSwarm Делегирование по ролям между специализированными агентами.
Детерминированный workflow LightFlow DAG, повторы, checkpoints, утверждения, resume и rerun.
Инструменты и интеграции tools, ToolRegistry, MCP Python-инструменты, генерация, runtime-загрузка или MCP-серверы.
Граница памяти MemoryPolicy, MemoryScope Изоляция tenants, происхождение, доверие, срок действия и допуск записи.
Общая память SharedMemoryPool Эксперименты общей памяти между агентами.
Безопасность input_guardrails, tool_guardrails, output_guardrails Приватность, подтверждение инструментов, рискованные параметры и редактирование вывода.
Runtime hooks hooks, HookContext, HookDecision Политики, аудит, редактирование, routing и изменение payload на границах жизненного цикла.
Наблюдаемость trace=True, agent.export_trace() Структурированные события run, модели, инструмента, ошибки и workflow.

Основные паттерны использования

LightAgent сохраняет простой путь вызова по умолчанию и позволяет постепенно добавлять production-контроль.

Паттерн Минимальный вызов Примечания
Базовый ответ agent.run(query) По умолчанию возвращает строку.
Streaming agent.run(query, stream=True) Возвращает OpenAI-совместимые chunks.
Структурированный результат agent.run(query, result_format="object") Возвращает контент и метаданные.
Trace agent.run(query, trace=True) Пишет события, не меняя строковый ответ по умолчанию.
Память пользователя agent.run(query, user_id="alice") Использует настроенный backend памяти и MemoryPolicy.
Инструменты LightAgent(..., tools=[fn]) Функции должны иметь tool_info.
Guardrails LightAgent(..., input_guardrails=[...]) Добавляет политики ввода, инструментов и вывода.
Runtime hooks LightAgent(..., hooks=[fn]) Наблюдает, заменяет или блокирует payload жизненного цикла.
Workflow LightFlow().step(...).run(query) Для детерминированного многошагового выполнения.

📋 Документация

  • По установке, моделям, инструментам, памяти, MCP, Skills, streaming и LightSwarm см. FAQ.
  • По детерминированным workflow, checkpoint, resume/rerun, утверждениям, fallback-agent и состояниям шагов см. LightFlow.
  • По пользовательским инструментам, ToolRegistry, ToolLoader, AsyncToolDispatcher и MCP см. Tools Guide.
  • По общей долговременной или графовой памяти см. Memory Security Guidance.
  • По SharedMemoryPool см. SharedMemoryPool.
  • По допуску записи памяти и срокам действия см. Memory Admission And Mutation Controls.
  • По безопасности ввода, инструментов и вывода см. Guardrails.
  • По runtime middleware для наблюдения, замены или блокировки payload см. Runtime Hooks.
  • По OpenRouter, локальным моделям и OpenAI-совместимым провайдерам см. Model Provider Configuration.
  • По структурированным trace см. Trace Observability.

🚧 В ближайшем будущем

  • Согласованная связь агентов 🛠️: Агенты также могут обмениваться информацией и передавать сообщения, реализуя сложную информационную связь и совместное выполнение задач.
  • Оценка Агентов 📊: встроенные инструменты оценки агентов, удобные для оценки и оптимизации созданных вами агентов для привязки к бизнес-сценариям, постоянное повышение уровня интеллекта.

🌟 Почему выбирают LightAgent?

  • Открытый и бесплатный 💖: полностью открытый, управляемый сообществом, регулярно обновляемый, все желающие могут внести свой вклад!
  • Легкость в освоении 🎯: подробная документация, множество примеров, быстрое освоение, простая интеграция в ваши проекты.
  • Поддержка сообщества 👥: активное сообщество разработчиков, готовое помочь и ответить на вопросы.
  • Высокая производительность ⚡: оптимизированный дизайн, высокая эффективность, удовлетворяющая требования к высокой конкуренции.

🛠️ Быстрый старт

Установка последней версии LightAgent

pip install lightagent

(Опционально установите пакет Mem0):

pip install mem0ai

Или вы можете использовать Mem0 в облачной стороне, кликнув здесь.

Пример кода Hello world

from LightAgent import LightAgent

# Инициализация агента
agent = LightAgent(model="gpt-4o-mini", api_key="your_api_key", base_url= "your_base_url")

# Запуск агента
response = agent.run("Привет, кто ты?")
print(response)

Проверка trace выполнения (v0.7.0)

Trace включается явно и сохраняет совместимость поведения agent.run() по умолчанию.

from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])

Checkpoint выполнения LightFlow (v0.9.0)

LightFlow может сохранять checkpoint workflow и продолжать неудачный запуск не с первого шага.

from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])

Использование SharedMemoryPool (v0.9.0)

SharedMemoryPool — легкий in-memory прототип для экспериментов с общей памятью между агентами.

from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))

Установка самосознания модели через системные подсказки

from LightAgent import LightAgent

# Инициализация агента
agent = LightAgent(
     role="Пожалуйста, помните, что вы - LightAgent, полезный помощник, который может помочь пользователям с использованием нескольких инструментов.",  # Описание системной роли
     model="deepseek-chat",  # Поддерживаемые модели: openai, chatglm, deepseek, qwen и т.д.
     api_key="your_api_key",  # Замените на ключ API вашего провайдера крупной модели
     base_url="your_base_url",  # Замените на URL API вашего провайдера крупной модели
 )
# Запуск агента
response = agent.run("Кто ты?")
print(response)

Пример кода использования инструмента

from LightAgent import LightAgent


# Определение инструмента
def get_weather(city_name: str) -> str:
    """
    Получить текущую погоду для `city_name`
    """
    return f"Результат запроса: Погода в {city_name} солнечная"
# Определить информацию о инструменте внутри функции
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Получите текущую информацию о погоде в заданном городе",
    "tool_params": [
        {"name": "city_name", "description": "Название города для запроса", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Инициализация агента
agent = LightAgent(model="qwen-turbo-2024-11-01", api_key="your_api_key", base_url= "your_base_url", tools=tools)

# Запуск агента
response = agent.run("Пожалуйста, проверьте погоду в Шанхае")
print(response)

Поддерживает настройку неограниченного количества инструментов.

Примеры нескольких инструментов: tools = [search_news,get_weather,get_stock_realtime_data,get_stock_kline_data]


Подробное описание функций

README сохраняет основную модель использования; длинные примеры, настройка адаптеров и production-практики находятся в отдельных документах.

1. Съемный модуль памяти (mem0)

LightAgent принимает любой backend памяти с store(data, user_id) и retrieve(query, user_id). Используйте user_id для изоляции диалогов и MemoryPolicy для общей памяти.

2. Интеграция инструментов

Python-функции с метаданными tool_info открывают контролируемые возможности агенту. ToolRegistry, ToolLoader, AsyncToolDispatcher и MCP описаны в Tools Guide.

3. Генератор инструментов

agent.create_tool() может генерировать код инструментов из API-документации или естественного описания. Перед production выполните review и тесты.

4. Дерево мышления (ToT)

Включайте tree_of_thought=True, когда нужны явное планирование, рефлексия и выбор инструментов.

5. Совместная работа агентов

LightSwarm делегирует работу между специализированными агентами. Роли должны быть узкими, а записи памяти контролироваться политиками.

6. Streaming API

agent.run(query, stream=True) возвращает OpenAI-совместимые chunks для chat UI и длинных ответов.

7. Самообучение агента

Самообучение следует сочетать с MemoryPolicy, чтобы не сохранять приватный, устаревший или нерелевантный контент.

8. Trace и Langfuse

LightAgent позволяет наблюдать выполнение через встроенный trace или Langfuse.

9. Оценка агентов

Оценка агентов будет измерять поведение в бизнес-сценариях.

10. Workflow LightFlow

LightFlow — детерминированный workflow-слой для выполнения известных шагов.

  • Состояния шагов: pending, running, success, failed, skipped, waiting_approval.
  • Проверка DAG: flow.validate(strict=True).
  • Управление шагом: timeout, max_retry, cancel_if, fallback_agent, requires_approval, approval_handler.
  • Сохранение и восстановление: JsonLightFlowStore, flow.resume(run_id), flow.rerun_step(run_id, step_name), flow.get_run(run_id), flow.list_runs().

См. LightFlow.

11. Guardrails

Guardrails — легкие hooks для проверки ввода, вызовов инструментов и вывода.

from LightAgent import (
    LightAgent,
    high_risk_parameter_guardrail,
    output_redaction_guardrail,
    privacy_input_guardrail,
    sensitive_tool_confirmation_guardrail,
)

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    input_guardrails=[privacy_input_guardrail()],
    tool_guardrails=[
        sensitive_tool_confirmation_guardrail(["transfer_money"], approved=False),
        high_risk_parameter_guardrail({"amount": lambda value: float(value) <= 1000}),
    ],
    output_guardrails=[output_redaction_guardrail()],
)

См. Guardrails.

12. SharedMemoryPool

SharedMemoryPool — in-memory прототип общей памяти между агентами, используйте его вместе с MemoryPolicy.

Поддержка основных моделей агентств

LightAgent работает с OpenAI-совместимыми chat completion endpoint: OpenAI, OpenRouter, Zhipu ChatGLM, DeepSeek, Qwen, StepFun, Moonshot/Kimi, MiniMax, vLLM, llama.cpp, Ollama и собственные gateways.

For provider-specific parameters, base URLs, local model setup, and troubleshooting, see Model Provider Configuration.

Сценарии использования

  • Умный клиент: Обеспечение эффективной поддержки клиентов через многоуровневое взаимодействие и интеграцию инструментов.
  • Анализ данных: Использование дерева мышления и многослойного взаимодействия для обработки сложных задач анализа данных.
  • Автоматизация инструментов: Быстрое создание индивидуальных инструментов через автоматическую генерацию.
  • Учебная помощь: Обеспечение персонализированного опыта обучения с помощью модуля памяти и потокового API.

🛠️ Рекомендации по вкладу

Мы приветствуем любую форму вклада! Будь то код, документация, тестирование или обратная связь - всё это огромная помощь проекту. Если у вас есть хорошие идеи или вы нашли ошибку, пожалуйста, подайте заявку или Pull Request. Вот шаги по вкладке:

  1. Сделайте форк проекта: нажмите кнопку Fork в правом верхнем углу, чтобы скопировать проект в ваш репозиторий GitHub.
  2. Создайте ветвь: создайте вашу разработческую ветвь локально:
    git checkout -b feature/YourFeature
    
  3. Подайте измененные данные: после завершения разработки подайте ваши изменения:
    git commit -m 'Добавление новой функции'
    
  4. Отправьте ветвь: отправьте ветвь в ваш удалённый репозиторий:
    git push origin feature/YourFeature
    
  5. Подайте Pull Request: в GitHub подайте Pull Request с описанием ваших изменений.

Мы проверим ваш вклад как можно быстрее, спасибо за поддержку!❤️


🙏 Благодарности

Разработка и реализация LightAgent стали возможны благодаря вдохновению и поддержке следующих открытых проектов, особенно благодарим эти замечательные проекты и команды:

  • mem0: Спасибо mem0 за предоставление модуля памяти, который стал важным элементом управления контекстом для LightAgent.
  • Swarm: Спасибо Swarm за идеи по многослойному взаимодействию агентов, которые стали основой функций LightAgent.
  • ChatGLM3: Спасибо ChatGLM3 за поддержку высокопроизводительных китайских моделей и идеи по проектированию.
  • Qwen: Спасибо Qwen за поддержку высокопроизводительных китайских моделей.
  • DeepSeek-V3: Спасибо DeepSeek-V3 за поддержку высокопроизводительных китайских моделей.
  • Серия шагов: Спасибо step за поддержку высокопроизводительных китайских моделей.

📄 Лицензия

LightAgent лицензирован под Apache 2.0 лицензией. Вы можете свободно использовать, изменять и распространять этот проект, но пожалуйста, соблюдайте условия лицензии.


📬 Свяжитесь с нами

Если у вас есть вопросы или предложения, команда всегда открыта для контакта:

Мы ждём ваших отзывов, чтобы вместе сделать LightAgent ещё сильнее!🚀


LightAgent - сделаем интеллект легче, а будущее проще. 🌈

LightAgent — легковесная, гибкая, мощная активная платформа агента, помогающая вам быстро разрабатывать интеллектуальные приложения!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lightagent-0.9.1.tar.gz (194.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lightagent-0.9.1-py3-none-any.whl (127.6 kB view details)

Uploaded Python 3

File details

Details for the file lightagent-0.9.1.tar.gz.

File metadata

  • Download URL: lightagent-0.9.1.tar.gz
  • Upload date:
  • Size: 194.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.11.7 Darwin/25.5.0

File hashes

Hashes for lightagent-0.9.1.tar.gz
Algorithm Hash digest
SHA256 0d1be42e7bb4c95c8938cb4690a4f8cc366783128b317c884192cf5edceb4982
MD5 1baba78362f9444fc24953afbda47a4e
BLAKE2b-256 ab294b11e5f7770a96508c02f4ef9f091a7e7bb926f18ecd5035d193664398e8

See more details on using hashes here.

File details

Details for the file lightagent-0.9.1-py3-none-any.whl.

File metadata

  • Download URL: lightagent-0.9.1-py3-none-any.whl
  • Upload date:
  • Size: 127.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.11.7 Darwin/25.5.0

File hashes

Hashes for lightagent-0.9.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ff2e57e5ab25755e94c56e8a9e82dc0041976d5354361ac2b6bbd63295d64425
MD5 c89b274c18f718379825726ced94f784
BLAKE2b-256 5a3df750ff44f59051a87824c84d5d0dce6042cb4ac923826209890ab616bcff

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page