Baize README

项目的 README,来自 github.com/Xu123-Bob/Baize。合并为一个 markdown 文件:README.md。

Baize Logo

Baize

Speak freely, keep secrets sealed

AtomGit    Xu123-Bob%2FBaize | Trendshift

GitHub stars GitHub forks License GitHub release Python 3.10+ 抖音

简体中文 | English | 日本語 | 한국어 | Español | Français | Русский


A security assistant for Vibe Coding and data analysis, inspired by a Chinese mythical beast.

An open-source Coding Agent CLI with strong privacy protection and multilingual interaction. It supports multiple backends (DeepSeek / OpenAI-compatible / Zhipu / Tongyi / Kimi / local Ollama) and provides full capabilities such as tool calling, skill loading, subagent delegation, context compression, and a secure sandbox.

The version with Docker has been added. The Zip file has also been included in the release.

This project has been put to the test in practice by me at the Beijing 2026 AI Youth Hackathon.


Core Advantages

Privacy Protection

Features

Product Introduction

Static website: https://baize-agent-website.pages.dev/

Baize CLI Interface

Baize CLI startup screen

Baize CLI startup screen

Baize CLI running screen -- 01

Baize CLI running screen

Baize CLI running screen -- 02

Baize CLI running screen

Installation

Prerequisites

Install from Source

Two download methods

  1. pip install https://github.com/Xu123-Bob/Baize.git

    bash -- press Win+R, enter cmd, then run:

    baize

  2. On the repository page, click <> Code --> Download ZIP.

(1) After extracting, enter the directory:

bash -- press Win+R, enter cmd

cd path\to\extracted\directory

pip install -r requirements.txt

python -m Baize

After installation, press Win+R, enter cmd, open the CLI, type baize, and run it.

(2) After downloading the ZIP, install locally. Extract it, enter the directory, and run:

bash -- press Win+R, enter cmd

pip install .

After installation, press Win+R, enter cmd, open the CLI, type baize, and run it.

Optional: Install Data Access Dependencies (Important for Data Analysis)

If you need Baize to drive SPSS or SQL databases, install the additional dependencies:

pip install -r requirements-data.txt

requirements-data.txt includes:

Alternatively, if the project is installed via pyproject.toml, you can use extras:

pip install -e ".[data]"          # Install all data access dependencies
pip install -e ".[spss]"          # SPSS only
pip install -e ".[sql]"           # General SQL only
pip install -e ".[sql-mssql]"     # SQL Server only (includes pyodbc)

Optional: Online Deployment

1、Docker Image Setup

curl -fsSL https://get.docker.com | sh
sudo systemctl start docker
sudo systemctl enable docker

2、Deployment Principles

3、Deployment Preview

BaiZe Web startup interface

白泽 web 启动界面

Quick Start

Run with an LLM API

  1. First run
baize

On first run, Baize automatically generates two configuration files:

~/.baize/config.toml   # Backend configuration (choose DeepSeek / OpenAI / Ollama)

~/.baize/.env          # Key file

On Windows, the path is C:\Users\YourUserName\.baize\.

2. Choose a backend

Open ~/.baize/config.toml and modify active_provider (this step is required):

# Baize configuration file
# Modify active_provider to switch backends
# Possible values: "deepseek" / "qwen" / "kimi" / "glm" / "openai" / "ollama"

active_provider = "deepseek"

[model_providers.deepseek]
name = "DeepSeek"
base_url = "https://api.deepseek.com"
env_key = "DEEPSEEK_API_KEY"
model = "deepseek-flash"

[model_providers.qwen]
name = "Qwen"
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
env_key = "DASHSCOPE_API_KEY"
model = "qwen-plus"

[model_providers.kimi]
name = "Kimi"
base_url = "https://api.moonshot.cn/v1"
env_key = "MOONSHOT_API_KEY"
model = "kimi-k2.7-code"

[model_providers.glm]
name = "GLM"
base_url = "https://open.bigmodel.cn/api/paas/v4"
env_key = "ZHIPUAI_API_KEY"
model = "glm-4-plus"

[model_providers.openai]
name = "OpenAI"
base_url = "https://api.openai.com/v1"
env_key = "OPENAI_API_KEY"
model = "gpt-4o"

[model_providers.ollama]
name = "Ollama (local)"
base_url = "http://localhost:11434/v1"
env_key = ""
model = "qwen2.5:7b"

3. Enter your API key

Edit ~/.baize/.env. If you need to use a particular LLM, remove the leading # from that provider's key line, add # in front of the other LLM keys to lock their output, enter the API key, and make sure to save the file. It takes effect only after saving:

