Metadata-Version: 2.4
Name: ShunX-ai
Version: 1.3.1
Summary: A minimalist library with as few dependencies as possible.
Author-email: Fujiwara Kyokugen <s@shunx.top>
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: numpy; extra == "dev"
Provides-Extra: memory
Requires-Dist: pymilvus>=2.4.0; extra == "memory"
Requires-Dist: sentence-transformers>=2.2.0; extra == "memory"
Dynamic: license-file

# ShunX-ai

前身项目 https://pypi.org/project/kiori/  遵循MIT分发

**ShunX** 是一个极简、高度可扩展的 Python 框架，用于构建基于 SLM/LLM 的 Agent。遵循其设计理念，它不堆砌冗余依赖，只提供干净、可组合的架构。

自 1.2.0 版本起，ShunX 拥抱 **零配置（Zero-Configuration）** 与 **自动自愈（Auto-Healing）**：它依赖现代小语言模型（SLM）的推理能力，并内置了自动纠正模型输出语法错误的机制。

---

## 架构概览

在把 prompt 发送给模型之前，ShunX 会无缝融合多种机制：

1. **长期记忆（LTM）与加权模式匹配**：基于 Milvus Lite，LTM 把历史交互和 few-shot 例子编码成向量存储。新 prompt 到来时，ShunX 执行语义搜索（余弦相似度），高置信度的匹配会被动态复制（加权放大），以显著影响模型的行为。
2. **短期记忆（Replay Buffer）**：保留对话中最近的回合，让模型清楚感知近期上下文。*注意：ShunX 会智能过滤掉损坏的交互，确保你的 SLM 只学到格式完美的例子。*
3. **智能解析器（`ShunXParser`）**：评估 LLM 输出并将其分为三种状态：
   - `SUCCESS`：LLM 输出与预期的 `[ACTION: name, ARGS: {...}]` 格式完全匹配。
   - `NATURAL_CHAT`：LLM 只是在与用户自然对话。
   - `BROKEN_FORMAT`：LLM 尝试执行行动，但 JSON 或方括号语法出错。
4. **自愈循环（Auto-Healing Loop）**：如果 LLM 输出了 `BROKEN_FORMAT`，ShunX 会自动累加重试计数器、追加一条系统观察消息（`[System Observation: ...]`），并立即提示 LLM 自己纠正错误。

---

## 安装

```bash
# 核心极简安装
pip install shunx-ai

# 安装含记忆模块的依赖（pymilvus 与 sentence-transformers）
pip install "shunx-ai[memory]"
```

## 快速开始：端到端流程

下面是一个完整示例，演示如何初始化 Agent、配置记忆、注册行动，并执行用户 prompt。

```python
from shunx_ai.agent import ShunXAgent
from shunx_ai.models import Action, ActionExample
from shunx_ai.memory import MilvusLTM, ReplayBuffer

# 1. 配置记忆模块
ltm = MilvusLTM()  # 自动初始化本地 Milvus Lite 向量库
replay_buffer = ReplayBuffer()

# 2. 往 LTM 里写入先验知识（few-shot 例子）
example = ActionExample(
    user_prompt="Check the server status",
    expected_action_text="[ACTION: get_status, ARGS: {}]"
)
ltm.add_examples([example])

# 3. 初始化 ShunX Agent（零配置！）
agent = ShunXAgent(ltm=ltm, replay_buffer=replay_buffer)

# 4. 定义并注册行动（普通的 Python 可调用对象）
def get_status() -> str:
    return "Server is running smoothly."

agent.add_action(Action("get_status", "Fetches current server status", get_status))

# 5. 提供 LLM 回调函数
def my_llm_callback(prompt: str) -> str:
    # 为演示故意模拟一个损坏的 LLM 响应：
    return 'I will run the command: [ACTION: get_status ARGS: {}' # 缺少逗号和右括号！

# 6. 执行流水线
# ShunX 会自动检测 BROKEN_FORMAT、追加修正提示，
# 并反复调用 `my_llm_callback`，直到输出合法的 SUCCESS 格式或达到 max_retries！
result = agent.run("Is the server okay?", llm_callback=my_llm_callback, max_retries=3)

print(result)
```

## 高级用法

### 聊天模板（适用于经过聊天微调的 SLM）

传入 `chat_format`，让 ShunX 用模型专属模板包装 prompt，并在 assistant 回合开头**预填（prefix-fill）** `[ACTION:` —— 模型只需补全后续内容，可大幅降低格式错误率。

```python
# 支持："gemma"（默认）、"llama3"、"chatml"
agent = ShunXAgent(chat_format="chatml")

result = agent.run("Is the server okay?", llm_callback=my_llm_callback)
```

### 自然语言总结

设置 `summarize_observation=True`，让 LLM 把原始行动结果改写成自然友好的回答（隐藏行动名等技术细节）：

```python
reply = agent.run("Is the server okay?", llm_callback=my_llm_callback, summarize_observation=True)
```

### 静态 Few-shot 例子

即使不配置向量记忆（`ltm`），你也可以手动固定一些总是会被写进 prompt 的例子：

```python
agent = ShunXAgent()
agent.add_example(ActionExample(
    user_prompt="Check the CPU usage",
    expected_action_text="[ACTION: get_cpu, ARGS: {}]"
))
```

`get_context_examples(...)` 也支持在单次调用中覆盖 `threshold`、`max_copies` 和 `sample_n` 参数；不传则使用构造时的默认值。

## 设计理念

ShunX 追求轻量、易懂、不依赖臃肿的外部包。通过保持核心架构的极简，开发者可以自由组合和定制 AI 执行流程，而不被僵化的设计模式束缚。
