Metadata-Version: 2.4
Name: llm-log-system
Version: 0.1.0rc1
Summary: Self-hosted LLM observability SDK for Python, LangChain, and LangGraph
Project-URL: Homepage, https://github.com/moshangsang24/llm-log
Project-URL: Documentation, https://github.com/moshangsang24/llm-log#readme
Project-URL: Repository, https://github.com/moshangsang24/llm-log
Project-URL: Issues, https://github.com/moshangsang24/llm-log/issues
Project-URL: Changelog, https://github.com/moshangsang24/llm-log/blob/main/CHANGELOG.md
Author: moshangsang24
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: langchain,langgraph,llm,observability,tracing
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
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 :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.10
Provides-Extra: integrations
Requires-Dist: langchain-core<2,>=0.3.27; extra == 'integrations'
Requires-Dist: langgraph<2,>=0.2.60; extra == 'integrations'
Provides-Extra: langchain
Requires-Dist: langchain-core<2,>=0.3.27; extra == 'langchain'
Provides-Extra: langgraph
Requires-Dist: langchain-core<2,>=0.3.27; extra == 'langgraph'
Requires-Dist: langgraph<2,>=0.2.60; extra == 'langgraph'
Description-Content-Type: text/markdown

# llm-log-system

[![PyPI](https://img.shields.io/pypi/v/llm-log-system?include_prereleases)](https://pypi.org/project/llm-log-system/)
[![Python](https://img.shields.io/pypi/pyversions/llm-log-system)](https://pypi.org/project/llm-log-system/)
[![CI](https://github.com/moshangsang24/llm-log/actions/workflows/ci.yml/badge.svg)](https://github.com/moshangsang24/llm-log/actions/workflows/ci.yml)
[![License](https://img.shields.io/pypi/l/llm-log-system)](https://github.com/moshangsang24/llm-log/blob/main/LICENSE)

面向 Python、LangChain 与 LangGraph 的低侵入大语言模型调用日志与链路追踪 SDK，配合自托管的 [LLM Log System](https://github.com/moshangsang24/llm-log) 服务端使用。

> 当前版本为 `0.1.0rc1` 候选版本，建议先用于评估、集成测试和预发布环境。

## 功能

- 手动创建 Trace、LLM Span 和自定义 Span；
- 自动采集 LangChain chain、LLM、chat model、tool 与 retriever；
- 关联 LangGraph 根图、节点、并行分支和子图；
- 支持同步、异步、流式、异常和取消调用；
- 客户端递归脱敏、正文开关和 UTF-8 字节截断；
- 有界内存队列、后台批量、短超时、有限重试和 gzip；
- 上报故障默认不影响模型调用和业务异常语义；
- 提供无敏感信息的本地诊断计数。

## 安装

安装当前候选版本：

```bash
python -m pip install --pre llm-log-system
```

也可以固定版本：

```bash
python -m pip install "llm-log-system==0.1.0rc1"
```

按使用的框架安装可选依赖：

```bash
python -m pip install "llm-log-system[langchain]==0.1.0rc1"
python -m pip install "llm-log-system[langgraph]==0.1.0rc1"
python -m pip install "llm-log-system[integrations]==0.1.0rc1"
```

手动采集只依赖 `httpx` 和 `pydantic`，不需要安装 LangChain 或 LangGraph。

## 快速开始

先在 Web 控制台创建应用和 API Key，然后配置采集端：

```bash
export LLM_LOG_ENDPOINT=https://logs.example.com
export LLM_LOG_API_KEY=llmlog_your_api_key
export LLM_LOG_ENVIRONMENT=production
```

`LLM_LOG_ENDPOINT` 应填写服务根地址，不要附加 `/api/v1/ingest/spans:batch`。

### 手动采集

```python
from llm_log_system import LLMLogClient

client = LLMLogClient(global_tags={"service": "summary-api"})

try:
    with client.trace("生成摘要"):
        with client.llm_span("provider/model", name="摘要模型") as span:
            prompt = "请总结这段文本"
            span.set_input({"prompt": prompt})

            result = {"content": "这里是模型返回结果"}

            span.set_output(result)
            span.set_usage(input_tokens=12, output_tokens=8, total_tokens=20)
finally:
    client.close()
```

上下文管理器会自动记录开始时间、结束时间、耗时、成功状态和业务异常。需要显式等待后台队列时使用：

```python
client.flush(timeout=5)
```

### LangChain

```python
from llm_log_system import LLMLogClient

client = LLMLogClient()
callback = client.langchain_callback()

result = runnable.invoke(
    {"question": "什么是链路追踪？"},
    config={"callbacks": [callback]},
)

client.close()
```

### LangGraph

```python
from llm_log_system import LLMLogClient

client = LLMLogClient()
callback = client.langchain_callback()

result = graph.invoke(
    {"question": "分析这次工作流"},
    config={"callbacks": [callback]},
)

client.close()
```

异步调用使用框架原生 `ainvoke`，流式调用沿用 `stream` 或 `astream`。同一个回调实例可以关联图、节点、模型、工具、检索器和子图。

## 配置

显式传入 `LLMLogClient` 的参数优先于环境变量。

| 环境变量                  | 默认值        | 说明                      |
| ------------------------- | ------------- | ------------------------- |
| `LLM_LOG_ENDPOINT`        | 无            | LLM Log System 服务根地址 |
| `LLM_LOG_API_KEY`         | 无            | 应用 API Key              |
| `LLM_LOG_ENVIRONMENT`     | `development` | 日志所属环境              |
| `LLM_LOG_ENABLED`         | `true`        | 是否启用采集              |
| `LLM_LOG_CAPTURE_INPUT`   | `true`        | 是否采集输入正文          |
| `LLM_LOG_CAPTURE_OUTPUT`  | `true`        | 是否采集输出正文          |
| `LLM_LOG_MAX_FIELD_BYTES` | `65536`       | 单字段最大 UTF-8 字节数   |
| `LLM_LOG_QUEUE_SIZE`      | `1000`        | 本地有界队列容量          |
| `LLM_LOG_BATCH_SIZE`      | `50`          | 单批最大 Span 数量        |
| `LLM_LOG_GZIP`            | `false`       | 是否压缩批量请求          |

未同时配置 Endpoint 和 API Key 时，SDK 不会启动后台发送线程，手动上下文和业务代码仍可正常执行。

## 隐私与可靠性

- 默认对常见密码、Token、密钥和认证字段进行递归脱敏；
- 使用 `capture_input=False` 或 `capture_output=False` 关闭正文采集；
- 使用 `redaction_patterns` 或 `custom_redactor` 增加业务脱敏规则；
- 队列满时优先保证业务线程，不对模型调用施加无限背压；
- 网络错误、限流和服务端错误仅进行有限次数重试；
- 默认模式下采集错误不会覆盖业务返回值或业务异常；
- `strict=True` 仅适合测试和调试环境。

Prompt、模型响应和 metadata 可能包含业务机密或个人信息。生产接入前应根据自己的数据分类要求关闭不必要的正文采集并配置脱敏规则。

## 诊断

SDK 诊断信息只保留在本地，不会再次上传到采集服务：

```python
diagnostics = client.get_diagnostics()

print(diagnostics.queued)
print(diagnostics.sent)
print(diagnostics.retried)
print(diagnostics.failed)
print(diagnostics.dropped)
```

## 兼容性

- Python 3.10～3.13；
- `langchain-core>=0.3.27,<2`；
- `langgraph>=0.2.60,<2`；
- 未安装框架可选依赖时，核心 SDK 仍可导入和使用。

最低与最新已验证组合见[框架兼容矩阵](https://github.com/moshangsang24/llm-log/blob/main/docs/architecture/%E6%A1%86%E6%9E%B6%E5%85%BC%E5%AE%B9%E7%9F%A9%E9%98%B5.md)。

## 文档与示例

- [项目文档](https://github.com/moshangsang24/llm-log#readme)
- [手动采集示例](https://github.com/moshangsang24/llm-log/tree/main/examples/requests_manual)
- [LangChain 示例](https://github.com/moshangsang24/llm-log/tree/main/examples/langchain_basic)
- [LangGraph 示例](https://github.com/moshangsang24/llm-log/tree/main/examples/langgraph_basic)
- [Span 上报协议](https://github.com/moshangsang24/llm-log/blob/main/docs/api/%E5%8D%8F%E8%AE%AEv1.0.md)
- [变更记录](https://github.com/moshangsang24/llm-log/blob/main/CHANGELOG.md)
- [问题反馈](https://github.com/moshangsang24/llm-log/issues)

## 开发

从源码安装 SDK：

```bash
git clone https://github.com/moshangsang24/llm-log.git
cd llm-log
make setup
make test-sdk
```

提交变更前请阅读[仓库协作指南](https://github.com/moshangsang24/llm-log/blob/main/AGENTS.md)。

## 许可证

本 SDK 基于 [Apache License 2.0](https://github.com/moshangsang24/llm-log/blob/main/LICENSE) 发布，并遵守项目的 [NOTICE](https://github.com/moshangsang24/llm-log/blob/main/NOTICE) 声明。