# ============================================================
# Baize key file
# ============================================================
# Only fill in the key for the backend you want to use; keep the rest commented out.
# Variable names must match the env_key fields in config.toml.
#
# Location:
#   Linux / macOS: ~/.baize/.env
#   Windows:       C:\Users\YourUserName\.baize\.env
# ============================================================

# ---------- DeepSeek (default backend) ----------
# Get it at: https://platform.deepseek.com/api_keys
DEEPSEEK_API_KEY=

# ---------- OpenAI or any OpenAI-compatible endpoint (optional) ----------
# Suitable for Groq, Tongyi, Moonshot, Zhipu, OpenAI, etc.
# Note: base_url is configured in [model_providers.xxx] in config.toml, not here.
# OPENAI_API_KEY=

# ---------- Tongyi Qianwen (optional) ----------
# Get it at: https://dashscope.console.aliyun.com/
# DASHSCOPE_API_KEY=

# ---------- Kimi / Moonshot (optional) ----------
# Get it at: https://platform.moonshot.cn/console/api-keys
# MOONSHOT_API_KEY=

# ---------- Zhipu GLM (optional) ----------
# Get it at: https://open.bigmodel.cn/usercenter/apikeys
# ZHIPUAI_API_KEY=

# ---------- Custom gateway (optional) ----------
# CUSTOM_API_KEY=

# ---------- Ollama (local model, no key required) ----------
# Just make sure Ollama is running on localhost:11434. No configuration is needed here.
  1. Restart
baize

If you see the black-gold logo and welcome message, startup succeeded.

Ollama Local Models (Zero Cost)

Don't want to use a cloud API? Use local Ollama:

bash

# 1. Install Ollama: https://ollama.com/download
# 2. Pull a model
ollama pull qwen2.5:7b

# 3. Start the Ollama service
ollama serve

# 4. Modify ~/.baize/config.toml
active_provider = "ollama"

# 5. Start Baize
baize

Recommended models: qwen2.5:7b (strong Chinese), llama3.1:8b, deepseek-r1:7b.

Usage Examples

After startup, describe your needs in natural language at the >>> Decree: prompt:

>>> Decree: Write a Python script to scrape Douban Top250 and save it as CSV

>>> Decree: Help me check type errors in all Python files under src/

>>> Decree: Find all places in this repository that use requests and change them to httpx

Multilingual Interaction

Baize supports nine languages: Chinese, English, Japanese, Korean, Spanish, French, German, Russian, and Arabic.

There are two ways to switch:

Method 1: Just Speak (Automatic Detection)

Baize automatically detects the language of your input and switches:

>>> Decree: Hello, help me write a Python script
[System] Detected input language: English. Baize has switched to English interaction.
(Baize replies in English)

>>> Decree: 日本語で答えてください
[System] Detected input language: Japanese. Baize has switched to Japanese interaction.
(Baize replies in Japanese)

Method 2: Manual Command

>>> Decree: /lang                # Show current language and available list
[System] Current language: Chinese (zh)
[System] Available languages:
    zh    Chinese ←
    en    English
    ja    日本語
    ko    한국어
    es    Español
    fr    Français

>>> Decree: /lang English        # Switch by language name
>>> Decree: /lang ja             # Switch by language code
>>> Decree: /lang 西班牙语        # Chinese name also works

Supports language name / language code / Chinese name / native name. For example, to switch to English, any of English, en, 英语, or 英文 works.

Built-in Commands

Data Access Usage Examples

After configuring SPSS / SQL, you can drive them directly with natural language:

>>> Decree: Use SPSS to open data.sav and tell me the variable list and sample size

>>> Decree: Run descriptive statistics on data.sav, then run a linear regression

>>> Decree: Query the sales table for orders with sales amount over 100,000 last month, grouped by customer

>>> Decree: Export the SPSS analysis results to CSV, then join them with customer master data using SQL

Extension Mechanisms

Baize supports four extension mechanisms. Place them in the current working directory and they take effect.

Skills

Write domain knowledge in ./skills/<skill-name>/SKILL.md. The AI will proactively load it when encountering complex tasks.

markdown

---
name: pandas-eda

description: Best practices for exploratory data analysis with pandas

tags: data,python
---

# Pandas EDA Guide

## Core Steps
1. df.info() to inspect field types and missing values
2. df.describe() for statistical description
...

You can also manually load it in the conversation with /pandas-eda.

Subagents

Define specialized subagents in ./subagent/<role-name>/AGENT.md. The main agent can delegate tasks through the agent tool.

markdown

---
name: code-reviewer

description: Strict code reviewer
---

