LightAgent🚀 – small footprint, big potential. 🌟(Open-source Agentic framework)
LightAgent is a modular, open-source Python framework with reusable Skills, tools, optional long-term memory, and OpenAI-compatible models and streaming. Use LightSwarm for routing, LightFlow for known steps, and LightDAG for persistent, dynamically verified tasks. Its optional event-sourced runtime adds durable Sessions, async execution, policy, and approvals. MCP supports stdio, SSE, and Streamable HTTP.
News
[2026-11-15] LightAgent v1.0.0 released on GitHub. Adds reconnectable execution, a shared Job/Subagent lifecycle, transactional recovery and optional signed Providers.
- [2026-10-04] v0.12.0 implemented in source (not yet published): opt-in persistent research, verified DAG experiments, durable inbox, independent chat, a local reference panel, and evaluated version adoption/rollback. See the research service guide.
- [2026-10-01] LightAgent v0.11.0 Released: Adds opt-in persistent Dynamic DAG multi-agent execution, verification-gated immutable artifacts, restart-safe leases and fencing, and a unified narrowing-only
SecurityContextwith capability and approval controls. - [2026-08-15] LightAgent v0.10.0 Released: Adds the unified event-sourced Agent Runtime with durable Sessions, async execution, Capability Registry and Policy, Inbox/Goals/Budgets, compaction and recovery, Jobs/subagents, standardized Skills/MCP adapters, and SQLite FTS5 retrieval.
- [2026-08-15] LightAgent v0.9.7 Released: Adds a dependency-free Connector contract with offline validation and examples, expands Python executor security checks, introduces an opt-in Mem0 Graph security matrix, and adds a public API compatibility inventory for v1.0 stabilization.
- [2026-07-30] LightAgent v0.9.6 Released: Adds production trace summaries and exporters, deterministic evaluation, durable human approval for tools, handoffs, and LightFlow, plus fail-closed shared Graph Memory admission and audit controls.
- [2026-07-10] LightAgent v0.9.3 Released: Completes runtime hook lifecycle coverage and hardens streaming tool safety with
max_tool_iterations, consistenton_error/after_runclosure, and expanded regression coverage. - [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.
- [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()andstream=Truebehavior 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.
✨ 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
mem0memory module, automatically managing user personalized memory during conversations, making agents smarter. - Autonomous Learning 📚️: Each agent possesses autonomous learning capabilities, and admins with permissions can manage each agent.
- Tool Integration 🛠️: Support for custom tools (
Tools) and MCP tool integration, flexible expansion to meet diverse needs. - Complex Goals 🌳: Built-in Tree of Thought (
ToT) module with reflection, supporting complex task decomposition and multi-step reasoning, enhancing task processing capabilities. - Multi-Agent Collaboration 🤖: Simpler to implement multi-agent collaboration than Swarm, with built-in LightSwarm for intent recognition and task delegation, enabling smarter handling of user input and delegating tasks to other agents as needed.
- 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.
- Optional Codex Agent Backend: Use the local Codex CLI to run workspace tasks with
LightAgent(backend="codex"). The default LightAgent backend does not require Codex. - Streaming API 🌊: Supports OpenAI streaming format API service output, seamlessly integrates with mainstream chat frameworks, enhancing user experience.
- Trace Observability 🔎: Opt-in
trace=Truerun traces record structured run lifecycle, model request summaries, tool calls, tool results, and errors without changing the default string return value. - Evaluation Harness 📊:
LightEvaluatorruns deterministic agent or LightFlow regression cases for output, tool choice, policy events, recovery, latency, usage, and estimated cost. - Human Review 👤:
HumanApprovalHook, durable review stores, and LightFlow approval checkpoints support approve, reject, argument editing, human responses, batches, and trace feedback for high-impact actions. - 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. - Event-Sourced Runtime 🧱: Optional durable Sessions, replay, checkpoints, forks, async entry points, scoped Capability Providers, unified Policy, Inbox, Goals, Budgets, Jobs, subagents, context compaction, and SQLite FTS5 retrieval.
- Dynamic Verified DAGs: Opt-in LightDAG persists runtime graph changes, executes independent Workers concurrently, requires application-owned verification before artifact publication, and resumes safely with leases and fencing.
- 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. |
| Durable runtime state | Session, AgentRuntime |
Replayable events, checkpoints, Inbox, Goals, Budgets, Jobs, and context recovery. |
| Durable execution (v1.0.0) | ExecutionService, ExecutionHandle |
Ordinary reconnectable tasks without a research contract; explicit host backend and security context. |
| Capability layer | CapabilityRegistry, PolicyEngine |
Scoped Providers, permission snapshots, lifecycle, policy, and audit. |
| Unified security context | SecurityContext, CapabilityGate, ApprovalToken |
Identity, narrowing-only permissions, authorization, and operation-bound approval. |
| Multi-agent routing | LightSwarm |
Role-based delegation across specialized agents. |
| Deterministic workflow | LightFlow |
Ordered DAG workflows, retries, checkpoints, durable approvals, resume, and rerun. |
| Dynamic verified workflow | LightDAG |
Runtime decomposition, Verifiers, artifacts, concurrent Workers, and recovery. |
| Tools and integrations | tools, ToolRegistry, MCP |
Python tools, generated tools, runtime tool loading, or MCP tool servers. Legacy arbitrary-Python tools are blocked in model/tool dispatch; use safe_expression or a custom isolated tool. |
| 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, summarize_trace, trace exporters |
Structured events, latency, usage, retry/error metrics, JSONL or external export. |
| Evaluation | LightEvaluator, EvaluationCase |
Fixed regression cases for output, tools, policy events, recovery, latency, and cost. |
| Human review | HumanApprovalHook, ApprovalDecision, review stores |
Fail-closed tool/handoff review, argument editing, durable decisions, and feedback. |
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. |
| Evaluation | LightEvaluator().run(agent, cases) |
Run deterministic behavioral checks from structured traces. |
| Tool approval | LightAgent(..., hooks=[HumanApprovalHook(...)]) |
Require review before selected tools or handoffs. |
| Workflow | LightFlow().step(...).run(query) |
Use for deterministic multi-step execution. |
| Dynamic workflow | LightDAG(...).create_run(...) |
Use when Workers must propose tasks and only verified artifacts may complete nodes. |
| Durable session | agent.run(query, session_id="project-42") |
Configure a persistent SessionStore to continue and replay a conversation. |
| Async | await agent.arun(query) |
Keep an asyncio application responsive. |
Safe Tool Execution Defaults
In v0.10.1, arbitrary Python execution tools are not registered by default.
Use the built-in safe_expression tool for bounded arithmetic and data-only
expressions:
from LightAgent import safe_expression
print(safe_expression("45 * 9827"))
Legacy execute_python_code, execute_python_file, and
execute_python_code_stream are blocked in model and dispatcher invocation,
including with enable_unsafe_python=True or a registered SandboxProvider.
Trusted application code may call them directly under its own isolation
controls. Use a custom sandbox-backed tool for agent code execution; see
Python Executor Security.
Evaluate And Review High-Risk Actions
from LightAgent import EvaluationCase, HumanApprovalHook, LightEvaluator
agent.hooks.hooks.append(HumanApprovalHook(tools={"send_payment"}))
report = LightEvaluator().run(agent, [
EvaluationCase(
name="payment policy",
query="Pay invoice 42",
expected_trace_events=("approval_required",),
forbidden_tools=("delete_account",),
),
])
print(report.to_dict())
Pending approvals can be stored in JsonReviewStore; resolve them with an
ApprovalDecision, then rerun with approval_id=request.request_id. LightFlow
also persists step approvals through flow.approve(...); flow.resume(...).
v1.0.0: Durable Execution And Recovery
- Reconnectable tasks:
ExecutionServiceruns ordinary tasks through host-registered backends, without a research contract. UseExecutionHandleafter a restart to reconnect and inspect state, events, and receipts. See the offline example. - State and recovery: Jobs and Subagents share a lifecycle, leases, and cooperative cancellation. SQLite transactions protect Session state, messages, and budget accounting. Restored Subagents require explicit host binding, and uncertain external outcomes must be reconciled before retrying. See Job/history migration and the offline migration example.
- Safety and installation: Optional signed Provider bindings verify publisher signatures and require explicit host approval without replacing runtime policy. Skills and PyYAML remain in the base install. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS, and signature verification are optional.
- Compatibility: Ordinary
run()and streaming behavior are unchanged. Research contracts, evaluation, version promotion, and the debug panel live in the separate LightResearch extension. Legacymode="persistent"keeps its research semantics and requiresLightResearch.enable_legacy_api(). See the research migration guide.
See the GitHub Release for release notes and the validation record for the scope of testing. The core ships no production UI, and default CI does not require LightResearch.
v0.11.0: Verified Dynamic Workflows
Choose LightSwarm for role-based routing, LightFlow for a known workflow, and opt-in LightDAG when Workers must propose tasks during execution.
SqliteTaskGraphStorepersists tasks, attempts, graph changes, events, and recovery state. Independent Worker instances can run concurrently.- Workers submit
TaskOutcome.candidate(...),TaskOutcome.decompose(...), orTaskOutcome.blocked(...). Only an application-owned Verifier can approve decomposition or publish immutable artifacts. - Leases and fencing reject stale attempts during restart recovery.
SecurityContext,CapabilityGate, and operation-boundApprovalTokenkeep identity, narrowing-only permissions, and approvals explicit.
Offline LightDAG Example
No model, API key, or network is needed. This example uses a temporary SQLite database and artifact directory, then removes them on exit.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
For durable use, keep explicit database/artifact paths instead of a temporary directory. The complete dynamic decomposition and repair example and LightDAG guide cover dependencies, integration, retries, and recovery.
For durable Sessions, async calls, Capability Providers, Policy, Inbox, Goals, Budgets, and Jobs, see the runtime guide.
Compatibility And Safety
- Existing
agent.run(query),stream=True, anduser_idremain supported. LightDAG is opt-in and does not replace LightFlow. - v0.11.0 is single-host with local SQLite and one active scheduler per run. Execution is at-least-once; external side effects need idempotency. Distributed workers, a Web UI, and built-in code sandboxing are not included.
- Legacy
execute_python_code,execute_python_file, andexecute_python_code_streamare blocked in model/tool dispatch even withenable_unsafe_python=Trueor a registeredSandboxProvider. Usesafe_expressionor a genuinely isolated custom tool; trusted direct utility calls are not security sandboxes. - Memory provenance, admission, and promotion policies remain necessary. Framework regression tests do not certify a real shared Graph Memory backend; see the memory security boundary.
Release Versus Current Main
The v0.11.0 release was published on 2026-10-01. The later main fixes for tool-selection JSON, MCP SDK 1.x/2.x, and the optional deed.page example were merged after that tag; an installed release may not contain them. The following installs current main, not the original release tag:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
See the Tools Guide, optional Memcode adapter, deed.page example, and public API compatibility inventory. These examples do not require adding their external services to the core runtime.
🧩 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 an optional example that publishes agent-written pages to deed.page over Streamable HTTP MCP, with token handling and tool filtering, see Publishing Pages With deed.page Over MCP.
For packaging existing Tools, Skills, MCP settings, Hooks, and memory adapters into an offline-validatable extension, see Lightweight Connectors.
For shared long-term memory or graph memory deployments, review the Memory Security Guidance.
For the opt-in Mem0 Graph backend security matrix and issue #39 validation boundary, see Shared Graph Memory Security Validation.
For lightweight shared memory experiments, see SharedMemoryPool.
For optional ClawMem long-term memory adapter setup, see ClawMem Memory Adapter.
For an optional, user-scoped Memcode v2 adapter with offline fake-client tests, see Memcode Memory Adapter.
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 trace observability, summaries, and external export, see Trace Observability.
For deterministic regression cases, metrics, and CI guidance, see Evaluation Harness.
For tool/handoff approval, durable LightFlow review, batches, and feedback, see Human Review.
For the v1.0 stability proposal, supported Python versions, public imports, and compatibility promises, see Public API And Compatibility Inventory.
For durable Sessions, Capability Providers, Policy, Inbox, Goals, Budgets, Jobs, compaction, subagents, Skills/MCP updates, and SQLite FTS5 retrieval, see LightAgent v0.10 Runtime.
For persistent dynamic task graphs, independent Workers, strict verification, immutable artifacts, leases, restart recovery, and unified security context, see LightDAG.
For browser-use integration with recent browser-use versions, see browser-use Integration.
Roadmap
See the roadmap for delivered milestones and future plans. Inbox, Jobs, and subagents are already available in the opt-in runtime.
🌟 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 LightAgent
Install the package available on PyPI:
pip install lightagent
To install the exact v1.0.0 release from GitHub:
python -m pip install 'git+https://github.com/wanxingai/LightAgent.git@v1.0.0'
For a local v1.0.0 checkout, run the following from its root. Install only the extras you need:
python -m pip install . # base only
python -m pip install '.[mcp]' # keep the existing setup_mcp() configuration
python -m pip install '.[mem0]' # from mem0 import Memory; pass it as memory=
python -m pip install '.[langfuse]' # keep the existing tracetools configuration
Use python -m pip install '.[all]' to install all optional Python dependencies
for MCP, Mem0, Langfuse, LiteLLM, OSS/NOS, and Provider signature verification.
This does not install LightResearch or the Codex CLI.
Skills and their PyYAML dependency are included in the base install. Discovery
still scans skills/ (or the configured skills_directories). Set
auto_discover_skills=False when you do not want to scan.
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)
Use Codex as the Agent Backend
On a POSIX host, install and authenticate the Codex CLI separately and make sure
codex is on PATH. The v1.0.0 adapter supports the CLI's 0.160.x protocol.
LightAgent reuses CLI authentication; do not pass api_key or base_url.
Create a dedicated ./workspace directory before running this example:
from LightAgent import LightAgent
agent = LightAgent(name="codex-assistant", backend="codex")
result = agent.run(
"Summarize the files in this workspace without changing them.",
workspace="./workspace",
execution_timeout=120,
result_format="object",
)
if result.error:
raise RuntimeError(result.error)
print(result.content)
This uses codex exec to run the task, not a model endpoint in LightAgent's
native loop. The adapter does not bridge LightAgent Python tools, memory, or
per-tool guardrails. See workspace execution
for sandbox settings, backend events, and session resumption.
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 tool-heavy streaming tasks, max_tool_iterations can cap repeated tool-call loops independently from max_retry.
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
namespaceto separate tenants or environments. - Use
allowed_sources,allowed_scopes, andallowed_agent_namesto limit retrieved memory. - Use
memory_write_admission,reject_write_patterns,min_write_length, andreject_duplicate_writesto control writes. - Use
enforce_expires_at=Truewhen memory records carry expiration metadata.
8. Langfuse Log Tracking
With the langfuse extra installed, LightAgent can send trace data through the existing
tracetools["TraceToolConfig"] configuration. Built-in trace events do not require Langfuse:
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
LightEvaluator measures output, tool selection, policy events, recovery, latency, usage, and estimated cost against deterministic business cases.
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, andapproval_handler. - Persistence:
JsonLightFlowStorestores 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)andflow.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, PolicyHook
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,
PolicyHook(block_dangerous_tool, phases={"before_tool_call"}, timeout=2.0),
],
)
result = agent.run("Summarize this secret-token safely.", result_format="object", trace=True)
print(result.content)
print(result.trace)
Hooks can target before_run, after_run, on_error, before_model_request, after_model_response, before_tool_call, after_tool_result, before_memory_retrieve, after_memory_retrieve, before_memory_write, after_memory_write, before_memory_promote, after_memory_promote, and on_handoff. Wrap security-sensitive callbacks with PolicyHook(...) to fail closed on exceptions or timeouts while ordinary observability hooks remain failure-isolated. 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 and Runtime Hook Recipes.
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.
Self-learning and delegation evidence become non-injectable memory candidates first; promote them with MemoryPolicy(memory_promotion_admission=...) or agent.promote_memory_candidate(candidate_id) before they can enter future prompts.
When upgrading from v0.9.4, audit legacy internal memory before backfilling promotion_status="promoted" and injectable=True; use require_promotion_for_internal_memory=False only as a temporary compatibility option. See Memory Admission.
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:
- Fork this project: Click the
Forkbutton at the top right corner to copy the project to your GitHub repository. - Create a branch: Create your development branch locally:
git checkout -b feature/YourFeature
- Submit changes: After finishing development, submit your changes:
git commit -m 'Add some feature'
- Push the branch: Push the branch to your remote repository:
git push origin feature/YourFeature
- 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:
- Wanxing AI Email: service@wanxingai.com
- Professor Zhang Liwen Email: zhang.liwen@shufe.edu.cn
- GitHub Issues: https://github.com/wanxingai/LightAgent/issues
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
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
LightAgent🚀 超轻量、可“成长”的智能体框架,现已原生支持Skill
🚀 LightAgent
不再只是“聊天”,而是真正的“完成任务”。LightAgent 把记忆(mem0)、工具(Tools)、思维树(ToT)和多智能体协作融合进一个极简的包中,而你只需 一行代码 就能构建一个能自我学习、按需加载Skill的智能体 —— 就像给大模型装上“招式库”与“执行大脑”。
🔥 为什么开发者会爱上它?
- Skill 原生支持:像管理代码一样管理 AI 能力。把 PDF 处理、代码审查、SOP 流程打包成可复用的 Skill,Agent 按需调用 —— 告别 prompt 堆积,迎接工程化 AI。
- 比 OpenAI Swarm 更简易的多智能体协作:无需复杂编排,轻松构建“Agent 小分队”,并行拆解复杂任务。
- MCP 协议(stdio/SSE/Streamable HTTP):连接外部数据源与工具,按应用配置的权限边界执行。
- 零成本切换底层模型:OpenAI、智谱 ChatGLM、DeepSeek、阶跃星辰、通义千问…… 想用哪个用哪个。
- 开箱即用的 API 服务:标准 OpenAI 流式输出格式,可直接接入主流 Chat 前端(如 NextChat、LobeChat),秒变生产级应用。
- 持久化与动态验证:可选事件溯源 Runtime 提供持久化 Session、异步执行与策略控制;已知步骤使用
LightFlow,动态拆解且成果需要验证的任务使用LightDAG。
🌟 LightAgent = 轻 + 灵 + 可扩展
从个人脚本到企业级 Workflow,它帮你把“聪明的模型”变成“可靠的员工”。
Star 我们,尝试你的第一个 Skill 驱动的 Agent —— 改动几行代码,见证 AI 真正“动手做事”。
新闻
[2026-11-15] LightAgent v1.0.0 已在 GitHub 正式发布:新增可重连的持久执行、统一 Job/Subagent 生命周期、事务化恢复和可选的 Provider 签名验证。
- [2026-10-04] v0.12.0 源码已实现(尚未发布):持久研究服务、目录驱动的 DAG 实验、消息与独立聊天、参考面板、版本评估/采用/回滚。默认普通调用不变;后台模式需显式启用。见 持续研究指南。
- [2026-10-01] LightAgent v0.11.0 正式发布:新增可选的持久化动态 DAG 多 Agent 执行、验证通过后才发布的不可变成果、可恢复租约与 fencing,以及统一且只能收窄权限的
SecurityContext、能力和审批控制。 - [2026-08-15] LightAgent v0.10.0 正式发布:新增统一的事件溯源 Agent Runtime,支持可持久化 Session、异步执行、Capability Registry 与 Policy、Inbox/Goals/Budgets、上下文压缩与恢复、Jobs/子 Agent、标准化 Skills/MCP 适配器和 SQLite FTS5 检索。
- [2026-08-15] LightAgent v0.9.7 正式发布:新增轻量、零依赖的 Connector 契约及离线校验与示例,强化 Python 执行器安全检查,补充可选的 Mem0 Graph 安全验证矩阵,并通过公共 API 兼容性清单为 v1.0 稳定化做准备。
- [2026-07-30] LightAgent v0.9.6 正式发布:新增生产级 Trace 汇总与导出、确定性评测、工具、handoff 和 LightFlow 的可持久化人工审批,以及共享 Graph Memory 的 fail-closed 写入准入与审计控制。
- [2026-07-10] LightAgent v0.9.3 正式发布:补全
after_run、on_error和记忆检索 Hooks 生命周期,新增独立的max_tool_iterations流式工具循环上限并保持max_retry向后兼容,同时完善错误收尾、Trace 和回归测试。 - [2026-06-24] LightAgent v0.9.0 开发版:新增可持久化 LightFlow checkpoint、resume/rerun、审批节点、更清晰的步骤状态和 trace 元数据,同时补充 Guardrails 模板、MemoryPolicy 控制和 SharedMemoryPool 原型。
- [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。
✨ 特性
- 轻量高效 🚀:极简设计,快速部署,适合各种规模的应用场景。(No LangChain, No LlamaIndex)核心框架保持小而清晰,按需使用模型、MCP、记忆和可观测相关依赖,完全开源。
- 记忆支持 🧠:支持为每个用户自定义长期记忆,原生支持
mem0记忆模块,实现对话过程中自动管理用户个性化记忆,让 Agent 更智能。 - 自主学习 📚️:每个agent拥有自主学习能力,并且拥有权限的管理员可以管理每个agent。
- 工具集成 🛠️:支持自定义工具(
Tools)和MCP工具集成,灵活扩展,满足多样化需求。 - 复杂目标 🌳:内置带反思的思维树(ToT)模块,支持复杂任务分解和多步推理,提升任务处理能力。
- 多智能体协同 🤖:比Swarm更简单的多智能体协同,内置的LightSwarm实现意图判断和任务转移功能,能够更智能地处理用户输入,并根据需要将任务转移给其他代理。
- 独立执行 🤖:无人为干预自主完成任务工具调用。
- 多模型支持 🔄:兼容 OpenAI、智谱 ChatGLM、百川大模型、阶跃星辰、DeepSeek、Qwen 系列大模型。
- 可选 Codex Agent 后端:通过
LightAgent(backend="codex")使用本机 Codex CLI 执行工作区任务。默认 LightAgent 后端无需 Codex。 - 流式 API输出 🌊:支持 OpenAI 流格式 API 服务输出,无缝接入主流 Chat 框架,提升用户体验。
- Trace 可观测性 🔎:通过
trace=True可选开启结构化运行轨迹,记录运行开始/结束、模型请求摘要、工具调用、工具结果和错误,同时保持默认字符串返回行为不变。 - 评测框架 📊:
LightEvaluator可对 Agent 或 LightFlow 执行确定性回归用例,检查输出、工具选择、策略事件、恢复能力、延迟、usage 和预估成本。 - 人工审核 👤:
HumanApprovalHook、可持久化审核存储和 LightFlow 审批 checkpoint 支持高风险动作的批准、拒绝、参数编辑、人工响应、批量审核和 trace 反馈。 - Runtime Hooks 🧩:通过有序
hooks=[...]中间件观察、替换或阻断运行、模型、工具、记忆、LightSwarm handoff 和 LightFlow 步骤阶段;安全策略可使用PolicyHook在异常或超时时 fail closed,并将决策写入 trace。 - 事件溯源 Runtime 🧱:可选的持久化 Session、回放、checkpoint、fork、异步入口、分层 Capability Provider、统一 Policy、Inbox、Goals、Budgets、Jobs、子 Agent、上下文压缩和 SQLite FTS5 检索。
- Tools工具生成器 🚀:只需将您的API文档交给[Tools工具生成器],它将自动化地为您打造专属的tools,助您在短短1小时内快速构建数百个个性化的自定义工具,提升效率,释放您的创新潜能。
- agent自我学习 🧠️:每个agent拥有自己的场景记忆能力,拥有从用户的对话中进行自我学习能力。
- 自适应tools机制 🛠️:支持添加无限量tools,在上万个工具中让大模型过滤无关工具后再发送给大模型,可大幅度降低Token消耗。
- 工作流编排 🔁:LightFlow 将多个 Agent 编排为确定性多步骤工作流,支持显式依赖、步骤输出传递、重试、checkpoint、resume/rerun、审批节点、fallback agent 和可追踪执行。
- 共享记忆原型 🧠:SharedMemoryPool 提供带来源元数据和范围检索的追加式内存共享记忆,适合多 Agent 实验。
- Guardrails 模板 🛡️:可复用的输入、工具和输出安全策略模板,可用于隐私拦截、敏感工具确认、高风险参数校验和输出脱敏。
- 动态验证 DAG:可选的 LightDAG 持久化运行期图变更,并发执行独立 Worker,只有应用固定的 Verifier 通过后才发布成果,并通过租约和 fencing 实现安全恢复。
🧭 架构速览
| 层级 | 主要 API | 适用场景 |
|---|---|---|
| 单 Agent 运行时 | LightAgent |
一个 Agent 的模型调用、工具、记忆、流式输出、trace 和 guardrails。 |
| 持久化运行状态 | Session、AgentRuntime |
可回放事件、checkpoint、Inbox、Goals、Budgets、Jobs 和上下文恢复。 |
| 持久执行(v1.0.0) | ExecutionService、ExecutionHandle |
普通可重连任务,不要求研究契约;显式指定宿主后端与安全上下文。 |
| 能力层 | CapabilityRegistry、PolicyEngine |
分层 Provider、权限快照、生命周期、策略与审计。 |
| 统一安全上下文 | SecurityContext、CapabilityGate、ApprovalToken |
身份、只能收窄的权限、授权与绑定具体操作的审批。 |
| 多 Agent 路由 | LightSwarm |
在多个专业 Agent 之间进行角色化委托。 |
| 确定性工作流 | LightFlow |
DAG 工作流、重试、checkpoint、持久化审批、resume 和 rerun。 |
| 动态验证工作流 | LightDAG |
运行期拆解、Verifier、成果、并行 Worker 与恢复。 |
| 工具与集成 | tools、ToolRegistry、MCP |
Python 工具、生成工具、运行时加载工具或 MCP 工具服务。旧任意 Python 执行工具在模型/工具调度中被阻断;使用 safe_expression 或自定义隔离工具。 |
| 记忆边界 | MemoryPolicy、MemoryScope |
租户隔离、来源、可信度、过期和写入准入控制。 |
| 共享记忆原型 | SharedMemoryPool |
多 Agent 共享记忆实验。 |
| 安全控制 | input_guardrails、tool_guardrails、output_guardrails |
隐私拦截、敏感工具确认、高风险参数校验和输出脱敏。 |
| Runtime Hooks | hooks、HookContext、HookDecision |
在生命周期边界实现策略、审计、脱敏、路由和 payload 改写。 |
| 可观测性 | trace=True、summarize_trace、trace exporter |
结构化事件、延迟、usage、重试/错误指标以及 JSONL 或外部导出。 |
| 评测 | LightEvaluator、EvaluationCase |
对输出、工具、策略事件、恢复、延迟和成本执行固定回归用例。 |
| 人工审核 | HumanApprovalHook、ApprovalDecision、review store |
工具/handoff 的 fail-closed 审核、参数编辑、持久化决策和反馈。 |
核心使用模式
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。 |
| 评测 | LightEvaluator().run(agent, cases) |
基于结构化 trace 执行确定性行为检查。 |
| 工具审批 | LightAgent(..., hooks=[HumanApprovalHook(...)]) |
在选定工具或 handoff 执行前要求人工审核。 |
| 工作流 | LightFlow().step(...).run(query) |
用于确定性多步骤执行。 |
| 动态工作流 | LightDAG(...).create_run(...) |
用于 Worker 需要提出子任务且节点只能由已验证成果完成的场景。 |
| 持久化 Session | agent.run(query, session_id="project-42") |
配置持久化 SessionStore 后延续并回放会话。 |
| 异步调用 | await agent.arun(query) |
避免阻塞 asyncio 应用。 |
安全工具默认行为
从 v0.10.1 开始,任意 Python 执行工具默认不会注册。对于受限的算术和
数据表达式,请使用内置的 safe_expression 工具:
from LightAgent import safe_expression
print(safe_expression("45 * 9827"))
旧的 execute_python_code、execute_python_file 和
execute_python_code_stream 不允许通过模型或工具调度器执行,设置
enable_unsafe_python=True 或注册 SandboxProvider 也不会解除阻断。
可信应用代码仍可在自行隔离的环境中直接调用;Agent 执行代码应使用真正委托给
沙箱的自定义工具。详见
Python 执行器安全说明。
评测并审核高风险动作
from LightAgent import EvaluationCase, HumanApprovalHook, LightEvaluator
agent.hooks.hooks.append(HumanApprovalHook(tools={"send_payment"}))
report = LightEvaluator().run(agent, [
EvaluationCase(
name="payment policy",
query="支付 42 号发票",
expected_trace_events=("approval_required",),
forbidden_tools=("delete_account",),
),
])
print(report.to_dict())
待审批请求可写入 JsonReviewStore;使用 ApprovalDecision 完成审核后,通过
approval_id=request.request_id 重新运行。LightFlow 也可通过
flow.approve(...); flow.resume(...) 持久化并恢复步骤审批。
v1.0.0:通用持久执行与恢复
- 可重连任务:
ExecutionService通过宿主注册的后端执行普通任务,不要求研究契约。重启后可用ExecutionHandle重连,查询状态、事件和回执。见离线示例。 - 状态与恢复: Job 和 Subagent 共用生命周期、租约和协作式取消。SQLite 事务保护 Session 状态、消息和预算记账。Subagent 冷重连后需由宿主显式绑定;外部操作结果不明时,由宿主核对后决定是否重试,不自动重放。见 Job/历史迁移指南和离线迁移示例。
- 安全与安装: 可选的 Provider 签名与重授信要求验证发布者签名和宿主显式批准,不替代运行时权限控制。基础安装包含 Skills 和 PyYAML;MCP、Mem0、Langfuse、LiteLLM、OSS/NOS 和验签依赖按需安装。
- 兼容性: 普通
run()和流式调用保持不变。研究契约、评估、版本晋升和调试面板位于独立的 LightResearch 扩展;旧mode="persistent"保持研究语义,需显式调用LightResearch.enable_legacy_api()。见研究迁移指南。
发布说明见 GitHub Release,测试范围见验收记录。核心不提供正式产品 UI,默认 CI 不依赖 LightResearch。
v0.11.0:动态验证工作流
角色化路由使用 LightSwarm,已知步骤的工作流使用 LightFlow;需要 Worker 在执行过程中提出新任务时,选择显式启用的 LightDAG。
SqliteTaskGraphStore保存任务、尝试、图变更、事件和恢复状态;独立 Worker 实例可并发执行。- Worker 只能提交
TaskOutcome.candidate(...)、TaskOutcome.decompose(...)或TaskOutcome.blocked(...)。拆解和不可变成果的发布必须由应用固定的 Verifier 审核。 - 租约和 fencing 在重启恢复时拒绝过期尝试。
SecurityContext、CapabilityGate和绑定具体操作的ApprovalToken明确承载身份、只能收窄的权限与审批信息。
离线 LightDAG 示例
不需要模型、API Key 或网络。示例使用临时 SQLite 数据库和成果目录,退出时清理。
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
需要持久化时,应使用固定的数据库和成果路径,而非临时目录。完整的动态拆解与修复示例及 LightDAG 指南涵盖依赖、集成、重试与恢复。
持久化 Session、异步调用、Capability Provider、Policy、Inbox、Goals、Budgets 和 Jobs 的配置请查看 Runtime 指南。
兼容性与安全边界
- 原有
agent.run(query)、stream=True和user_id继续可用。LightDAG 需要显式启用,不替代 LightFlow。 - v0.11.0 采用单机、本地 SQLite、每次运行一个活动调度器的边界。执行语义为至少一次,外部副作用必须自行保证幂等;本版不包含分布式 Worker、Web UI 或内置代码沙箱。
- 即使设置
enable_unsafe_python=True或注册SandboxProvider,旧的execute_python_code、execute_python_file、execute_python_code_stream也不能由模型或工具调度器执行。应使用safe_expression或真正隔离的自定义工具;可信应用直接调用旧工具不等于获得安全沙箱。 - 记忆仍须配置来源、写入准入和提升策略。框架回归测试不等于真实共享图记忆后端的安全认证,详见记忆安全边界。
已发布版本与当前 main
v0.11.0 于 2026-10-01 发布。工具筛选 JSON、MCP SDK 1.x/2.x 和可选 deed.page 示例的后续修复是在该 tag 之后合入 main 的,已安装的发布包不一定包含。以下命令安装当前 main,不是原始发布 tag:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
更多内容见 Tools Guide、可选 Memcode 适配器、deed.page 示例与公共 API 兼容性清单。这些示例不要求核心运行时接入相应外部服务。
📋 文档
- 常见安装、模型、工具、记忆、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。
- 确定性回归用例、指标和 CI 方案请查看 Evaluation Harness。
- 工具/handoff 审批、LightFlow 持久化审核、批量决策和反馈请查看 Human Review。
- 持久化 Session、Capability Provider、Policy、Inbox、Goals、Budgets、Jobs、上下文压缩、子 Agent、Skills/MCP 更新和 SQLite FTS5 检索,请查看 LightAgent v0.10 Runtime。
- 持久化动态图、独立 Worker、严格验证、不可变成果、租约恢复和统一安全上下文,请查看 LightDAG。
路线图
已交付能力与后续计划请查看路线图。Inbox、Jobs 和子 Agent 已包含在可选 Runtime 中。
🌟 为什么选择 LightAgent?
- 开源免费 💖:完全开源,社区驱动,持续更新,欢迎贡献!
- 易于上手 🎯:文档详尽,示例丰富,快速上手,轻松集成到你的项目中。
- 社区支持 👥:活跃的开发者社区,随时为你提供帮助和解答。
- 高性能 ⚡:优化设计,高效运行,满足高并发场景需求。
🛠️ 快速开始
安装 LightAgent
安装 PyPI 上提供的包:
pip install lightagent
从 GitHub 安装指定的 v1.0.0 版本:
python -m pip install 'git+https://github.com/wanxingai/LightAgent.git@v1.0.0'
从本地 v1.0.0 源码安装时,请在仓库根目录运行,并按需选择 extras:
python -m pip install .
python -m pip install '.[mcp]'
python -m pip install '.[mem0]'
python -m pip install '.[langfuse]'
使用 python -m pip install '.[all]' 可一次装齐 MCP、Mem0、Langfuse、LiteLLM、
OSS/NOS 和 Provider 验签所需的 Python 依赖,不包含独立的 LightResearch 或 Codex CLI。
基础安装已包含 Skills 和 PyYAML。默认仍扫描 skills/,也支持原有的 skills_directories。不需要扫描技能时可设置 auto_discover_skills=False。
MCP 仍使用原有的 setup_mcp(mcp_setting=...) 配置;Mem0 仍使用 from mem0 import Memory,并通过 memory= 接入。已单独安装相应 SDK 的应用无需重复安装。
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)
使用 Codex 作为 Agent 后端
在 POSIX 主机上单独安装并登录 Codex CLI,确保 PATH 中可以找到 codex。
v1.0.0 的适配器支持 CLI 的 0.160.x 协议。LightAgent 复用 CLI 认证,
不需要传入 api_key 或 base_url。运行示例前,请先创建独立的 ./workspace 目录:
from LightAgent import LightAgent
agent = LightAgent(name="codex-assistant", backend="codex")
result = agent.run(
"概述当前工作区的文件,不要修改它们。",
workspace="./workspace",
execution_timeout=120,
result_format="object",
)
if result.error:
raise RuntimeError(result.error)
print(result.content)
这种方式由 codex exec 执行任务,不是为 LightAgent 原生循环更换模型端点。
该适配器不桥接 LightAgent 的 Python 工具、记忆或逐工具 Guardrails。
沙箱设置、后端事件和会话恢复见工作区执行文档。
查看运行 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 配合使用,避免低质量、隐私、过期或无关内容进入长期记忆。反思、委托摘要等内部证据默认先生成不可注入的记忆候选,需要通过 memory_promotion_admission 或 agent.promote_memory_candidate(candidate_id) 显式提升后,才会进入未来 prompt。
从 v0.9.4 升级时,应先审查旧的内部记忆,再为通过审查的记录回填 promotion_status="promoted" 和 injectable=True;require_promotion_for_internal_memory=False 仅用于临时兼容。具体迁移说明请查看 Memory Admission。
8. Trace 与 Langfuse
内置 trace 不依赖 Langfuse。安装 langfuse extra 后,原 tracetools["TraceToolConfig"] 配置保持不变。
9. Agent 测评
LightEvaluator 可围绕确定性业务用例评估输出、工具选择、策略事件、恢复能力、延迟、usage 和预估成本。
10. LightFlow 工作流
LightFlow 是确定性工作流层,适合让任务按已知步骤执行,而不是完全依赖自由形式规划。
- 步骤状态:
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 是围绕 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、promotion status 和 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。以下是贡献步骤:
- Fork 本项目:点击右上角的
Fork按钮,将项目复制到您的 GitHub 仓库。 - 创建分支:在本地创建您的开发分支:
git checkout -b feature/YourFeature
- 提交更改:完成开发后,提交您的更改:
git commit -m 'Add some feature'
- 推送分支:将分支推送到您的远程仓库:
git push origin feature/YourFeature
- 提交 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或上海财经大学统计与数据科学学院张立文教授联系:
- 万行AI邮箱:service@wanxingai.com
- 张立文教授邮箱:zhang.liwen@shufe.edu.cn
- GitHub Issues:https://github.com/wanxingai/LightAgent/issues
我们期待您的反馈,一起让 LightAgent 变得更强大!🚀
LightAgent - 让智能更轻量,让未来更简单。 🌈
LightAgent —— 轻量、灵活、强大的主动式 Agent 框架,助您快速构建智能应用!
Star History
论文
@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🚀(Próximo marco de IA Agentic)
LightAgent es un framework modular de código abierto para Python con Skills reutilizables, herramientas, memoria a largo plazo opcional y modelos y streaming compatibles con OpenAI. LightSwarm gestiona el enrutamiento, LightFlow los pasos conocidos y LightDAG las tareas dinámicas persistentes y verificadas. El runtime opcional basado en eventos añade sesiones persistentes, ejecución asíncrona, políticas y aprobaciones. MCP admite stdio, SSE y Streamable HTTP.
Noticias
[2026-11-15] LightAgent v1.0.0 se publicó oficialmente en GitHub. Añade ejecución con reconexión, un ciclo de vida común para Jobs y subagentes, recuperación transaccional y firmas opcionales de Providers.
- [2026-10-01] LightAgent v0.11.0 publicado: incorpora DAG dinámicos multiagente persistentes y opcionales, artefactos inmutables sujetos a verificación, recuperación mediante leases y fencing, y un
SecurityContextunificado con permisos que solo pueden restringirse y controles de aprobación. - [2026-08-15] LightAgent v0.10.0 publicado: incorpora el runtime basado en eventos con sesiones persistentes, ejecución asíncrona, Capability Registry y Policy, Inbox, Goals, Budgets, Jobs, subagentes, compactación del contexto y búsqueda SQLite FTS5.
- [2026-08-15] LightAgent v0.9.7 publicado: añade un contrato Connector ligero y sin dependencias con validación sin conexión y ejemplos, amplía las comprobaciones de seguridad del ejecutor de Python, incorpora una matriz de seguridad opcional para Mem0 Graph y prepara la estabilización de v1.0 con un inventario de compatibilidad de la API pública.
- [2026-07-30] LightAgent v0.9.6 publicado: añade resúmenes y exportadores de trazas para producción, evaluación determinista, aprobación humana persistente para herramientas, handoffs y LightFlow, además de admisión de escritura fail-closed y auditoría para memoria gráfica compartida.
- [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: Framework Python modular y de código abierto, sin LangChain ni LlamaIndex, con dependencias específicas para modelos, MCP, memoria y trazas.
- Runtime basado en eventos: Sesiones persistentes opcionales, replay, checkpoints, llamadas asíncronas, Capability y Policy, Inbox, Goals, Budgets, Jobs, subagentes, compactación del contexto y búsqueda SQLite FTS5.
- DAG dinámicos verificados: LightDAG persiste cambios del grafo, ejecuta Workers independientes en paralelo y publica artefactos inmutables solo después de la verificación definida por la aplicación.
- 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 herramientasTools] 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. - Evaluación y revisión humana 📊:
LightEvaluatorejecuta regresiones deterministas;HumanApprovalHook, los review stores persistentes y los checkpoints de LightFlow permiten aprobar, rechazar, editar argumentos y registrar feedback.
🧭 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. |
| Estado persistente del runtime | Session, AgentRuntime |
Replay, checkpoints, Inbox, Goals, Budgets, Jobs y recuperación del contexto. |
| Capa de capacidades | CapabilityRegistry, PolicyEngine |
Proveedores con alcance limitado, políticas, ciclo de vida y auditoría. |
| Contexto de seguridad unificado | SecurityContext, CapabilityGate, ApprovalToken |
Identidad, permisos que solo se reducen, autorización y aprobaciones ligadas a una operación. |
| Enrutamiento multiagente | LightSwarm |
Delegación por roles entre agentes especializados. |
| Workflow determinista | LightFlow |
DAG, reintentos, checkpoints, aprobaciones, resume y rerun. |
| Workflow dinámico verificado | LightDAG |
Descomposición dinámica, verificadores, artefactos, Workers paralelos y recuperación. |
| 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. |
| Workflow dinámico | LightDAG(...).create_run(...) |
Proponer tareas y verificar resultados antes de publicarlos. |
| Sesión persistente | agent.run(query, session_id="project-42") |
Requiere configurar un SessionStore persistente para replay y continuación. |
| Asíncrono | await agent.arun(query) |
Entrada no bloqueante para aplicaciones asyncio. |
v1.0.0: Ejecución persistente y recuperación
- Tareas con reconexión:
ExecutionServiceejecuta tareas normales mediante un backend registrado por la aplicación.ExecutionHandlepermite reconectar y consultar su estado después de un reinicio. - Estado y recuperación: Jobs y subagentes comparten un ciclo de vida con cancelación cooperativa. Las transacciones SQLite protegen los mensajes y la contabilidad del presupuesto; si el resultado es incierto, la aplicación debe comprobarlo antes de repetir efectos externos.
- Seguridad e instalación: Los Providers firmados pueden requerir aprobación explícita de la aplicación, sin sustituir las políticas de ejecución. La instalación básica incluye Skills y PyYAML. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS y la verificación de firmas son opcionales.
- Compatibilidad:
run()y el streaming conservan su comportamiento. La investigación es una extensión independiente de LightResearch; el modo anteriormode="persistent"requiere registrarla de forma explícita.
Guía de ejecución · Migración de Jobs e historial · Ejemplo sin conexión
v0.11.0: Workflows dinámicos verificados
Usa LightSwarm para enrutar por roles, LightFlow para pasos conocidos y el LightDAG opcional cuando los Workers deban proponer nuevas tareas durante la ejecución.
SqliteTaskGraphStorepersiste tareas, intentos, cambios del grafo, eventos y estado de recuperación. Las instancias independientes de Worker pueden ejecutarse en paralelo.- Los Workers devuelven
TaskOutcome.candidate(...),TaskOutcome.decompose(...)oTaskOutcome.blocked(...). Solo un Verifier definido por la aplicación puede aprobar una descomposición o publicar artefactos inmutables. - Los leases y el fencing rechazan intentos obsoletos al recuperar una ejecución.
SecurityContext,CapabilityGateyApprovalTokenvinculado a la operación explicitan identidad, permisos que solo pueden restringirse y aprobaciones.
Ejemplo LightDAG sin conexión
No requiere modelo, clave de API ni red. Utiliza una base SQLite y un directorio de artefactos temporales que se eliminan al terminar.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
Para persistencia real, conserva rutas explícitas de base de datos y artefactos en lugar de directorios temporales. El ejemplo completo de descomposición y reparación y la guía LightDAG cubren dependencias, integración, reintentos y recuperación.
La guía del runtime explica sesiones persistentes, llamadas asíncronas, Capability Providers, Policy, Inbox, Goals, Budgets y Jobs.
Compatibilidad y límites de seguridad
agent.run(query),stream=Trueyuser_idsiguen disponibles. LightDAG es opcional y no sustituye a LightFlow.- v0.11.0 se limita a un host, SQLite local y un planificador activo por ejecución. La ejecución es al menos una vez; los efectos externos requieren idempotencia. No incluye Workers distribuidos, interfaz web ni sandbox de código integrado.
- Los antiguos
execute_python_code,execute_python_fileyexecute_python_code_streamestán bloqueados en la ejecución de herramientas del modelo, incluso conenable_unsafe_python=Trueo unSandboxProviderregistrado. Usasafe_expressiono una herramienta realmente aislada; la llamada directa a estas utilidades no es un sandbox de seguridad. - Siguen siendo necesarias las políticas de procedencia, admisión y promoción de memoria. Las pruebas del framework no certifican un backend real de memoria gráfica compartida; consulta seguridad de memoria.
Versión publicada y main actual
v0.11.0 se publicó el 2026-10-01. Las correcciones posteriores de JSON de selección de herramientas, MCP SDK 1.x/2.x y el ejemplo opcional deed.page se integraron después de ese tag y pueden no estar en el paquete publicado. El siguiente comando instala main actual, no el tag original:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Consulta Tools Guide, el adaptador Memcode opcional, el ejemplo deed.page y el inventario de compatibilidad pública. Estos servicios externos no son un requisito del runtime principal.
📋 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.
- Para regresiones deterministas, consulta Evaluation Harness.
- Para aprobación de herramientas/handoffs, revisión persistente y feedback, consulta Human Review.
Hoja de ruta
Consulta la hoja de ruta para los hitos entregados y los planes futuros. Inbox, Jobs y subagentes ya están disponibles en el runtime opcional.
🌟 ¿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
LightEvaluator mide salida, selección de herramientas, eventos de política, recuperación, latencia, usage y coste estimado.
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:
- Fork este proyecto: Haz clic en el botón
Forken la parte superior derecha para copiar el proyecto a tu repositorio de GitHub. - Crear una rama: Crea tu rama de desarrollo local:
git checkout -b feature/TuCaracterística
- Enviar cambios: Después de completar el desarrollo, envía tus cambios:
git commit -m 'Agregar alguna característica'
- Enviar la rama: Envía tu rama a tu repositorio remoto:
git push origin feature/TuCaracterística
- 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:
- Correo electrónico: service@wanxingai.com
- Issues en GitHub: https://github.com/wanxingai/LightAgent/issues
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 : framework d'agents IA de nouvelle génération
LightAgent est un framework Python modulaire et open source avec des Skills réutilisables, des outils, une mémoire à long terme optionnelle, ainsi que des modèles et du streaming compatibles OpenAI. LightSwarm gère le routage, LightFlow les étapes connues et LightDAG les tâches dynamiques persistantes et vérifiées. Le runtime optionnel fondé sur les événements ajoute sessions persistantes, exécution asynchrone, politiques et approbations. MCP prend en charge stdio, SSE et Streamable HTTP.
Actualités
[2026-11-15] LightAgent v1.0.0 est officiellement disponible sur GitHub. Cette version ajoute l'exécution avec reconnexion, un cycle de vie commun aux Jobs et sous-agents, la reprise transactionnelle et la signature facultative des Providers.
- [2026-10-01] LightAgent v0.11.0 publié : ajoute des DAG dynamiques multi-agents persistants et optionnels, des artefacts immuables soumis à vérification, une reprise avec baux et fencing, et un
SecurityContextunifié avec permissions uniquement réductibles et contrôles d'approbation. - [2026-08-15] LightAgent v0.10.0 publié : introduit le runtime fondé sur les événements avec sessions persistantes, exécution asynchrone, Capability Registry et Policy, Inbox, Goals, Budgets, Jobs, sous-agents, compactage du contexte et recherche SQLite FTS5.
- [2026-08-15] LightAgent v0.9.7 publié : ajoute un contrat Connector léger et sans dépendance avec validation hors ligne et exemples, renforce les contrôles de sécurité de l'exécuteur Python, introduit une matrice de sécurité Mem0 Graph optionnelle et prépare la stabilisation de v1.0 avec un inventaire de compatibilité de l'API publique.
- [2026-07-30] LightAgent v0.9.6 publié : ajoute des résumés et exportateurs de traces pour la production, une évaluation déterministe, une approbation humaine persistante pour les outils, les handoffs et LightFlow, ainsi qu'une admission d'écriture fail-closed et des contrôles d'audit pour la mémoire graphique partagée.
- [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.
✨ Fonctionnalités
- Léger et efficace : framework Python modulaire et open source, sans LangChain ni LlamaIndex, avec des dépendances ciblées pour les modèles, MCP, la mémoire et les traces.
- Runtime fondé sur les événements : sessions persistantes optionnelles, replay, checkpoints, appels asynchrones, Capability et Policy, Inbox, Goals, Budgets, Jobs, sous-agents, compactage du contexte et recherche SQLite FTS5.
- DAG dynamiques vérifiés : LightDAG persiste les changements du graphe, exécute les Workers indépendants en parallèle et ne publie les artefacts immuables qu'après vérification définie par l'application.
- Mémoire : mémoire à long terme personnalisable par utilisateur, avec intégration optionnelle de
mem0et contrôle par MemoryPolicy. - Apprentissage : chaque agent peut exploiter la mémoire de ses échanges, sous le contrôle d'administrateurs autorisés.
- Intégration d'outils : outils Python personnalisés, génération d'outils et intégration MCP.
- Objectifs complexes : le module Tree of Thought (
ToT) prend en charge la décomposition et le raisonnement en plusieurs étapes. - Collaboration multi-agent : LightSwarm reconnaît les intentions et délègue aux agents spécialisés.
- Exécution autonome : tâches et outils s'exécutent dans les limites des politiques et approbations configurées.
- Modèles multiples : fournisseurs compatibles OpenAI, dont OpenAI, DeepSeek, Qwen, Zhipu ChatGLM et les serveurs locaux compatibles.
- API en streaming : réponses au format OpenAI pour l'intégration aux interfaces de conversation.
- Génération d'outils : création d'outils à partir de la documentation d'une API ; voir le guide des outils.
- Mémoire contextuelle : conservation des informations pertinentes issues des conversations, selon la politique d'admission.
- Sélection adaptative des outils : sélection d'un sous-ensemble pertinent avant l'envoi au modèle afin de limiter la taille du contexte.
- 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. - Évaluation et revue humaine 📊 :
LightEvaluatorexécute des régressions déterministes ;HumanApprovalHook, les review stores persistants et les checkpoints LightFlow permettent approbation, rejet, édition des arguments et feedback.
🧭 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. |
| État persistant du runtime | Session, AgentRuntime |
Replay, checkpoints, Inbox, Goals, Budgets, Jobs et restauration du contexte. |
| Couche de capacités | CapabilityRegistry, PolicyEngine |
Fournisseurs à portée limitée, politiques, cycle de vie et audit. |
| Contexte de sécurité unifié | SecurityContext, CapabilityGate, ApprovalToken |
Identité, permissions uniquement réductibles, autorisation et approbations liées à une opération. |
| 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. |
| Workflow dynamique vérifié | LightDAG |
Décomposition dynamique, vérificateurs, artefacts, Workers parallèles et reprise. |
| 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. |
| Workflow dynamique | LightDAG(...).create_run(...) |
Proposer des tâches et vérifier les résultats avant publication. |
| Session persistante | agent.run(query, session_id="project-42") |
Nécessite un SessionStore persistant configuré pour le replay et la reprise. |
| Asynchrone | await agent.arun(query) |
Point d'entrée non bloquant pour les applications asyncio. |
v1.0.0 : Exécution persistante et reprise
- Tâches avec reconnexion :
ExecutionServiceexécute des tâches ordinaires via un backend enregistré par l'application hôte.ExecutionHandlepermet de se reconnecter aux tâches et de consulter leur état après un redémarrage. - État et reprise : Jobs et sous-agents partagent un cycle de vie avec annulation coopérative. Les transactions SQLite protègent les messages et les opérations budgétaires ; une issue incertaine doit être vérifiée par l'hôte avant toute répétition d'un effet externe.
- Sécurité et installation : Les Providers signés peuvent exiger l'approbation explicite de l'hôte, sans remplacer les politiques d'exécution. L'installation de base inclut les Skills et PyYAML. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS et la vérification des signatures sont facultatifs.
- Compatibilité :
run()et le streaming conservent leur comportement. La recherche relève de l'extension séparée LightResearch ; l'ancienmode="persistent"nécessite son enregistrement explicite.
Guide d'exécution · Migration des Jobs et de l'historique · Exemple hors ligne
v0.11.0 : Workflows dynamiques vérifiés
Utilisez LightSwarm pour le routage par rôle, LightFlow pour des étapes connues et le LightDAG optionnel lorsque les Workers doivent proposer de nouvelles tâches pendant l'exécution.
SqliteTaskGraphStoreconserve tâches, tentatives, modifications du graphe, événements et état de reprise. Des instances indépendantes de Worker peuvent s'exécuter en parallèle.- Les Workers renvoient
TaskOutcome.candidate(...),TaskOutcome.decompose(...)ouTaskOutcome.blocked(...). Seul un Verifier fixé par l'application peut accepter une décomposition ou publier des artefacts immuables. - Les baux et le fencing rejettent les tentatives périmées lors d'une reprise.
SecurityContext,CapabilityGateet lesApprovalTokenliés à une opération rendent explicites identité, permissions uniquement réductibles et approbations.
Exemple LightDAG hors ligne
Aucun modèle, clé API ou réseau n'est nécessaire. L'exemple utilise une base SQLite et un répertoire d'artefacts temporaires, supprimés à la fin.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
Pour conserver les données, utilisez des chemins explicites et durables plutôt que des répertoires temporaires. L'exemple complet de décomposition et réparation et le guide LightDAG couvrent dépendances, intégration, nouvelles tentatives et reprise.
Le guide du runtime explique les sessions persistantes, appels asynchrones, Capability Providers, Policy, Inbox, Goals, Budgets et Jobs.
Compatibilité et limites de sécurité
agent.run(query),stream=Trueetuser_idrestent disponibles. LightDAG est optionnel et ne remplace pas LightFlow.- v0.11.0 fonctionne sur un seul hôte, avec SQLite local et un ordonnanceur actif par exécution. L'exécution est au moins une fois ; les effets externes exigent l'idempotence. Workers distribués, interface web et sandbox de code intégrée sont hors périmètre.
- Les anciens
execute_python_code,execute_python_fileetexecute_python_code_streamsont bloqués dans l'exécution des outils du modèle, même avecenable_unsafe_python=Trueou unSandboxProviderenregistré. Utilisezsafe_expressionou un outil réellement isolé ; l'appel direct à ces utilitaires ne constitue pas une sandbox de sécurité. - Les politiques de provenance, d'admission et de promotion mémoire restent nécessaires. Les tests du framework ne certifient pas un backend réel de mémoire graphique partagée ; voir la sécurité mémoire.
Version publiée et branche main actuelle
v0.11.0 a été publiée le 2026-10-01. Les corrections ultérieures du JSON de sélection d'outils, des SDK MCP 1.x/2.x et l'exemple optionnel deed.page ont été intégrés après ce tag et peuvent manquer dans le paquet publié. La commande suivante installe main actuel, pas le tag initial :
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Consultez Tools Guide, l'adaptateur Memcode optionnel, l'exemple deed.page et l'inventaire de compatibilité publique. Ces services externes ne sont pas requis par le runtime principal.
📋 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.
- Pour les régressions déterministes, consultez Evaluation Harness.
- Pour l'approbation outil/handoff, la revue persistante et le feedback, consultez Human Review.
Feuille de route
Consultez la feuille de route pour les étapes livrées et les projets futurs. Inbox, Jobs et sous-agents sont déjà disponibles dans le runtime optionnel.
🌟 Pourquoi choisir LightAgent ?
- Libre et ouvert : développement communautaire et contributions bienvenues.
- Prise en main : documentation et exemples pour intégrer progressivement le framework.
- Communauté : échanges, questions et suivi des problèmes sur GitHub.
- Concurrence : points d'entrée asynchrones et Workers indépendants pour les tâches parallélisables.
🛠️ Démarrage rapide
Installer la dernière version de LightAgent
pip install lightagent
(Optionnel) Installez le paquet Mem0 avec pip :
pip install mem0ai
Vous pouvez aussi utiliser le service hébergé Mem0.
Premier exemple
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"))
Définir le rôle de l'agent avec un message système
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)
Exemple d'utilisation d'un outil
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)
Plusieurs outils personnalisés peuvent être enregistrés.
Exemple de liste : tools = [search_news, get_weather, get_stock_realtime_data, get_stock_kline_data].
Fonctionnalités en détail
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
LightEvaluator mesure sortie, choix d’outils, événements de politique, reprise, latence, usage et coût estimé.
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.
Modèles pris en charge
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.
Pour les paramètres des fournisseurs, les URL de base, les modèles locaux et le dépannage, consultez la configuration des modèles.
Cas d'utilisation
- Service client : conversations multi-tours et intégration d'outils métier.
- Analyse de données : décomposition des tâches et collaboration entre agents.
- Automatisation : création et intégration d'outils personnalisés.
- Assistance pédagogique : expériences personnalisées avec mémoire et réponses en streaming.
🛠️ Contribuer
Les contributions au code, à la documentation, aux tests et les retours sont bienvenus. Signalez les problèmes ou proposez vos améliorations dans une issue ou une pull request :
- Créer un fork : copiez le projet vers votre compte avec le bouton
Fork. - Créer une branche : créez une branche locale pour vos modifications :
git checkout -b feature/YourFeature
- Enregistrer les modifications : après le développement, créez un commit :
git commit -m 'Add some feature'
- Publier la branche : envoyez-la vers votre fork :
git push origin feature/YourFeature
- Ouvrir une pull request : décrivez les changements et les tests sur GitHub.
Nous examinerons votre contribution dès que possible. Merci de votre soutien.
🙏 Remerciements
LightAgent s'appuie sur les idées et les contributions des projets open source suivants :
- mem0 : module de mémoire et gestion du contexte.
- Swarm : principes de collaboration multi-agent.
- ChatGLM3 : modèles et inspiration.
- Qwen : modèles de langage.
- DeepSeek-V3 : modèles de langage.
- StepFun : modèles de langage.
📄 Licence
LightAgent est distribué sous licence Apache 2.0. Vous pouvez l'utiliser, le modifier et le redistribuer dans le respect de cette licence.
📬 Nous contacter
Pour toute question ou suggestion :
- Courriel : service@wanxingai.com
- GitHub Issues: https://github.com/wanxingai/LightAgent/issues
Vos retours contribuent à améliorer LightAgent.
LightAgent - Une intelligence plus légère, un avenir plus simple.
LightAgent : un framework d'agents léger, flexible et modulaire pour construire des applications intelligentes.
LightAgent🚀(Nächste Generation des Agentic AI-Frameworks)
LightAgent ist ein modulares Open-Source-Framework für Python mit wiederverwendbaren Skills, Werkzeugen, optionalem Langzeitspeicher und OpenAI-kompatiblen Modellen und Streaming-Antworten. LightSwarm übernimmt das Routing, LightFlow feste Abläufe und LightDAG persistente, dynamisch verifizierte Aufgaben. Die optionale ereignisbasierte Runtime bietet dauerhafte Sessions, asynchrone Ausführung sowie Richtlinien und Freigaben. MCP wird über stdio, SSE und Streamable HTTP angebunden.
Neuigkeiten
[2026-11-15] LightAgent v1.0.0 wurde offiziell auf GitHub veröffentlicht. Neu sind wiederverbindbare Ausführung, ein gemeinsamer Job-/Subagent-Lebenszyklus, transaktionale Wiederherstellung und optionale Provider-Signaturen.
- [2026-10-01] LightAgent v0.11.0 veröffentlicht: ergänzt opt-in persistente dynamische Multi-Agenten-DAGs, verifikationsgebundene unveränderliche Artefakte, Wiederanlauf mit Leases und Fencing sowie einen einheitlichen
SecurityContextmit ausschließlich einschränkbarer Berechtigung und Freigabekontrollen. - [2026-08-15] LightAgent v0.10.0 veröffentlicht: führt die ereignisbasierte Agent Runtime mit persistenten Sessions, asynchroner Ausführung, Capability Registry und Policy, Inbox, Goals, Budgets, Jobs, Subagenten, Kontextkomprimierung und SQLite-FTS5-Suche ein.
- [2026-08-15] LightAgent v0.9.7 veröffentlicht: ergänzt einen leichtgewichtigen, abhängigkeitsfreien Connector-Vertrag mit Offline-Validierung und Beispielen, erweitert die Sicherheitsprüfungen des Python-Executors, fügt eine optionale Mem0-Graph-Sicherheitsmatrix hinzu und bereitet mit einer öffentlichen API-Kompatibilitätsübersicht die Stabilisierung von v1.0 vor.
- [2026-07-30] LightAgent v0.9.6 veröffentlicht: ergänzt produktionsreife Trace-Zusammenfassungen und Exporte, deterministische Evaluation, dauerhafte menschliche Freigaben für Tools, Handoffs und LightFlow sowie ausfallsichere Schreibfreigaben und Audit-Kontrollen für gemeinsam genutzten Graph-Speicher.
- [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: Modulares, vollständig offenes Python-Framework ohne LangChain oder LlamaIndex, mit gezielten Abhängigkeiten für Modelle, MCP, Speicher und Tracing.
- Ereignisbasierte Runtime: Optionale persistente Sessions, Replay, Checkpoints, asynchrone Aufrufe, Capability- und Policy-Kontrollen, Inbox, Goals, Budgets, Jobs, Subagenten, Kontextkomprimierung und SQLite-FTS5-Suche.
- Dynamische verifizierte DAGs: LightDAG speichert Graphänderungen, führt unabhängige Worker parallel aus und veröffentlicht unveränderliche Artefakte erst nach anwendungsseitiger Verifikation.
- 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. - Evaluation und menschliche Freigabe 📊:
LightEvaluatorführt deterministische Regressionen aus;HumanApprovalHook, persistente Review-Stores und LightFlow-Checkpoints unterstützen Freigabe, Ablehnung, Argumentänderung und Feedback.
🧭 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. |
| Persistenter Runtime-Zustand | Session, AgentRuntime |
Replay, Checkpoints, Inbox, Goals, Budgets, Jobs und Kontextwiederherstellung. |
| Capability-Schicht | CapabilityRegistry, PolicyEngine |
Begrenzte Provider, Richtlinien, Lebenszyklus und Audit. |
| Einheitlicher Sicherheitskontext | SecurityContext, CapabilityGate, ApprovalToken |
Identität, nur einschränkbare Rechte, Autorisierung und operationsgebundene Freigaben. |
| Multi-Agent-Routing | LightSwarm |
Rollenbasierte Delegation zwischen spezialisierten Agenten. |
| Deterministischer Workflow | LightFlow |
DAG, Wiederholungen, Checkpoints, Freigaben, Resume und Rerun. |
| Dynamischer verifizierter Workflow | LightDAG |
Dynamische Zerlegung, Verifier, Artefakte, parallele Worker und Wiederherstellung. |
| 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. |
| Dynamischer Workflow | LightDAG(...).create_run(...) |
Aufgaben dynamisch vorschlagen und Ergebnisse vor Veröffentlichung prüfen. |
| Persistente Session | agent.run(query, session_id="project-42") |
Erfordert einen konfigurierten persistenten SessionStore für Replay und Fortsetzung. |
| Asynchron | await agent.arun(query) |
Nicht blockierender Einstieg für asyncio-Anwendungen. |
v1.0.0: Persistente Ausführung und Wiederherstellung
- Aufgaben wieder aufnehmen:
ExecutionServicestartet gewöhnliche Aufgaben über einen vom Host registrierten Backend-Adapter. MitExecutionHandlelassen sich laufende Aufgaben nach einem Neustart wieder verbinden und abfragen. - Zustand und Wiederherstellung: Jobs und Subagenten nutzen einen gemeinsamen Lebenszyklus mit kooperativem Abbruch. SQLite-Transaktionen sichern Nachrichten und Budgetbuchungen; bei unklarem Ausgang ist eine Prüfung durch den Host nötig, bevor externe Aktionen wiederholt werden.
- Sicherheit und Installation: Signierte Providers können eine ausdrückliche Freigabe durch den Host verlangen; Laufzeitrichtlinien bleiben wirksam. Skills und PyYAML gehören zur Basisinstallation. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS und Signaturprüfung sind optional.
- Kompatibilität: Normale
run()- und Streaming-Aufrufe bleiben unverändert. Forschung ist eine separate LightResearch-Erweiterung; der alte Modusmode="persistent"braucht eine ausdrückliche Registrierung.
Ausführungsleitfaden · Job- und Verlaufsmigration · Offline-Beispiel
v0.11.0: Verifizierte dynamische Workflows
Verwenden Sie LightSwarm für rollenbasiertes Routing, LightFlow für bekannte Abläufe und das optionale LightDAG, wenn Worker während der Ausführung neue Aufgaben vorschlagen sollen.
SqliteTaskGraphStorespeichert Aufgaben, Versuche, Graphänderungen, Ereignisse und Wiederherstellungszustand. Unabhängige Worker-Instanzen können parallel laufen.- Worker liefern
TaskOutcome.candidate(...),TaskOutcome.decompose(...)oderTaskOutcome.blocked(...). Nur ein von der Anwendung festgelegter Verifier darf Zerlegungen genehmigen oder unveränderliche Artefakte veröffentlichen. - Leases und Fencing verhindern nach einem Neustart die Veröffentlichung veralteter Versuche.
SecurityContext,CapabilityGateund operationsgebundeneApprovalTokenmachen Identität, ausschließlich einschränkbare Rechte und Freigaben explizit.
LightDAG-Beispiel ohne Netzwerk
Das Beispiel benötigt weder Modell noch API-Schlüssel oder Netzwerk. Es verwendet eine temporäre SQLite-Datenbank und ein Artefaktverzeichnis und entfernt sie anschließend.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
Für dauerhaften Betrieb feste Datenbank- und Artefaktpfade statt temporärer Verzeichnisse verwenden. Das vollständige Beispiel für Zerlegung und Reparatur und der LightDAG-Leitfaden behandeln Abhängigkeiten, Integration, Wiederholungen und Wiederherstellung.
Dauerhafte Sessions, asynchrone Aufrufe, Capability Provider, Policy, Inbox, Goals, Budgets und Jobs beschreibt der Runtime-Leitfaden.
Kompatibilität und Sicherheitsgrenzen
agent.run(query),stream=Trueunduser_idbleiben verfügbar. LightDAG ist opt-in und ersetzt LightFlow nicht.- v0.11.0 läuft auf einem Host mit lokaler SQLite-Datenbank und einem aktiven Scheduler je Lauf. Die Ausführung erfolgt mindestens einmal; externe Seiteneffekte benötigen Idempotenz. Verteilte Worker, Web-UI und eine eingebaute Code-Sandbox sind nicht enthalten.
- Die alten Tools
execute_python_code,execute_python_fileundexecute_python_code_streamsind für Modell-/Tool-Dispatch gesperrt, auch mitenable_unsafe_python=Trueoder registriertemSandboxProvider. Nutzen Siesafe_expressionoder ein tatsächlich isoliertes eigenes Tool; direkte Utility-Aufrufe sind keine Sicherheits-Sandbox. - Herkunft, Schreibzulassung und explizite Freigabe interner Erinnerungen bleiben erforderlich. Framework-Tests zertifizieren keinen realen gemeinsamen Graphspeicher; siehe Speichersicherheit.
Release und aktueller main-Zweig
v0.11.0 wurde am 2026-10-01 veröffentlicht. Spätere Korrekturen für Tool-Auswahl-JSON, MCP SDK 1.x/2.x und das optionale deed.page-Beispiel wurden erst danach in main integriert und sind nicht zwangsläufig im installierten Release enthalten. Folgender Befehl installiert den aktuellen main-Zweig, nicht den ursprünglichen Release-Tag:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Weitere Informationen: Tools Guide, optionaler Memcode-Adapter, deed.page-Beispiel und öffentliche API-Kompatibilität. Die externen Dienste dieser Beispiele sind keine Voraussetzung für die Kern-Runtime.
📋 Dokumentation
- Für Installation, Modelle, Tools, Speicher, MCP, Skills, Streaming und LightSwarm siehe FAQ.
- Für deterministische Workflows, Checkpoints, Resume/Rerun, Freigaben, Fallback-Agenten und Schrittstatus siehe LightFlow.
- Für eigene Tools, ToolRegistry, ToolLoader, AsyncToolDispatcher und MCP siehe Tools Guide.
- Für gemeinsamen Langzeitspeicher oder Graphspeicher siehe Memory Security Guidance.
- Für SharedMemoryPool siehe SharedMemoryPool.
- Für Speicher-Schreibzulassung und Ablaufregeln siehe Memory Admission And Mutation Controls.
- Für Eingabe-, Werkzeug- und Ausgabesicherheit siehe Guardrails.
- Für Runtime-Middleware zum Beobachten, Ersetzen oder Blockieren von Payloads siehe Runtime Hooks.
- Für OpenRouter, lokale Modelle und OpenAI-kompatible Anbieter siehe Model Provider Configuration.
- Für strukturierte Traces siehe Trace Observability.
- Für deterministische Regressionen siehe Evaluation Harness.
- Für Tool/Handoff-Freigaben, persistente Reviews und Feedback siehe Human Review.
Roadmap
Bereits gelieferte Funktionen und weitere Pläne stehen in der Roadmap. Inbox, Jobs und Subagenten sind in der optionalen Runtime bereits verfügbar.
🌟 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
LightEvaluator misst Verhalten anhand von Ausgabe, Tools, Policy-Ereignissen, Recovery, Latenz und Kosten.
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:
- Forken Sie dieses Projekt: Klicken Sie auf die Schaltfläche
Forkin der oberen rechten Ecke, um das Projekt in Ihr GitHub-Repository zu kopieren. - Erstellen Sie einen Branch: Erstellen Sie lokal Ihren Entwicklungsbranch:
git checkout -b feature/YourFeature
- Änderungen einreichen: Nach Abschluss der Entwicklung Ihre Änderungen einreichen:
git commit -m 'Fügen Sie eine Funktion hinzu'
- Branch pushen: Pushen Sie den Branch in Ihr Remote-Repository:
git push origin feature/YourFeature
- 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:
- E-Mail: service@wanxingai.com
- GitHub Issues:https://github.com/wanxingai/LightAgent/issues
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🚀(次世代エージェンティックAIフレームワーク)
LightAgent は、再利用可能な Skills、ツール、任意の長期メモリ、OpenAI 互換モデルとストリーミングに対応した、モジュール型のオープンソース Python フレームワークです。LightSwarm はルーティング、LightFlow は既知の手順、LightDAG は永続化された動的・検証付きタスクを担当します。任意で有効化するイベントソーシング Runtime は、永続 Session、非同期実行、ポリシーと承認を提供します。MCP は stdio、SSE、Streamable HTTP に対応します。
ニュース
[2026-11-15] LightAgent v1.0.0 を GitHub で正式にリリースしました。再接続可能な実行、Job とサブエージェントの統一ライフサイクル、トランザクションによる復旧、オプションの Provider 署名検証を追加しました。
- [2026-10-01] LightAgent v0.11.0 リリース:オプトインの永続的な動的マルチエージェント DAG、検証後にのみ公開する不変成果物、リースと fencing による再開、一方向に権限を制限する統一
SecurityContextと承認制御を追加しました。 - [2026-08-15] LightAgent v0.10.0 リリース:永続 Session、非同期実行、Capability Registry と Policy、Inbox、Goals、Budgets、Jobs、サブエージェント、コンテキスト圧縮、SQLite FTS5 検索を備えたイベントベースの Agent Runtime を導入しました。
- [2026-08-15] LightAgent v0.9.7 リリース:オフライン検証とサンプルを備えた軽量かつ依存関係のない Connector 契約、Python executor のセキュリティ検査、オプトインの Mem0 Graph セキュリティ検証マトリクスを追加し、公開 API 互換性一覧によって v1.0 の安定化に備えました。
- [2026-07-30] LightAgent v0.9.6 リリース:本番向け Trace 要約とエクスポーター、決定的評価、ツール・handoff・LightFlow の永続的な人間承認、共有 Graph Memory の fail-closed 書き込み承認と監査制御を追加。
- [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 を参照してください。
✨ 特徴
- 軽量で効率的:LangChain や LlamaIndex を必要としない、モジュール型のオープンソース Python フレームワークです。モデル、MCP、メモリ、トレースには用途別の依存ライブラリを使用します。
- イベントソーシング Runtime:任意の永続 Session、リプレイ、checkpoint、非同期呼び出し、Capability と Policy、Inbox、Goals、Budgets、Jobs、サブ Agent、コンテキスト圧縮、SQLite FTS5 検索。
- 動的・検証付き DAG:LightDAG はグラフ変更を永続化し、独立した Worker を並列実行して、アプリケーション側の検証後にのみ不変の成果物を公開します。
- メモリサポート 🧠:各ユーザーのためにカスタマイズ可能な長期メモリをサポートし、対話の過程でユーザーの個性に応じたメモリを自動管理することにより、エージェントをより賢くします。
- 自主学習 📚️:各エージェントは自ら学ぶ能力を持ち、アクセス権を持つ管理者はそれぞれのエージェントを管理できます。
- ツール統合 🛠️:カスタマイズ可能なツール(
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 ステップの各フェーズを監視、置換、ブロックできます。 - 評価と人間レビュー 📊:
LightEvaluatorは決定的な回帰評価を実行し、HumanApprovalHook、永続 review store、LightFlow checkpoint は承認、拒否、引数編集、feedback を支援します。
🧭 アーキテクチャ概要
| レイヤー | 主な API | 用途 |
|---|---|---|
| 単一 Agent 実行 | LightAgent |
モデル呼び出し、ツール、メモリ、ストリーミング、trace、guardrails。 |
| 永続 Runtime 状態 | Session、AgentRuntime |
リプレイ、checkpoint、Inbox、Goals、Budgets、Jobs、コンテキスト復元。 |
| 能力レイヤー | CapabilityRegistry、PolicyEngine |
範囲を限定した Provider、ポリシー、ライフサイクル、監査。 |
| 統一セキュリティコンテキスト | SecurityContext、CapabilityGate、ApprovalToken |
ID、縮小のみ可能な権限、認可、操作に結び付いた承認。 |
| マルチ Agent ルーティング | LightSwarm |
専門 Agent 間の役割ベース委譲。 |
| 決定的 workflow | LightFlow |
DAG、リトライ、checkpoint、承認、resume、rerun。 |
| 動的・検証付きワークフロー | LightDAG |
動的分解、Verifier、成果物、Worker の並列実行、復元。 |
| ツールと統合 | 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) |
決定的な多段階実行に使います。 |
| 動的ワークフロー | LightDAG(...).create_run(...) |
タスクを動的に提案し、公開前に結果を検証します。 |
| 永続 Session | agent.run(query, session_id="project-42") |
継続とリプレイには永続 SessionStore の設定が必要です。 |
| 非同期 | await agent.arun(query) |
asyncio アプリケーション向けの非ブロッキング入口。 |
v1.0.0: 永続実行と復旧
- 再接続可能なタスク:
ExecutionServiceはホストが登録したバックエンドで通常タスクを実行します。再起動後はExecutionHandleで再接続し、状態を確認できます。 - 状態管理と復旧: Job とサブエージェントは協調的なキャンセルを含む共通のライフサイクルを使用します。メッセージと予算の記録は SQLite のトランザクションで管理し、結果が不明な場合はホストが確認するまで外部操作を自動再実行しません。
- 安全性とインストール: 署名付き Provider ではランタイムのポリシーに加えて、ホストによる明示的な承認を要求できます。基本インストールには Skills と PyYAML が含まれます。MCP、Mem0、Langfuse、LiteLLM、OSS/NOS、署名検証はオプションです。
- 互換性: 通常の
run()とストリーミングは従来どおりです。研究機能は独立した LightResearch 拡張に移り、従来のmode="persistent"には明示的な登録が必要です。
実行ガイド · Job と履歴の移行 · オフライン例
v0.11.0: 検証付き動的ワークフロー
役割ベースの委譲には LightSwarm、既知の手順には LightFlow、実行中に Worker が新しいタスクを提案する場合にはオプトインの LightDAG を使います。
SqliteTaskGraphStoreはタスク、試行、グラフ変更、イベント、復旧状態を永続化します。独立した Worker インスタンスを並行実行できます。- Worker は
TaskOutcome.candidate(...)、TaskOutcome.decompose(...)、TaskOutcome.blocked(...)を返します。分解の承認と不変成果物の公開は、アプリケーションが固定した Verifier のみが行います。 - リースと fencing は再開時に古い試行を拒否します。
SecurityContext、CapabilityGate、操作に紐づくApprovalTokenにより、識別情報、縮小のみ可能な権限、承認を明示します。
オフライン LightDAG サンプル
モデル、API キー、ネットワークは不要です。一時 SQLite データベースと成果物ディレクトリを使い、終了時に削除します。
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
永続利用では一時ディレクトリではなく明示的な保存先を指定してください。動的分解と修復の完全なサンプルと LightDAG ガイドで依存関係、統合、再試行、復旧を説明しています。
永続 Session、非同期呼び出し、Capability Provider、Policy、Inbox、Goals、Budgets、Jobs の設定は Runtime ガイドを参照してください。
互換性とセキュリティ境界
agent.run(query)、stream=True、user_idは引き続き利用できます。LightDAG は明示的に有効化する機能で、LightFlow を置き換えません。- v0.11.0 は単一ホスト、ローカル SQLite、実行ごとに一つのアクティブなスケジューラーを前提とします。実行は at-least-once で、外部副作用には冪等性が必要です。分散 Worker、Web UI、組み込みコードサンドボックスは含みません。
- 旧
execute_python_code、execute_python_file、execute_python_code_streamは、enable_unsafe_python=Trueや登録済みSandboxProviderがあってもモデルのツール実行ではブロックされます。safe_expressionまたは実際に隔離されたカスタムツールを使ってください。ユーティリティの直接呼び出しは安全なサンドボックスではありません。 - メモリの出所、書き込み許可、昇格ポリシーは引き続き必要です。フレームワークのテストだけで実際の共有グラフメモリ backend の安全性は認証できません。メモリの安全境界を参照してください。
公開リリースと現在の main
v0.11.0 は 2026-10-01 に公開されました。ツール選択 JSON、MCP SDK 1.x/2.x、オプションの deed.page サンプルに関する後続変更は、その tag より後に main へ統合されており、公開済みパッケージに含まれるとは限りません。次のコマンドは元の tag ではなく現在の main をインストールします。
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Tools Guide、オプションの Memcode アダプター、deed.page サンプル、公開 API 互換性一覧も参照してください。これらの外部サービスはコア実行環境の必須条件ではありません。
📋 ドキュメント
- インストール、モデル、ツール、メモリ、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 を参照してください。
- 決定的な回帰評価については Evaluation Harness を参照してください。
- ツール/handoff 承認、永続レビュー、feedback については Human Review を参照してください。
ロードマップ
実装済みの機能と今後の計画はロードマップを参照してください。Inbox、Jobs、サブ Agent は任意で有効化する Runtime ですでに利用できます。
🌟 なぜ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 評価
LightEvaluator は決定的な業務ケースに対して出力、ツール選択、ポリシーイベント、回復、遅延、usage、推定コストを測定します。
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を提出してください。以下は貢献のステップです:
- このプロジェクトをフォーク:右上の
Forkボタンをクリックして、プロジェクトをGitHubリポジトリにコピーします。 - ブランチを作成:ローカルに開発ブランチを作成します:
git checkout -b feature/YourFeature
- 変更をコミット:開発を完了したら、変更をコミットします:
git commit -m 'Add some feature'
- ブランチをプッシュ:ブランチをリモートリポジトリにプッシュします:
git push origin feature/YourFeature
- プルリクエストを提出:GitHub上でプルリクエストを提出し、変更内容を説明します。
私たちは迅速にあなたの貢献をレビューします!ご支援ありがとうございます!❤️
🙏 謝辞
LightAgentの開発と実現は、以下のオープンソースプロジェクトのインスピレーションとサポートに寄っています。特に以下の優れたプロジェクトとチームに感謝します:
- mem0:メモリモジュールを提供してくれたmem0に感謝します。
- Swarm:マルチエージェント協調設計のアイデアを提供してくれたSwarmに感謝します。
- ChatGLM3:高性能な中国語大モデルのサポートとデザインのインスピレーションを提供してくれたChatGLM3に感謝します。
- Qwen:高性能な中国語大モデルのサポートを提供してくれたQwenに感謝します。
- DeepSeek-V3:高性能な中国語大モデルのサポートを提供してくれたDeepSeek-V3に感謝します。
- StepFun:高性能な中国語大モデルのサポートを提供してくれたstepに感謝します。
📄 ライセンス
LightAgentはApache 2.0ライセンスの下で使用されます。本プロジェクトは自由に使用、変更、配布できますが、ライセンスの条項を遵守してください。
📬 お問い合わせ
何か問題や提案がある場合は、いつでもお問い合わせください:
- メール:service@wanxingai.com
- GitHub Issues:https://github.com/wanxingai/LightAgent/issues
あなたのフィードバックをお待ちしております。一緒にLightAgentを強化しましょう!🚀
- さらに多くのツール 🛠️:実用的なツールを継続的に統合し、多くのシーンのニーズに応えます。
- モデルサポートの拡張 🔄:さらに多くの大モデルをサポートするように継続的に拡張します。
- 機能の追加 🎯:実用的な機能をさらに追加し、続々と更新を予定していますのでご期待ください!
- さらなるドキュメント 📚:詳細なドキュメントがあり、豊富なサンプルで迅速に始められ、プロジェクトに簡単に統合できます。
- さらなるコミュニティサポート 👥:活発な開発者コミュニティがあり、いつでも支援を提供します。
- さらなるパフォーマンス最適化 ⚡:継続的にパフォーマンスを最適化し、同時運用のシーンのニーズに応えます。
- さらなるオープンソース貢献 🌟:コードの貢献を歓迎し、より優れたLightAgentの構築に取り組みましょう!
LightAgent - インテリジェンスを軽量化し、未来をシンプルに。 🌈
LightAgent —— 軽量で柔軟、強力な能動的エージェントフレームワークで、迅速にインテリジェントなアプリケーションを構築します!
LightAgent🚀(차세대 Agentic AI 프레임워크)
LightAgent는 재사용 가능한 Skills, 도구, 선택적 장기 메모리, OpenAI 호환 모델 및 스트리밍을 지원하는 모듈형 오픈 소스 Python 프레임워크입니다. LightSwarm은 라우팅, LightFlow는 정해진 단계, LightDAG는 영속적인 동적 검증 작업을 담당합니다. 선택적 이벤트 소싱 Runtime은 영속 Session, 비동기 실행, 정책 및 승인을 제공합니다. MCP는 stdio, SSE, Streamable HTTP를 지원합니다.
뉴스
[2026-11-15] LightAgent v1.0.0이 GitHub에 정식 릴리스되었습니다. 재연결 가능한 실행, Job과 하위 에이전트의 통합 수명 주기, 트랜잭션 기반 복구와 선택형 Provider 서명 검증을 추가했습니다.
- [2026-10-01] LightAgent v0.11.0 릴리스: 선택형 영속 동적 다중 에이전트 DAG, 검증 후에만 공개되는 불변 산출물, lease와 fencing을 통한 복구, 권한을 축소만 할 수 있는 통합
SecurityContext및 승인 제어를 추가했습니다. - [2026-08-15] LightAgent v0.10.0 릴리스: 영속 Session, 비동기 실행, Capability Registry와 Policy, Inbox, Goals, Budgets, Jobs, 하위 에이전트, 컨텍스트 압축 및 SQLite FTS5 검색을 갖춘 이벤트 기반 Agent Runtime을 도입했습니다.
- [2026-08-15] LightAgent v0.9.7 릴리스: 오프라인 검증과 예제를 포함한 경량 무의존성 Connector 계약을 추가하고, Python executor 보안 검사를 강화했으며, 선택형 Mem0 Graph 보안 검증 매트릭스와 v1.0 안정화를 위한 공개 API 호환성 목록을 도입했습니다.
- [2026-07-30] LightAgent v0.9.6 릴리스: 프로덕션 Trace 요약 및 내보내기, 결정론적 평가, 도구·handoff·LightFlow의 지속 가능한 사람 승인, 공유 Graph Memory의 fail-closed 쓰기 승인 및 감사 제어를 추가했습니다.
- [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를 참고하세요.
✨ 특징
- 경량 및 효율성: LangChain이나 LlamaIndex 없이 사용하는 모듈형 오픈 소스 Python 프레임워크로, 모델, MCP, 메모리, 추적에는 목적별 의존성을 사용합니다.
- 이벤트 소싱 Runtime: 선택적 영속 Session, 재생, checkpoint, 비동기 호출, Capability와 Policy, Inbox, Goals, Budgets, Jobs, 하위 Agent, 컨텍스트 압축 및 SQLite FTS5 검색.
- 동적 검증 DAG: LightDAG는 그래프 변경을 영속화하고 독립 Worker를 병렬 실행하며, 애플리케이션이 지정한 검증을 통과한 후에만 불변 결과물을 게시합니다.
- 기억 지원 🧠: 각 사용자에 대한 맞춤형 장기 기억을 지원하며, 기본적으로
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를 관찰, 교체, 차단할 수 있습니다. - 평가와 사람 검토 📊:
LightEvaluator는 결정적 회귀 평가를 실행하며,HumanApprovalHook, 영구 review store, LightFlow checkpoint는 승인, 거부, 인자 편집과 feedback을 지원합니다.
🧭 아키텍처 한눈에 보기
| 계층 | 주요 API | 사용 시점 |
|---|---|---|
| 단일 Agent 런타임 | LightAgent |
모델 호출, 도구, 메모리, 스트리밍, trace, guardrails가 필요한 경우. |
| 영속 런타임 상태 | Session, AgentRuntime |
재생, checkpoint, Inbox, Goals, Budgets, Jobs 및 컨텍스트 복구. |
| 기능 계층 | CapabilityRegistry, PolicyEngine |
범위가 제한된 Provider, 정책, 수명 주기 및 감사. |
| 통합 보안 컨텍스트 | SecurityContext, CapabilityGate, ApprovalToken |
ID, 축소만 가능한 권한, 인가 및 작업에 연결된 승인. |
| 다중 Agent 라우팅 | LightSwarm |
전문 Agent 간 역할 기반 위임. |
| 결정적 workflow | LightFlow |
DAG, 재시도, checkpoint, 승인, resume, rerun. |
| 동적 검증 워크플로 | LightDAG |
동적 분해, Verifier, 결과물, 병렬 Worker 및 복구. |
| 도구와 통합 | 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) |
결정적 다단계 실행에 사용합니다. |
| 동적 워크플로 | LightDAG(...).create_run(...) |
작업을 동적으로 제안하고 게시 전에 결과를 검증합니다. |
| 영속 Session | agent.run(query, session_id="project-42") |
이어서 실행하거나 재생하려면 영속 SessionStore를 설정해야 합니다. |
| 비동기 | await agent.arun(query) |
asyncio 애플리케이션용 비차단 진입점입니다. |
v1.0.0: 영속 실행과 복구
- 재연결 가능한 작업:
ExecutionService는 호스트가 등록한 백엔드에서 일반 작업을 실행합니다. 다시 시작한 뒤에도ExecutionHandle로 재연결해 상태를 확인할 수 있습니다. - 상태 관리와 복구: Job과 하위 에이전트가 협력적 취소를 포함한 수명 주기를 공유합니다. 메시지와 예산 기록은 SQLite 트랜잭션으로 관리하며, 결과가 불확실하면 호스트가 확인할 때까지 외부 작업을 자동으로 반복하지 않습니다.
- 보안 및 설치: 서명된 Provider에 대해 런타임 정책과 별도로 호스트의 명시적 승인을 요구할 수 있습니다. 기본 설치에는 Skills와 PyYAML이 포함됩니다. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS 및 서명 검증은 선택 사항입니다.
- 호환성: 일반
run()호출과 스트리밍은 기존과 동일합니다. 연구 기능은 별도 LightResearch 확장으로 이동했으며, 기존mode="persistent"에는 명시적 등록이 필요합니다.
실행 가이드 · Job 및 기록 이전 · 오프라인 예제
v0.11.0: 검증 기반 동적 워크플로
역할 기반 라우팅에는 LightSwarm, 정해진 단계에는 LightFlow, 실행 중 Worker가 새 작업을 제안해야 할 때는 선택적으로 활성화하는 LightDAG를 사용합니다.
SqliteTaskGraphStore는 작업, 시도, 그래프 변경, 이벤트 및 복구 상태를 저장합니다. 독립적인 Worker 인스턴스를 동시에 실행할 수 있습니다.- Worker는
TaskOutcome.candidate(...),TaskOutcome.decompose(...)또는TaskOutcome.blocked(...)를 반환합니다. 분해 승인과 불변 산출물 공개는 애플리케이션이 고정한 Verifier만 수행합니다. - lease와 fencing은 재시작 시 오래된 시도를 거부합니다.
SecurityContext,CapabilityGate, 작업에 바인딩된ApprovalToken이 신원, 축소만 가능한 권한 및 승인을 명시합니다.
오프라인 LightDAG 예제
모델, API 키, 네트워크가 필요하지 않습니다. 임시 SQLite 데이터베이스와 산출물 디렉터리를 사용하고 종료 시 정리합니다.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
영속 사용 시에는 임시 디렉터리 대신 명시적인 저장 경로를 유지하세요. 동적 분해와 복구 전체 예제 및 LightDAG 가이드에서 의존성, 통합, 재시도, 복구를 설명합니다.
영속 Session, 비동기 호출, Capability Provider, Policy, Inbox, Goals, Budgets, Jobs 설정은 Runtime 가이드를 참고하세요.
호환성과 보안 경계
- 기존
agent.run(query),stream=True,user_id는 계속 지원합니다. LightDAG는 선택 기능이며 LightFlow를 대체하지 않습니다. - v0.11.0은 단일 호스트, 로컬 SQLite, 실행당 하나의 활성 스케줄러를 전제로 합니다. 실행은 최소 한 번이며 외부 부작용에는 멱등성이 필요합니다. 분산 Worker, Web UI, 내장 코드 샌드박스는 포함하지 않습니다.
enable_unsafe_python=True또는 등록된SandboxProvider가 있어도 기존execute_python_code,execute_python_file,execute_python_code_stream의 모델/도구 디스패치는 차단됩니다.safe_expression이나 실제로 격리된 사용자 정의 도구를 사용하세요. 유틸리티 직접 호출은 보안 샌드박스가 아닙니다.- 메모리 출처, 쓰기 승인 및 승격 정책은 여전히 필요합니다. 프레임워크 테스트만으로 실제 공유 그래프 메모리 backend의 보안을 인증할 수 없습니다. 메모리 보안 경계를 참고하세요.
공개 릴리스와 현재 main
v0.11.0은 2026-10-01에 공개되었습니다. 도구 선택 JSON, MCP SDK 1.x/2.x 및 선택형 deed.page 예제의 후속 변경은 해당 tag 이후 main에 병합되었으며 배포 패키지에는 없을 수 있습니다. 다음 명령은 원래 tag가 아닌 현재 main을 설치합니다.
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Tools Guide, 선택형 Memcode 어댑터, deed.page 예제, 공개 API 호환성 목록을 참고하세요. 이러한 외부 서비스는 핵심 런타임의 필수 조건이 아닙니다.
📋 문서
- 설치, 모델, 도구, 메모리, 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를 참고하세요.
- 결정적 회귀 평가는 Evaluation Harness를 참고하세요.
- 도구/handoff 승인, 영구 검토와 feedback은 Human Review를 참고하세요.
로드맵
완료된 기능과 향후 계획은 로드맵을 참고하세요. Inbox, Jobs, 하위 Agent는 선택적 Runtime에서 이미 사용할 수 있습니다.
🌟 왜 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 평가
LightEvaluator는 결정적 업무 사례에서 출력, 도구 선택, 정책 이벤트, 복구, 지연, usage와 예상 비용을 측정합니다.
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를 제출해 주십시오. 기여 방법은 다음과 같습니다:
- 이 프로젝트 포크하기: 오른쪽 상단의
Fork버튼을 클릭하여 프로젝트를 귀하의 GitHub 리포지토리로 복사합니다. - 브랜치 생성: 로컬에서 개발 브랜치를 생성합니다:
git checkout -b feature/YourFeature
- 변경 내역 제출: 개발을 완료한 후 변경 사항을 제출합니다:
git commit -m 'Add some feature'
- 브랜치 푸시: 브랜치를 귀하의 원격 리포지토리에 푸시합니다:
git push origin feature/YourFeature
- 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 라이센스를 따릅니다. 본 프로젝트는 자유롭게 사용, 수정 및 배포할 수 있지만 라이센스 조건을 준수해야 합니다.
📬 문의하기
질문이나 제안이 있는 경우 언제든지 문의해 주십시오:
- 이메일: service@wanxingai.com
- GitHub Issues:https://github.com/wanxingai/LightAgent/issues
우리는 귀하의 피드백을 기대하며 함께 LightAgent를 더 강력하게 만들어 갑시다!🚀
- 더 많은 도구 🛠️: 사용 사례 요구를 충족하기 위해 더 많은 유용한 도구를 지속적으로 통합합니다.
- 더 많은 모델 지원 🔄: 더 많은 대형 모델을 지속적으로 지원하여 더 다양한 응용 사례를 충족합니다.
- 더 많은 기능 🎯: 더 많은 유용한 기능이 지속적으로 업데이트됩니다. 기대해 주세요!
- 더 많은 문서 📚: 자세한 문서와 풍부한 예시로 빠르게 배워 프로젝트에 쉽게 통합할 수 있습니다.
- 더 많은 커뮤니티 지원 👥: 활발한 개발자 커뮤니티가 언제든지 도움과 해답을 제공합니다.
- 더 많은 성능 최적화 ⚡: 고병렬 요구를 충족하기 위해 성능을 지속적으로 최적화합니다.
- 더 많은 오픈 소스 기여 🌟: 기여 코드를 환영하며 함께 더 나은 LightAgent를 만들어 갑시다!
LightAgent - 스마트함을 더 가볍게, 미래를 더 단순하게 만듭니다. 🌈
LightAgent —— 경량화, 유연성, 강력한 능동적 에이전트 프레임워크로, 스마트 애플리케이션을 신속하게 구축합니다!
LightAgent🚀(Próxima geração de estrutura de IA Agentic)
LightAgent é um framework Python modular e de código aberto com Skills reutilizáveis, ferramentas, memória de longo prazo opcional e modelos e streaming compatíveis com OpenAI. LightSwarm cuida do roteamento, LightFlow de etapas conhecidas e LightDAG de tarefas dinâmicas persistentes e verificadas. O runtime opcional baseado em eventos oferece sessões persistentes, execução assíncrona, políticas e aprovações. MCP suporta stdio, SSE e Streamable HTTP.
Notícias
[2026-11-15] LightAgent v1.0.0 foi lançado oficialmente no GitHub. A versão adiciona execução com reconexão, ciclo de vida unificado para Jobs e subagentes, recuperação transacional e assinaturas opcionais de Providers.
- [2026-10-01] LightAgent v0.11.0 lançado: adiciona DAGs dinâmicos multiagente persistentes e opcionais, artefatos imutáveis publicados somente após verificação, recuperação com leases e fencing e um
SecurityContextunificado com permissões que só podem ser reduzidas e controles de aprovação. - [2026-08-15] LightAgent v0.10.0 lançado: introduz o runtime baseado em eventos com Sessions persistentes, execução assíncrona, Capability Registry e Policy, Inbox, Goals, Budgets, Jobs, subagentes, compactação de contexto e busca SQLite FTS5.
- [2026-08-15] LightAgent v0.9.7 lançado: adiciona um contrato Connector leve e sem dependências com validação offline e exemplos, amplia as verificações de segurança do executor Python, introduz uma matriz de segurança opcional para Mem0 Graph e prepara a estabilização da v1.0 com um inventário de compatibilidade da API pública.
- [2026-07-30] LightAgent v0.9.6 lançado: adiciona resumos e exportadores de trace para produção, avaliação determinística, aprovação humana persistente para ferramentas, handoffs e LightFlow, além de admissão de escrita fail-closed e controles de auditoria para memória gráfica compartilhada.
- [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: Framework Python modular e de código aberto, sem LangChain nem LlamaIndex, com dependências específicas para modelos, MCP, memória e rastreamento.
- Runtime baseado em eventos: Sessões persistentes opcionais, replay, checkpoints, chamadas assíncronas, Capability e Policy, Inbox, Goals, Budgets, Jobs, subagentes, compactação do contexto e busca SQLite FTS5.
- DAGs dinâmicos verificados: LightDAG persiste alterações do grafo, executa Workers independentes em paralelo e publica artefatos imutáveis somente após verificação definida pela aplicação.
- 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. - Avaliação e revisão humana 📊:
LightEvaluatorexecuta regressões determinísticas;HumanApprovalHook, review stores persistentes e checkpoints LightFlow suportam aprovação, rejeição, edição de argumentos e feedback.
🧭 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. |
| Estado persistente do runtime | Session, AgentRuntime |
Replay, checkpoints, Inbox, Goals, Budgets, Jobs e recuperação do contexto. |
| Camada de capacidades | CapabilityRegistry, PolicyEngine |
Provedores com escopo limitado, políticas, ciclo de vida e auditoria. |
| Contexto de segurança unificado | SecurityContext, CapabilityGate, ApprovalToken |
Identidade, permissões que só podem ser reduzidas, autorização e aprovações vinculadas a uma operação. |
| Roteamento multiagente | LightSwarm |
Delegação por papéis entre agentes especializados. |
| Workflow determinístico | LightFlow |
DAG, retentativas, checkpoints, aprovações, resume e rerun. |
| Workflow dinâmico verificado | LightDAG |
Decomposição dinâmica, verificadores, artefatos, Workers paralelos e recuperação. |
| 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. |
| Workflow dinâmico | LightDAG(...).create_run(...) |
Propor tarefas e verificar resultados antes da publicação. |
| Sessão persistente | agent.run(query, session_id="project-42") |
Exige um SessionStore persistente configurado para replay e continuação. |
| Assíncrono | await agent.arun(query) |
Entrada não bloqueante para aplicações asyncio. |
v1.0.0: Execução persistente e recuperação
- Tarefas com reconexão:
ExecutionServiceexecuta tarefas comuns usando um backend registrado pelo aplicativo hospedeiro.ExecutionHandlepermite reconectar e consultar o estado após uma reinicialização. - Estado e recuperação: Jobs e subagentes compartilham um ciclo de vida com cancelamento cooperativo. Transações SQLite protegem mensagens e registros de orçamento; resultados incertos exigem confirmação do hospedeiro antes de repetir efeitos externos.
- Segurança e instalação: Providers assinados podem exigir aprovação explícita do hospedeiro, sem substituir as políticas de execução. A instalação básica inclui Skills e PyYAML. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS e verificação de assinaturas são opcionais.
- Compatibilidade:
run()e streaming mantêm o comportamento anterior. A pesquisa foi movida para a extensão separada LightResearch; o modo legadomode="persistent"exige registro explícito.
Guia de execução · Migração de Jobs e histórico · Exemplo offline
v0.11.0: Workflows dinâmicos verificados
Use LightSwarm para roteamento por papéis, LightFlow para etapas conhecidas e o LightDAG opcional quando os Workers precisarem propor novas tarefas durante a execução.
SqliteTaskGraphStorepersiste tarefas, tentativas, alterações do grafo, eventos e estado de recuperação. Instâncias independentes de Worker podem executar em paralelo.- Os Workers retornam
TaskOutcome.candidate(...),TaskOutcome.decompose(...)ouTaskOutcome.blocked(...). Somente um Verifier definido pela aplicação pode aprovar decomposições ou publicar artefatos imutáveis. - Leases e fencing rejeitam tentativas antigas durante a recuperação.
SecurityContext,CapabilityGateeApprovalTokenvinculado à operação explicitam identidade, permissões que só podem ser reduzidas e aprovações.
Exemplo LightDAG offline
Não exige modelo, chave de API nem rede. Usa um banco SQLite e um diretório de artefatos temporários, removidos ao terminar.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
Para persistência real, mantenha caminhos explícitos para banco e artefatos em vez de diretórios temporários. O exemplo completo de decomposição e reparo e o guia LightDAG cobrem dependências, integração, novas tentativas e recuperação.
O guia do runtime explica sessões persistentes, chamadas assíncronas, Capability Providers, Policy, Inbox, Goals, Budgets e Jobs.
Compatibilidade e limites de segurança
agent.run(query),stream=Trueeuser_idcontinuam disponíveis. LightDAG é opcional e não substitui LightFlow.- v0.11.0 limita-se a um host, SQLite local e um escalonador ativo por execução. A execução é pelo menos uma vez; efeitos externos exigem idempotência. Workers distribuídos, interface web e sandbox de código integrada não estão incluídos.
- Os antigos
execute_python_code,execute_python_fileeexecute_python_code_streamsão bloqueados na execução de ferramentas pelo modelo, mesmo comenable_unsafe_python=Trueou umSandboxProviderregistrado. Usesafe_expressionou uma ferramenta realmente isolada; chamadas diretas a esses utilitários não são uma sandbox de segurança. - As políticas de procedência, admissão e promoção de memória continuam necessárias. Testes do framework não certificam um backend real de memória gráfica compartilhada; consulte segurança de memória.
Versão publicada e main atual
v0.11.0 foi publicada em 2026-10-01. Correções posteriores de JSON de seleção de ferramentas, MCP SDK 1.x/2.x e o exemplo opcional deed.page foram integrados após esse tag e podem não estar no pacote publicado. O comando a seguir instala o main atual, não o tag original:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
Consulte Tools Guide, o adaptador Memcode opcional, o exemplo deed.page e o inventário de compatibilidade pública. Esses serviços externos não são obrigatórios para o runtime principal.
📋 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.
- Para regressões determinísticas, consulte Evaluation Harness.
- Para aprovação de ferramentas/handoffs, revisão persistente e feedback, consulte Human Review.
Roteiro
Consulte o roteiro para os marcos entregues e os planos futuros. Inbox, Jobs e subagentes já estão disponíveis no runtime opcional.
🌟 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
LightEvaluator mede saída, uso de ferramentas, eventos de política, recuperação, latência e custo.
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:
- Fork este projeto: Clique no botão
Forkno canto superior direito para copiar o projeto para seu repositório GitHub. - Crie uma branch: Crie uma branch de desenvolvimento local:
git checkout -b feature/SuaFuncionalidade
- Submeta suas alterações: Após a conclusão do desenvolvimento, submeta suas alterações:
git commit -m 'Adicionando nova funcionalidade'
- Envie a branch: Envie a branch para o seu repositório remoto:
git push origin feature/SuaFuncionalidade
- 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:
- Email: service@wanxingai.com
- Issues no GitHub: https://github.com/wanxingai/LightAgent/issues
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 — модульный Python-фреймворк с открытым исходным кодом, переиспользуемыми Skills, инструментами, необязательной долговременной памятью и OpenAI-совместимыми моделями и потоковым выводом. LightSwarm отвечает за маршрутизацию, LightFlow — за известные шаги, а LightDAG — за сохраняемые динамические задачи с проверкой результатов. Необязательный событийный runtime добавляет постоянные сессии, асинхронное выполнение, политики и согласования. MCP поддерживает stdio, SSE и Streamable HTTP.
Новости
[2026-11-15] LightAgent v1.0.0 официально выпущен на GitHub. Добавлены выполнение с повторным подключением, единый жизненный цикл заданий и субагентов, транзакционное восстановление и необязательная проверка подписей поставщиков.
- [2026-10-01] Выпущен LightAgent v0.11.0: добавлены опциональные сохраняемые динамические DAG для нескольких агентов, неизменяемые артефакты с публикацией только после проверки, восстановление с арендой и fencing, а также единый
SecurityContextс правами, которые можно только сужать, и контролем одобрений. - [2026-08-15] Выпущен LightAgent v0.10.0: представлен событийный Agent Runtime с сохраняемыми Sessions, асинхронным выполнением, Capability Registry и Policy, Inbox, Goals, Budgets, Jobs, дочерними агентами, сжатием контекста и поиском SQLite FTS5.
- [2026-08-15] Выпущен LightAgent v0.9.7: добавлен лёгкий Connector-контракт без зависимостей с офлайн-валидацией и примерами, усилены проверки безопасности Python executor, добавлена опциональная матрица безопасности Mem0 Graph и подготовлена стабилизация v1.0 с помощью перечня совместимости публичного API.
- [2026-07-30] Выпущен LightAgent v0.9.6: добавлены производственные сводки и экспорт Trace, детерминированная оценка, сохраняемое человеческое одобрение для инструментов, handoff и LightFlow, а также fail-closed допуск записей и аудит общей Graph Memory.
- [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.
✨ Особенности
- Легковесность и эффективность: Модульный Python-фреймворк с открытым исходным кодом без LangChain и LlamaIndex, с целевыми зависимостями для моделей, MCP, памяти и трассировки.
- Событийный runtime: Необязательные постоянные сессии, воспроизведение событий, checkpoints, асинхронные вызовы, Capability и Policy, Inbox, Goals, Budgets, Jobs, субагенты, сжатие контекста и поиск SQLite FTS5.
- Динамические DAG с проверкой: LightDAG сохраняет изменения графа, параллельно выполняет независимые Workers и публикует неизменяемые артефакты только после проверки, заданной приложением.
- Поддержка памяти 🧠: поддержка пользовательской долгосрочной памяти для каждого пользователя, нативная поддержка модуля памяти
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. - Оценка и человеческая проверка 📊:
LightEvaluatorзапускает детерминированные регрессии;HumanApprovalHook, постоянные review-store и checkpoint LightFlow поддерживают одобрение, отклонение, изменение аргументов и feedback.
🧭 Архитектура кратко
| Слой | Основной API | Когда использовать |
|---|---|---|
| Runtime одного агента | LightAgent |
Один агент с моделью, инструментами, памятью, streaming, trace и guardrails. |
| Постоянное состояние runtime | Session, AgentRuntime |
Воспроизведение событий, checkpoints, Inbox, Goals, Budgets, Jobs и восстановление контекста. |
| Слой возможностей | CapabilityRegistry, PolicyEngine |
Провайдеры с ограниченной областью, политики, жизненный цикл и аудит. |
| Единый контекст безопасности | SecurityContext, CapabilityGate, ApprovalToken |
Идентичность, только сужаемые права, авторизация и согласования конкретных операций. |
| Маршрутизация агентов | LightSwarm |
Делегирование по ролям между специализированными агентами. |
| Детерминированный workflow | LightFlow |
DAG, повторы, checkpoints, утверждения, resume и rerun. |
| Динамический проверяемый процесс | LightDAG |
Динамическое разбиение, проверяющие модули, артефакты, параллельные Workers и восстановление. |
| Инструменты и интеграции | 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) |
Для детерминированного многошагового выполнения. |
| Динамический процесс | LightDAG(...).create_run(...) |
Предлагать задачи и проверять результаты перед публикацией. |
| Постоянная сессия | agent.run(query, session_id="project-42") |
Для продолжения и воспроизведения нужен настроенный постоянный SessionStore. |
| Асинхронный вызов | await agent.arun(query) |
Неблокирующая точка входа для приложений asyncio. |
v1.0.0: Долговременное выполнение и восстановление
- Повторное подключение к задачам:
ExecutionServiceзапускает обычные задачи через бэкенд, зарегистрированный приложением. После перезапускаExecutionHandleпозволяет снова подключиться к задаче и проверить её состояние. - Состояние и восстановление: Задания и субагенты используют общий жизненный цикл с кооперативной отменой. Транзакции SQLite защищают сообщения и учёт бюджета. При неизвестном результате приложение должно проверить состояние, прежде чем повторять внешнее действие.
- Безопасность и установка: Подписанные поставщики могут требовать явного одобрения приложения в дополнение к политикам выполнения. Базовая установка включает Skills и PyYAML. MCP, Mem0, Langfuse, LiteLLM, OSS/NOS и проверка подписей подключаются отдельно.
- Совместимость: Обычные вызовы
run()и потоковый вывод не изменились. Исследования вынесены в отдельное расширение LightResearch; прежнийmode="persistent"требует его явной регистрации.
Руководство по выполнению · Миграция заданий и истории · Офлайн-пример
v0.11.0: Проверяемые динамические процессы
Используйте LightSwarm для маршрутизации по ролям, LightFlow для заранее известных этапов и опциональный LightDAG, если Workers должны предлагать новые задачи во время выполнения.
SqliteTaskGraphStoreсохраняет задачи, попытки, изменения графа, события и состояние восстановления. Независимые экземпляры Worker могут выполняться параллельно.- Workers возвращают
TaskOutcome.candidate(...),TaskOutcome.decompose(...)илиTaskOutcome.blocked(...). Только заданный приложением Verifier может принять декомпозицию или опубликовать неизменяемые артефакты. - Аренда и fencing отклоняют устаревшие попытки при восстановлении.
SecurityContext,CapabilityGateи привязанный к операцииApprovalTokenявно задают идентичность, только сужаемые права и одобрения.
Офлайн-пример LightDAG
Модель, API-ключ и сеть не нужны. Пример использует временную базу SQLite и каталог артефактов и удаляет их при завершении.
from pathlib import Path
from tempfile import TemporaryDirectory
from LightAgent import (
CallableVerifier, LightDAG, LocalArtifactStore, PermissionSet,
SecurityContext, SqliteTaskGraphStore, TaskOutcome, TaskSpec,
)
with TemporaryDirectory() as directory:
root = Path(directory)
store = SqliteTaskGraphStore(root / "dag.sqlite3")
try:
dag = LightDAG(
store=store,
artifact_store=LocalArtifactStore(root / "artifacts"),
verifiers={"exact": CallableVerifier(
"exact", lambda request: request.candidate_content == b"42",
)},
)
dag.register_worker("local", lambda context: TaskOutcome.candidate("42"))
dag.create_run([TaskSpec(
task_id="answer", goal="42",
acceptance_contract={"equals": "42"},
worker_key="local", verifier_key="exact",
)], run_id="readme-demo", context=SecurityContext(
user_id="alice", tenant_id="demo", project_id="readme",
permissions=PermissionSet(allowed=frozenset({"dag.task.execute"})),
))
result = dag.run("readme-demo")
assert result.success
print(result.status.value)
finally:
store.close()
Для постоянного хранения задайте явные пути вместо временных каталогов. Полный пример декомпозиции и исправления и руководство LightDAG описывают зависимости, интеграцию, повторы и восстановление.
Настройку постоянных сессий, асинхронных вызовов, Capability Providers, Policy, Inbox, Goals, Budgets и Jobs описывает руководство по runtime.
Совместимость и границы безопасности
agent.run(query),stream=Trueиuser_idостаются доступными. LightDAG включается явно и не заменяет LightFlow.- v0.11.0 работает на одном хосте с локальной SQLite и одним активным планировщиком на запуск. Семантика выполнения — как минимум один раз; внешние побочные эффекты требуют идемпотентности. Распределённые Workers, Web UI и встроенная песочница кода не входят в выпуск.
- Старые
execute_python_code,execute_python_fileиexecute_python_code_streamзаблокированы в вызовах инструментов моделью даже приenable_unsafe_python=Trueили зарегистрированномSandboxProvider. Используйтеsafe_expressionлибо действительно изолированный инструмент; прямой вызов утилит не является безопасной песочницей. - Политики происхождения, допуска записи и продвижения памяти по-прежнему нужны. Тесты фреймворка не сертифицируют реальный общий графовый backend; см. безопасность памяти.
Опубликованный выпуск и текущий main
v0.11.0 опубликован 2026-10-01. Последующие исправления JSON выбора инструментов, MCP SDK 1.x/2.x и опциональный пример deed.page вошли в main после этого тега и могут отсутствовать в опубликованном пакете. Следующая команда устанавливает текущий main, а не исходный тег:
pip install --upgrade "git+https://github.com/wanxingai/LightAgent.git@main"
См. Tools Guide, опциональный адаптер Memcode, пример deed.page и перечень совместимости публичного API. Эти внешние сервисы не обязательны для основного runtime.
📋 Документация
- По установке, моделям, инструментам, памяти, 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.
- По детерминированным регрессиям см. Evaluation Harness.
- По одобрению tools/handoff, постоянной проверке и feedback см. Human Review.
План развития
Выполненные этапы и дальнейшие планы приведены в плане развития. Inbox, Jobs и субагенты уже доступны в необязательном runtime.
🌟 Почему выбирают 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. Оценка агентов
LightEvaluator измеряет вывод, выбор инструментов, события политик, восстановление, задержку, usage и оценочную стоимость.
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. Вот шаги по вкладке:
- Сделайте форк проекта: нажмите кнопку
Forkв правом верхнем углу, чтобы скопировать проект в ваш репозиторий GitHub. - Создайте ветвь: создайте вашу разработческую ветвь локально:
git checkout -b feature/YourFeature
- Подайте измененные данные: после завершения разработки подайте ваши изменения:
git commit -m 'Добавление новой функции'
- Отправьте ветвь: отправьте ветвь в ваш удалённый репозиторий:
git push origin feature/YourFeature
- Подайте 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 лицензией. Вы можете свободно использовать, изменять и распространять этот проект, но пожалуйста, соблюдайте условия лицензии.
📬 Свяжитесь с нами
Если у вас есть вопросы или предложения, команда всегда открыта для контакта:
- Электронная почта: service@wanxingai.com
- GitHub Issues:https://github.com/wanxingai/LightAgent/issues
Мы ждём ваших отзывов, чтобы вместе сделать LightAgent ещё сильнее!🚀
LightAgent - сделаем интеллект легче, а будущее проще. 🌈
LightAgent — легковесная, гибкая, мощная активная платформа агента, помогающая вам быстро разрабатывать интеллектуальные приложения!
Metadata
Release files for LightAgent 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| lightagent-1.0.0.tar.gz | 424.3 kB | Without provenance | Details for lightagent-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| lightagent-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for lightagent-1.0.0-py3-none-any.whl |
Total release size: 774.8 kB
Release files / lightagent-1.0.0.tar.gz
| Download URL | lightagent-1.0.0.tar.gz |
|---|---|
| Size | 424.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9217a52eb7ce32d1bb225c30c04c394d89a94b65ed08ff1eb7337e4a241ba7d9
|
|
BLAKE2b-256 checksum How to use checksums |
4a8f82c7d66dd14aaf8d9aa530ca3f046aa5eec1c168fe6727b6230f01c027f1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.8.5 CPython/3.11.7 Darwin/25.6.0
|
Release files / lightagent-1.0.0-py3-none-any.whl
| Download URL | lightagent-1.0.0-py3-none-any.whl |
|---|---|
| Size | 350.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e59d918c716c83d067d13e46e1ac47274f777344116e381a87c9fc0fb365a5bb
|
|
BLAKE2b-256 checksum How to use checksums |
1a158b101705aa38dde5f016a75acc8822e150c739b7ea231c957e7aa1083f12
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/1.8.5 CPython/3.11.7 Darwin/25.6.0
|
Security for LightAgent 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.