Metadata-Version: 2.4
Name: thryve
Version: 0.2.0
Summary: A modular framework for multi-LLM agents, tools, and workflows
License-Expression: MIT
License-File: LICENSE
Keywords: llm,agent,tool-calling,framework,ai
Author: SyJarvis
Author-email: jarvisshangye@gmail.com
Requires-Python: >=3.10
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.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Provides-Extra: all
Provides-Extra: dev
Provides-Extra: llama
Provides-Extra: transformers
Requires-Dist: aiosqlite (>=0.19) ; extra == "all"
Requires-Dist: httpx (>=0.25)
Requires-Dist: llama-cpp-python (>=0.2) ; extra == "llama"
Requires-Dist: openai (>=1.0)
Requires-Dist: pydantic (>=2.0)
Requires-Dist: pydantic-settings (>=2.0)
Requires-Dist: pytest (>=7.0) ; extra == "dev"
Requires-Dist: pytest-asyncio (>=0.21) ; extra == "dev"
Requires-Dist: pyyaml (>=6.0)
Requires-Dist: tiktoken (>=0.5) ; extra == "all"
Requires-Dist: torch (>=2.0) ; extra == "transformers"
Requires-Dist: transformers (>=4.36) ; extra == "transformers"
Project-URL: Homepage, https://github.com/SyJarvis/thryve
Project-URL: Repository, https://github.com/SyJarvis/thryve
Description-Content-Type: text/markdown

# Thryve

[English](README_en.md) | 中文

面向多 LLM Agent、工具调用、上下文管理与 DAG 工作流的模块化 Python 框架。Thryve 将多种后端（OpenAI、Ollama 等）、工具、记忆与 Agent 统一到一套 API 下。

## 特性

- **多后端 LLM/VLM**：OpenAI（对话、视觉、函数调用、嵌入）、Ollama；llama.cpp、Transformers 占位
- **统一消息格式**：文本 + 图像（多模态）、工具调用与结果
- **工具系统**：用 `@tool` 或 `Tool` 定义工具，注册与执行；OpenAI/Anthropic 格式转换
- **Agent 循环**：LLM → 工具调用 → 观察 → 循环，含 doom-loop 检测
- **上下文管理**：消息历史、token 预算、检查点、截断/摘要压缩
- **记忆**：SQLite 索引 + Markdown 记忆片双写，短期按日期分片，手写关键词检索（FTS + 规则重排）
- **DAG 工作流**：图拓扑排序、`LLMNode` / `AgentNode` / `ToolNode`，按层并行执行

## 架构

```
Config (YAML/env) ──► Thryve ──────────────────────────────────────────────► chat / stream / agent / graph
                                │
        ┌───────────────────────┼───────────────────────┐
        ▼                       ▼                       ▼
   AgentLoop              MemoryManager            GraphExecutor
        │                       │                       │
        ├──► ContextManager     ├──► HybridSearcher     (DAG 拓扑执行)
        ├──► ToolRegistry       └──► SQLiteStorage
        │
        └───────────────────────┬───────────────────────┘
                                ▼
                         ProviderAdapter
                                │
              ┌─────────────────┼─────────────────┐
              ▼                 ▼                 ▼
           OpenAI             Ollama        transformers / llama_cpp
```

## 安装

```bash
pip install thryve
```

可选依赖：

```bash
pip install thryve[dev]        # pytest, pytest-asyncio
pip install thryve[all]        # aiosqlite, tiktoken
pip install thryve[transformers]  # HuggingFace Transformers 后端
pip install thryve[llama]       # llama-cpp-python 后端
```

## 快速开始

### 1. 基础对话

设置 API Key 并使用默认配置：

```bash
export OPENAI_API_KEY=sk-...
```

```python
from thryve import Thryve, ThryveConfig

config = ThryveConfig.from_env()  # 读取 OPENAI_API_KEY、THRYVE_* 等
thryve = Thryve(config)
reply = thryve.chat("2 + 2 等于几？")  # 同步，直接返回 str
print(reply)
```

### 2. 显式配置对话