You are a senior code reviewer. During review, prioritize:
1. Boundary conditions and exception handling
2. Resource leaks
3. Concurrency safety
...

Hooks

Place PreToolUse-*.sh, PostToolUse-*.sh, and Stop-*.sh under ./hooks/. They receive JSON input and return a decision:

#!/bin/bash
# PreToolUse-guard.sh
read -r input
if echo "$input" | grep -q "rm -rf"; then
  echo '{"hookSpecificOutput":{"permissionDecision":"block","permissionDecisionReason":"Deletion prohibited"}}'
fi

Python hooks can directly call built-in APIs (see hook_* functions in Baize.py).

MCP Servers

Configure external tool servers in ./MCP/mcp_config.json:

{
  "mcpServers": [
    {
      "name": "filesystem",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
      "env": {},
      "enabled": true
    }
  ]
}

Security Design (Core)

Baize enables the following security mechanisms by default:

If you need to relax restrictions in trusted projects, you can modify ALLOWED_COMMANDS and FORBIDDEN_PATH_PATTERNS in Baize.py.

Privacy Redaction (Core)

Baize includes a built-in bidirectional reversible + disk redaction privacy protection mechanism covering the full path from input to disk:

Disabled by default; enable it when needed.

Two Ways to Enable

Method 1: Natural Language

Say directly in the conversation:

>>> Decree: Enable privacy redaction
[System] Privacy redaction enabled (standard mode).

>>> Decree: Enable strict redaction
[System] Privacy redaction enabled (strict mode).

>>> Decree: Disable privacy protection
[System] Privacy redaction disabled.

Method 2: Slash Commands

Two Modes

Standard: Mainland China mobile numbers, ID card numbers, bank card numbers (Luhn check), emails, IPv4/IPv6, OpenAI/Anthropic/GitHub/AWS API keys, Bearer tokens, private key blocks, password fields, URL credentials.

Strict: All standard rules + Chinese names, QQ numbers, WeChat IDs, mainland China license plate numbers.

How It Works

User input (with real PII) → messages store the original text

↓ sanitize_messages()

What is sent to the LLM is [[PHONE_1]], [[EMAIL_1]]

↓ LLM response

Returned placeholders → restore_message()

Restored to original text → disk write / display / tool execution

Intelligent Grading of Tool Parameters

Redacted (plain-text parameters that do not participate in actual execution):

Not redacted (paths/commands/URLs are actually used):

All redacted on disk write (because disk content is not re-executed, security first).

Disk Redaction

Enabled by default, independent of in-memory redaction. Even if /privacy off is used (no in-memory redaction), disk writes still go through at least the standard rules.

Key characteristics:

How to disable (not recommended): Set PERSIST_REDACT_ENABLED = False in Baize.py.

Example

>>> Decree: /privacy test My phone number is 13812345678, email [email protected]
Original: My phone number is 13812345678, email [email protected]
Redacted: My phone number is [[PHONE_1]], email [[EMAIL_1]]
Restored: My phone number is 13812345678, email [email protected]

>>> Decree: /privacy status
[Privacy Redaction]
Current mode : Standard mode (standard)
Session ID : 7d2f5e91
Enabled rules : 34 / 41
Active placeholders : 2
Mapping capacity : 2 / 2000
TTL : 86400 seconds
LRU evictions : 0
TTL evictions : 0
Sanitize calls: 3
Restore calls: 3

>>> Decree: /privacy rules
[Privacy Redaction Rule List] 41 rules in total
[Standard + Strict]
[✓] phone_cn Mainland China mobile number (standard,strict)
[✓] id_card_cn Mainland China ID card number (standard,strict)
[✓] jwt JWT Token (standard,strict)
...
[Strict only]
[✓] name_cn Chinese name (strict)
[✓] address_cn Chinese detailed address (strict)
...
Usage:
/privacy rule-off <name> disable a rule
/privacy rule-on <name> re-enable a rule

Test Screenshots

Privacy protection test screen -- 01

Privacy protection test screen

Privacy protection test screen -- 02

Privacy protection test screen

Data Access (Core)

Baize connects to enterprise data analysis software through MCP (Model Context Protocol). The main program requires no modification—just register the server in MCP/mcp_config.json.

SPSS Integration

Prerequisites

Configuration Steps

  1. Find the SPSS installation directory: The default path is usually C:\Program Files\IBM\SPSS Statistics\ followed by the version number (e.g. 31).

  2. Set the environment variable (in .env or system environment variables):

SPSS_INSTALL_PATH=C:\Program Files\IBM\SPSS Statistics\31
  1. Verify status:
spss-studio-mcp status

Expected output:

