# Klynx

[![PyPI version](https://img.shields.io/pypi/v/klynx.svg)](https://pypi.org/project/klynx/)
[![Python versions](https://img.shields.io/pypi/pyversions/klynx.svg)](https://pypi.org/project/klynx/)
[![License](https://img.shields.io/github/license/qzx997/klynx-kit.svg)](https://github.com/qzx997/klynx-kit/blob/main/LICENSE)

> [!WARNING] 
> **当前为测试版本 (Current version is in Beta testing)**
> Klynx 仍在活跃开发中，部分高级功能及 API 不够完善或可能在未来版本发生变动，请谨慎用于生产环境。

**Klynx** is an advanced, highly customizable autonomous agent framework built on top of [LangGraph](https://langchain-ai.github.io/langgraph/) and [LiteLLM](https://github.com/BerriAI/litellm). It is designed to seamless integrate with top-tier LLM providers globally (OpenAI, Anthropic, Google, DeepSeek, Zhipu, Moonshot, etc.) while offering a robust tool-calling infrastructure and built-in interactive terminal interfaces.

## 🚀 Features
- **Universal LLM Routing:** Write code once, use any model. Powered by `litellm`.
- **Advanced Agent Architectures:** Built with `langgraph` core state machines for recursive reasoning, memory, error reflection, and persistent context loops.
- **Robust Tools Environment:** Ships with native tools (e.g. Browser automation with Playwright, OS terminal integration, local filesystem querying).
- **Interactive TUI:** Comes with a built-in rich Text User Interface (`klynx/tui_app.py`) for streaming console interactions.
- **Proxy-Resistant:** `LiteLLM` adapters are configured internally to gracefully map local network environments without throwing blocking SSL errors.

## 📦 Installation

Install Klynx directly from PyPI:

```bash
pip install klynx
```

To update to the latest version, run:
```bash
pip install --upgrade klynx
```

*(Note: If using browser features, remember to run `playwright install chromium` once).*

## ⚡ Quick Start

With Klynx, creating a multi-modal agent and interacting with it requires just a few lines of code.

### 1. Initialize your Model

Klynx expects explicit passing of your API keys or auto-loading from `.env` files. We fully support major models.

```python
import os
from klynx import setup_model, set_tavily_api

# (Optional) Enable web search capabilities globally
set_tavily_api(os.getenv("TAVILY_API_KEY", ""))

# Setup your agent's brain
api_key = os.getenv("DEEPSEEK_API_KEY")
model = setup_model("deepseek", "deepseek-reasoner", api_key)
```

### 2. Create the Agent

Attach your model to a `KlynxAgent` state machine, optionally granting it all system tools.

```python
from klynx import create_agent

# Initialize agent in current directory
agent = create_agent(
    working_dir=os.getcwd(),
    model=model,
    max_iterations=15 
)

# Grant agent access to all default tools (Browser, Files, Terminal, Web Search)
agent.add_tools("all")
```

### 3. Run a Task

There are two primary ways to run instructions: a direct API call or an interactive terminal stream.

#### Option A: Single Invocation (API Level)
Useful when integrating Klynx into your own backend or processing pipeline. It returns the final agent state and summary.

```python
task = "Search the web for the latest Python version changes and write a summary to a file named 'python_updates.md'."
# `invoke` processes the execution loop and streaming yields events
for event in agent.invoke(task):
    event_type = event.get("type", "")
    content = event.get("content", "")
    
    if event_type == "done":
        # Final result state
        if event.get("task_completed"):
            print("Success! Agent Summary:", event.get("summary_content"))
    else:
        print(f"{content}") 
```

#### Option B: Real-time Terminal Streaming
If you want to watch the agent think, execute tools, and log out its process in a beautiful format directly in the console, use `run_terminal_agent_stream`.

```python
from klynx import run_terminal_agent_stream

# Interactive terminal chat loop
while True:
    task = input("\n[User]> ")
    if task.strip().lower() in ["exit", "q", "quit"]:
        break
    
    # This will stream reasoning tags, tool calls, and results to stdout
    result = run_terminal_agent_stream(agent, task, thread_id="my_cli_session")
```

### 4. Built-in TUI App

Klynx includes a powerful Text User Interface for managing and interacting with your agent directly in your terminal without writing CLI scripts.

Launch the interactive app directly from your terminal:
```bash
python -m klynx.tui_app
```

## 📜 License
This software is licensed under the [MIT License](LICENSE).

## 独立可执行程序打包 (Windows)

为了方便将包含 Klynx Agent TUI 的程序直接分发给非技术相关的终端用户，你可以使用 `PyInstaller` 将 TUI 应用一键打包为无需 Python 环境的 `.exe` 可执行文件。

### 打包步骤

1. 确保在包含所有依赖项（`textual`, `langchain`, `litellm` 等）的 Python 虚拟环境中，安装打包工具：
   ```bash
   pip install pyinstaller
   ```
2. 直接在项目根目录双击执行 `build.bat`，或者在终端运行它：
   ```bash
   .\build.bat
   ```
3. 等待编译结束。成功后，可执行文件会被输出到项目根目录下新生成的 `dist\Klynx-Agent.exe` 中。

### 分发与运行说明

- 你可以直接将生成的 `dist\Klynx-Agent.exe` 拷贝并分发到任何 Windows 10/11 这类操作系统中双击运行。
- **环境隔离说明**：该 TUI 具有独立的 API 密钥记忆能力，并且**会在 `.exe` 程序同目录下动态创建并读写 `.env` 文件来实现持久化保存**。
- **注意**：因此，请**避免**将 `.exe` 直接拖动放置在诸如 `C:\Windows`，`Program Files` 等需要高权限写入或者会导致目录权限受限的系统文件夹中运行。通常放置在“桌面”或任何其他的普通用户磁盘目录即可正常实现记忆配置。
