Metadata-Version: 2.4
Name: agentlenscn
Version: 0.1.0
Summary: See what your agents think. Open-source AI Agent observability platform.
Project-URL: Homepage, https://github.com/agentlens/agentlens
Project-URL: Repository, https://github.com/agentlens/agentlens
Project-URL: Documentation, https://github.com/agentlens/agentlens#readme
Project-URL: Issues, https://github.com/agentlens/agentlens/issues
Author: AgentLens Contributors
License-Expression: MIT
License-File: LICENSE
Keywords: agent,ai,debugging,llm,observability,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: click>=8.0.0
Requires-Dist: fastapi>=0.100.0
Requires-Dist: uvicorn>=0.20.0
Provides-Extra: all
Requires-Dist: dashscope>=1.14.0; extra == 'all'
Requires-Dist: minimax>=0.1.0; extra == 'all'
Requires-Dist: openai>=1.0.0; extra == 'all'
Requires-Dist: volcengine-python-sdk-ark-runtime>=0.1.0; extra == 'all'
Requires-Dist: zhipuai>=2.0.0; extra == 'all'
Provides-Extra: all-cn
Requires-Dist: dashscope>=1.14.0; extra == 'all-cn'
Requires-Dist: minimax>=0.1.0; extra == 'all-cn'
Requires-Dist: volcengine-python-sdk-ark-runtime>=0.1.0; extra == 'all-cn'
Requires-Dist: zhipuai>=2.0.0; extra == 'all-cn'
Provides-Extra: dashscope
Requires-Dist: dashscope>=1.14.0; extra == 'dashscope'
Provides-Extra: dev
Requires-Dist: httpx>=0.24.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: minimax
Requires-Dist: minimax>=0.1.0; extra == 'minimax'
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == 'openai'
Provides-Extra: volcengine
Requires-Dist: volcengine-python-sdk-ark-runtime>=0.1.0; extra == 'volcengine'
Provides-Extra: zhipuai
Requires-Dist: zhipuai>=2.0.0; extra == 'zhipuai'
Description-Content-Type: text/markdown

# AgentLens

**See what your agents think.**

Every AI agent is a black box. You send a prompt, wait, and get a result — but you have no idea what happened in between. Which tools did it call? How many tokens did it burn? Why did it make that decision?

AgentLens opens the box. It's an open-source observability toolkit that traces every step of your AI agent's execution — LLM calls, tool invocations, decision branches — and shows them in a real-time debug panel. For developers debugging agents, and for end users who need to trust them.

<!-- TODO: Add demo GIF here -->
<!-- ![AgentLens Demo](docs/demo.gif) -->

## The Problem

Building AI agents is hard. Debugging them is harder.

- Your agent calls GPT-4 five times but you only see the final output
- Token costs spike and you can't tell which step is burning money
- Users don't trust your agent because they can't see what it's doing
- Critical operations (deployments, payments) happen without human oversight

Existing tools like Langfuse track LLM calls, but agents are more than LLM calls — they're chains of decisions, tool uses, and branching logic. You need visibility into the full picture.

## How AgentLens Works

**3 lines of code. Full visibility.**

```python
import agentlens

agentlens.init(auto_instrument=["openai"])

# That's it. Every OpenAI call is now traced.
```

Then open the debug panel:

```bash
agentlens serve
# → http://localhost:7600
```

You'll see every agent run as an interactive execution tree — nested spans, token counts, latencies, inputs/outputs, errors — all in real time.

## Two Layers of Value

### Layer 1: Developer Debug Panel

Trace your agent's full execution chain with decorators:

```python
@agentlens.agent(name="research_agent")
def research(topic: str) -> str:
    queries = generate_queries(topic)    # traced
    results = search(queries)            # traced
    return summarize(results)            # traced

@agentlens.tool(name="search")
def search(queries: list) -> list:
    ...

@agentlens.llm_call(name="summarize", model="gpt-4o")
def summarize(results: list) -> str:
    ...
```

The debug panel gives you:

- **Execution tree** — Nested span hierarchy showing the full decision chain
- **Timeline waterfall** — Parallel execution visualization
- **Token & cost stats** — Per-call and per-trace token breakdown
- **Span details** — Input/output JSON, model info, latency, errors
- **Real-time streaming** — Watch spans appear as your agent runs
- **Error highlighting** — Failed steps are immediately visible

### Layer 2: End-User Widgets

Your users shouldn't have to blindly trust your agent. Embed transparency directly into your app with `@agentlens/widget`:

```tsx
import { AgentLensProvider, StatusStream, ThinkingView, ConfirmDialog } from '@agentlens/widget';

function App() {
  return (
    <AgentLensProvider endpoint="ws://localhost:7600/ws/traces">
      <ThinkingView collapsed={false} />
      <StatusStream maxItems={5} showTimestamp />
      <ConfirmDialog allowReason />
    </AgentLensProvider>
  );
}
```

| Component | What it does |
|-----------|-------------|
| `<StatusStream />` | Real-time feed showing what the agent is doing right now |
| `<ThinkingView />` | Step-by-step breakdown of the agent's reasoning process |
| `<ConfirmDialog />` | Pause execution for human approval on critical operations |

## Human-in-the-Loop

Some operations are too important to run on autopilot. Mark them with `requires_confirm=True` and the agent pauses until a human approves:

```python
@agentlens.tool(name="deploy", requires_confirm=True)
def deploy(env: str) -> dict:
    return {"status": "deployed", "env": env}

@agentlens.tool(name="apply_fix", requires_confirm=True)
def apply_fix(file: str, line: int, fix: str) -> dict:
    return {"status": "applied", "file": file}
```

When the agent hits a confirmed step, the `<ConfirmDialog>` widget pops up in the user's browser. Execution resumes only after approval.

## Architecture

```
Your Python Agent
    │
    ├── agentlens.init()              # One-line setup
    ├── @agent / @tool / @llm_call    # Decorator-based tracing
    └── OpenAI auto-instrument        # Zero-code tracing
            │
            ▼
    In-Process Collector (async)
            │
            ▼
    SQLite (~/.agentlens/traces.db)   # Zero infrastructure
            │
            ▼
    FastAPI Server (localhost:7600)
    ├── REST API    → /api/v1/traces
    ├── WebSocket   → /ws/traces (real-time push)
    ├── Debug Panel → React SPA
    └── Widget SDK  → @agentlens/widget (npm)
```

Everything runs locally. No cloud. No accounts. No data leaves your machine.

## Examples

### Research Agent (OpenAI auto-instrumentation)

```python
agentlens.init(auto_instrument=["openai"])

@agentlens.trace(name="research_agent")
def research(topic: str) -> str:
    queries = generate_search_queries(topic)  # GPT-4o-mini
    findings = [analyze(q) for q in queries]  # GPT-4o-mini × 3
    return synthesize(findings)               # GPT-4o
```

### Tool Chain Agent (custom tools)

```python
@agentlens.agent(name="daily_briefing_agent")
def daily_briefing(email: str, city: str, interests: list) -> str:
    weather = fetch_weather(city)
    news = [fetch_news(topic) for topic in interests]
    send_email(to=email, subject="Daily Briefing", body=compose(weather, news))
```

### Human-in-the-Loop Agent (confirmation flow)

```python
@agentlens.agent(name="code_review_agent")
def review_and_fix(repo: str) -> str:
    issues = analyze_codebase(repo)
    for issue in issues:
        apply_fix(issue)          # ← requires_confirm=True, pauses here
    if run_tests()["failed"] == 0:
        deploy("staging")         # ← requires_confirm=True, pauses here
```

See full examples in [`examples/`](examples/).

## API Reference

### Python SDK

```python
agentlens.init(auto_instrument=["openai"])       # Initialize
@agentlens.trace(name="my_trace")                # Top-level trace
@agentlens.agent(name="my_agent")                # Agent span
@agentlens.tool(name="my_tool")                  # Tool span
@agentlens.llm_call(name="call", model="gpt-4o") # LLM call span
```

### REST API

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/traces` | List traces (`limit`, `offset`, `status`) |
| GET | `/api/v1/traces/{id}` | Get trace with full span tree |
| GET | `/api/v1/traces/{id}/stats` | Trace statistics (tokens, cost, duration) |
| DELETE | `/api/v1/traces/{id}` | Delete a trace |

### WebSocket

Connect to `ws://localhost:7600/ws/traces` for real-time events:

- `span_start` — New span began
- `span_end` — Span completed (status, duration, tokens)
- `trace_end` — Trace completed

## Quick Start

```bash
pip install agentlens
```

```python
import agentlens
agentlens.init(auto_instrument=["openai"])
# All OpenAI calls are now traced
```

```bash
agentlens serve
# Open http://localhost:7600
```

## Development

```bash
# Clone and install
git clone https://github.com/TF-Wilbur/agentlens.git
cd agentlens
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Run tests (111 tests, 88% coverage)
pytest

# Frontend debug panel
cd frontend && npm install && npm run dev

# Widget library
cd widget && npm install && npm run build
```

## Why Not Langfuse / LangSmith?