=== SPSS MCP Capability Status ===
pyreadstat : OK v1.3.6
pandas     : OK v3.0.2
SPSS batch : OK
  1. Register it in MCP/mcp_config.json:
{
  "mcpServers": [
    {
      "name": "spss",
      "command": "spss-studio-mcp",
      "args": ["serve", "--transport", "stdio"],
      "env": {
        "SPSS_INSTALL_PATH": "C:\\Program Files\\IBM\\SPSS Statistics\\31"
      },
      "enabled": true
    }
  ]
}

If SPSS batch: NOT FOUND

This means spss-studio-mcp did not find the SPSS engine, but pyreadstat + pandas are working. In this case, it enters file mode:

Solution: Set SPSS_INSTALL_PATH correctly in MCP/mcp_config.json, or accept file-mode degradation.

SQL Integration

Supported Databases

PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, Dameng, Kingbase, TiDB, OceanBase, etc. (based on SQLAlchemy 2.0 drivers).

Configuration Steps

  1. Prepare a read-only database account (strongly recommended):
CREATE USER baize_ro WITH PASSWORD 'xxx';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO baize_ro;
  1. Prepare the connection string:
  1. Register it in MCP/mcp_config.json:
{
  "mcpServers": [
    {
      "name": "sql",
      "command": "atengk-mcp-server-rdbms",
      "args": ["--transport", "stdio"],
      "env": {
        "DATABASE_URL": "postgresql+psycopg://baize_ro:pwd@localhost:5432/prod"
      },
      "enabled": true
    }
  ]
}

Built-in Security Guardrails

atengk-mcp-server-rdbms provides multiple layers of protection:

Configure Multiple Databases at Once

If you want to connect to multiple databases simultaneously, register multiple servers:

{
  "mcpServers": [
    {
      "name": "sql_prod",
      "command": "atengk-mcp-server-rdbms",
      "args": ["--transport", "stdio"],
      "env": { "DATABASE_URL": "postgresql+psycopg://ro:pwd@prod:5432/db" },
      "enabled": true
    },
    {
      "name": "sql_warehouse",
      "command": "atengk-mcp-server-rdbms",
      "args": ["--transport", "stdio"],
      "env": { "DATABASE_URL": "mysql+pymysql://ro:pwd@dw:3306/analytics" },
      "enabled": true
    }
  ]
}

Baize will automatically merge all their tools into MATERTOOLS, and the LLM will select the appropriate one based on the task.

Directory Structure

    baize-agent/
    ├── pyproject.toml              # Packaging configuration
    ├── requirements-data.txt       # Data access dependencies (optional)
    ├── requirements-data           # Access dependencies
    ├── README.md
    ├── tests/                      # Tests (not shipped with the package)
    |   ├── __init__.py
    |   ├── test_history.py
    |   └── test_skill_loader.py
    ├── .env.example                # Environment variable example
    ├── .gitignore
    └── agent/                      # Main package
        ├── logo_*                  # Login screen logo
        ├── LOGO和启动交互界面       # Login screen logo image
        ├── __init__.py             # Version
        ├── Baize.py                # Main program and Agent Loop
        ├── config.py               # Multi-backend configuration loading
        ├── ui_theme.py             # CLI rendering theme
        ├── utils.py                # General utilities
        ├── logo.txt
        ├── skills/                 # Built-in skills
        ├── subagent/               # Built-in subagents
        ├── core/                   # Core logic (side-effect free, unit-testable)
        |   ├── __init__.py
        |   ├── history.py          # Session history cleaning / token estimation / compression
        |   └── privacy.py          # Privacy redaction: PII detection / placeholder replacement / reversible restore
        ├── hooks/                  # Built-in hooks
        └── MCP/                    # MCP client and configuration
            ├── __init__.py
            ├── mcp_client.py       # MCP client
            └── mcp_config.json     # MCP configuration

Environment Variables Reference

Write the above variables to ~/.baize/.env; no shell configuration file changes are needed.

Write the above variables to MCP/mcp_config.json.

Development

Running Tests

This project uses pytest. Before development, install the package in editable mode with development dependencies:

    pip install -e ".[dev]"

Run all tests:

    python -m pytest tests/ -v

Run a single file:

    python -m pytest tests/test_history.py -v

Code Structure Conventions

FAQ

A: In ~/.baize/.env, not the .env in the project root.

A: No. Just change active_provider in ~/.baize/config.toml.

A: No. Set active_provider = "ollama" and leave env_key empty.

A: In the conversation, simply say "switch to /path/to/project", and Baize will call the set_workspace tool.

A: Baize automatically performs two-level compression: first truncating old tool results, then requesting an LLM summary. You can also manually use /compact.