```python
from thryve import Thryve, ThryveConfig, LLMConfig

config = ThryveConfig(
    llm=LLMConfig(
        backend="openai",
        model="kimi-k2-turbo-preview",
        api_key="sk-ffzyxxx...",
        base_url="https://api.moonshot.cn/v1",
        temperature=0.7,
    )
)

thryve = Thryve(config)
reply = thryve.chat("你好！")
```

### 3. 带工具的 Agent

注册工具并让 Agent 调用：

```python
from thryve import Thryve, ThryveConfig, tool

@tool()
def add(a: int, b: int) -> int:
    """两数相加。"""
    return a + b

thryve = Thryve(ThryveConfig.from_env())
thryve.register_tool(add)
result = thryve.chat_with_agent("3 + 5 等于多少？")
print(result.final_response)
print(result.stop_reason)  # 如 COMPLETED
```

### 4. DAG 工作流

构建图并执行：

```python
from thryve import Thryve, ThryveConfig, Graph, FunctionNode

async def step_a(inputs):
    return inputs.get("x", 0) + 1

async def step_b(inputs):
    return inputs.get("step_a", 0) * 2

thryve = Thryve(ThryveConfig.from_env())
g = Graph()
g.chain(
    FunctionNode("step_a", step_a),
    FunctionNode("step_b", step_b),
)
outputs = thryve.execute_graph(g, {"x": 10})
print(outputs["step_a"])  # 11
print(outputs["step_b"])  # 22
```

### 5. 记忆与信息

```python
thryve.add_to_memory("用户偏好深色模式。", permanent=False)
chunks = thryve.search_memory("深色", top_k=5)
info = thryve.get_llm_info()  # provider, model, supports_vision, supports_tools
```

记忆配置示例（短期默认 7 天，按日期切片到 markdown）：

```yaml
memory:
  storage_path: "./data/memory.db"
  markdown_path: "./data/memory"
  short_term_retention_days: 7
  enable_fts: true
```

## 同步与异步

所有公开方法**默认是同步**的，可在 REPL、普通脚本中直接使用。异步版本使用 `_async` 后缀。

| 同步（默认） | 异步 | 说明 |
|---|---|---|
| `chat(message)` | `chat_async(message)` | 对话 |
| `chat_stream(message, callback=...)` | `chat_stream_async(message)` | 流式对话 |
| `chat_with_agent(message)` | `chat_with_agent_async(message)` | Agent 对话 |
| `execute_graph(graph, inputs)` | `execute_graph_async(graph, inputs)` | DAG 工作流 |

```python
# 同步（默认，直接调用）
reply = thryve.chat("你好")

# 异步（在 async def 中）
reply = await thryve.chat_async("你好")
```

## 流式输出

`chat()` / `chat_async()` 会等待完整回复再返回。需要边收边打时使用流式方法：

**同步流式**（默认）：

```python
reply = thryve.chat_stream(
    "什么是大语言模型",
    callback=lambda c: print(c, end="", flush=True),
)
print()  # 换行
# reply 仍是完整回复字符串
```

**异步流式**：

```python
async for chunk in thryve.chat_stream_async("什么是大语言模型"):
    print(chunk, end="", flush=True)
```

## 配置

- **环境变量**：`ThryveConfig.from_env()` 使用 `OPENAI_API_KEY`、`THRYVE_LLM_MODEL`、`THRYVE_LLM_BACKEND`、`THRYVE_MEMORY_PATH` 等。
- **文件**：`ThryveConfig.from_file("config.json")` 读取 JSON 配置。
- **合并**：`config.merge(other)` 用另一份配置覆盖。

### Memory 检索说明

Memory 默认使用**关键词检索**（FTS + 规则重排），不再依赖 embedding model。

## 项目结构

```
src/thryve/
  thryve.py       # Thryve 主入口
  llm.py          # LLM 门面
  config.py       # ThryveConfig, LLMConfig, EmbeddingConfig, MemoryConfig, AgentConfig
  core/
    backends/     # OpenAI, Ollama, llama_capp（占位）, transformers（占位）
    tools/        # Tool, ToolRegistry, ToolExecutor, @tool
    agent/        # Agent, AgentLoop, MultiAgentOrchestrator
    context/      # ContextManager, 检查点, 压缩
    memory/       # MemoryManager, SQLiteStorage, HybridSearcher
    graph/        # Graph, Node, GraphExecutor
```

## 许可证

MIT License