| | AgentLens | Langfuse | LangSmith |
|---|---|---|---|
| Traces full agent logic | Yes | LLM calls only | LangChain only |
| End-user widgets | Yes | No | No |
| Human-in-the-loop | Built-in | No | No |
| Self-hosted | Local-first | Docker required | Cloud only |
| Framework lock-in | None | None | LangChain |
| Setup | 3 lines | Docker + config | Account + API key |

## License

MIT

---

# AgentLens 中文介绍

**看见你的 Agent 在想什么。**

每个 AI Agent 都是一个黑盒。你发了一个 prompt，等了一会儿，拿到结果——但中间发生了什么，你一无所知。它调了哪些工具？烧了多少 token？为什么做了那个决定？

AgentLens 打开这个黑盒。它是一个开源的 AI Agent 可观测性工具，追踪 Agent 执行的每一步——LLM 调用、工具调用、决策分支——并在实时调试面板中展示。既帮开发者调试 Agent，也帮终端用户信任 Agent。

## 要解决的问题

构建 AI Agent 很难，调试它更难。

- Agent 调了 5 次 GPT-4，你只看到最终输出
- Token 费用飙升，不知道哪一步在烧钱
- 用户不信任你的 Agent，因为看不到它在干什么
- 关键操作（部署、支付）在没有人类监督的情况下执行

现有工具如 Langfuse 追踪 LLM 调用，但 Agent 不只是 LLM 调用——它是决策、工具使用和分支逻辑的链条。你需要看到全貌。

## 怎么用

**3 行代码，完整可见。**

```python
import agentlens

agentlens.init(auto_instrument=["openai"])

# 搞定。所有 OpenAI 调用自动被追踪。
```

然后打开调试面板：

```bash
agentlens serve
# → http://localhost:7600
```

你会看到每次 Agent 运行的交互式执行树——嵌套的 span、token 计数、延迟、输入/输出、错误——全部实时展示。

## 两层价值

### 第一层：开发者调试面板

用装饰器追踪 Agent 的完整执行链路：

```python
@agentlens.agent(name="research_agent")
def research(topic: str) -> str:
    queries = generate_queries(topic)    # 被追踪
    results = search(queries)            # 被追踪
    return summarize(results)            # 被追踪
```

调试面板提供：

- **执行树** — 嵌套的 span 层级，展示完整决策链路
- **时间线瀑布图** — 并行执行可视化
- **Token 和成本统计** — 按调用和按 trace 的 token 明细
- **Span 详情** — 输入/输出 JSON、模型信息、延迟、错误
- **实时流式更新** — 看着 span 随 Agent 运行逐个出现
- **异常高亮** — 失败步骤一目了然

### 第二层：终端用户 Widget 组件

你的用户不应该盲目信任 Agent。用 `@agentlens/widget` 把透明度直接嵌入你的应用：

```tsx
import { AgentLensProvider, StatusStream, ThinkingView, ConfirmDialog } from '@agentlens/widget';

function App() {
  return (
    <AgentLensProvider endpoint="ws://localhost:7600/ws/traces">
      <ThinkingView collapsed={false} />
      <StatusStream maxItems={5} showTimestamp />
      <ConfirmDialog allowReason />
    </AgentLensProvider>
  );
}
```

| 组件 | 功能 |
|------|------|
| `<StatusStream />` | 实时状态流，展示 Agent 当前在做什么 |
| `<ThinkingView />` | Agent 思考过程的逐步展示 |
| `<ConfirmDialog />` | 关键操作暂停，等待人类审批 |

## 人机协作（Human-in-the-Loop）

有些操作不能让 Agent 自动执行。标记 `requires_confirm=True`，Agent 会暂停等待人类批准：

```python
@agentlens.tool(name="deploy", requires_confirm=True)
def deploy(env: str) -> dict:
    return {"status": "deployed", "env": env}
```

当 Agent 执行到确认步骤时，`<ConfirmDialog>` 组件会在用户浏览器中弹出，只有批准后才继续执行。

## 为什么不用 Langfuse / LangSmith？

| | AgentLens | Langfuse | LangSmith |
|---|---|---|---|
| 追踪完整 Agent 逻辑 | 是 | 仅 LLM 调用 | 仅 LangChain |
| 终端用户组件 | 有 | 无 | 无 |
| 人机协作 | 内置 | 无 | 无 |
| 部署方式 | 本地优先 | 需要 Docker | 仅云端 |
| 框架绑定 | 无 | 无 | LangChain |
| 接入成本 | 3 行代码 | Docker + 配置 | 注册 + API Key |

## 快速开始

```bash
pip install agentlens
```

```python
import agentlens
agentlens.init(auto_instrument=["openai"])
# 所有 OpenAI 调用自动被追踪
```

```bash
agentlens serve
# 打开 http://localhost:7600
```

一切在本地运行。无需云服务、无需注册、数据不离开你的机器。