A: The default command allowlist blocks dangerous operations such as rm -rf /; before writing files, it shows a diff and asks for confirmation.

A: 1. Install pip install -r requirements-data.txt; 2. Set the SPSS_INSTALL_PATH environment variable to point to the SPSS installation directory; 3. Enable the spss server in MCP/mcp_config.json. See the "Data Access (SPSS / SQL)" section for details.

A: This means the SPSS engine was not found. Check whether SPSS_INSTALL_PATH correctly points to the directory containing stats.exe; if you only process .sav files, you can ignore this warning (it will fall back to file mode).

A: Install atengk-mcp-server-rdbms at the Python layer (pip install handles it). SQL Server users also need to install Microsoft ODBC Driver 18 at the system level, which cannot be installed via pip.

A: No. SQL MCP only allows SELECT by default and blocks all write operations at the AST syntax-tree level. It is still strongly recommended to create a read-only database account for Baize as a second safeguard.

A: If privacy redaction is enabled (/privacy on), tool results are automatically redacted for phone numbers, emails, ID cards, and other PII before being sent to the LLM. However, it is recommended to also use a read-only database account + data sampling (query only necessary fields) to reduce risk.

A: Because the tool definitions exposed by MCP servers are sent to the LLM with every conversation turn. SPSS has 60+ tools, adding a fixed overhead of about 6,000–12,000 tokens. If your common workflow does not involve SPSS, you can set its enabled to false and turn it on when needed.

Contributing

Issues and PRs are welcome. Please read CONTRIBUTOR.md before submitting a PR.

Thank you to every contributor who submits a PR.

Contributors

License

MIT License

Acknowledgements

☕ Sponsor

If Baize is useful to you, you are welcome to sponsor and support it. Independent development takes a lot of time. Sponsorship will not change the product update schedule. Thank you for your support!

WeChat QR code

Contact Me

WeChat QR code

Scan the WeChat QR code and note "Baize open-source collaboration" or "corporate recruitment".

Douyin QR code

Scan the Douyin QR code to follow.

Baize (Xu123-Bob/Baize)

正在搜索数据库…

这是什么?Baize 是一个开源的 AI 编程代理 CLI,可作为 Claude Code CLI 的直接替代品:你用自然语言描述任务,它替你编写、编辑和运行代码。
它像 Claude Code 那样绑定在一家 AI 提供方上吗?不——它是一个独立的终端代理,只需改一个配置项,就能在 DeepSeek、任何 OpenAI 兼容 API(GLM/Qwen/Kimi/OpenAI)或本地 Ollama 模型之间切换。
怎么安装并开始使用它?用 pip 从源码安装,或从 GitHub 下载 ZIP,然后在终端运行 `baize`;它会在首次运行时自动生成配置文件,并引导你选择后端、输入 API 密钥。
运行它之前我需要准备什么?你需要 Python 3.10+(如果正好是 3.10 还需要 tomli)和 pip,再加上所选后端的 API 密钥——除非你对接本地 Ollama 运行,那样完全不需要密钥。
把代码交给它之前,有什么坑需要知道?默认情况下,命令白名单和路径逃逸检查会拦下 rm -rf / 这类危险操作,但对受信任的项目可以通过直接编辑 Baize.py 放宽限制;写入操作始终会先显示 Diff 并请求确认。
它会把我的个人数据发给 LLM 吗?隐私脱敏默认是关闭的;启用后,它会在发送给 LLM 之前用占位符遮盖电话号码、邮箱、身份证、银行卡和 API 密钥,并在你看到的回复里还原真实值。
Baize 里的 Skills 和 Subagents 是什么?Skills 是带有领域知识的 SKILL.md 文件,Baize 会按需为特定任务加载它们;Subagents 则是单独定义的代理(AGENT.md),主代理可以把复杂工作委托给它们,让它们的上下文不进入主对话。
我能完全离线、免费地运行 Baize 吗?可以——在 config.toml 里把 activeprovider 设为“ollama”,运行 qwen2.5:7b 或 llama3.1:8b 之类的本地模型;不需要 API 密钥,也不需要联网。
对话变得太长时会发生什么?Baize 会自动执行两级上下文压缩——先截断旧的工具结果,再让 LLM 进行总结——你也可以用 /compact 命令手动触发。
我能把 Baize 连接到外部工具吗?可以,通过 Model Context Protocol:在 ./MCP/mcpconfig.json 里配置 GitHub 或 Filesystem 等服务器,Baize 就能在会话期间直接调用它们。
作者
Xu123-Bob
大小
31.9 MB
星标
674
时长
2个月
提交 · 90 天