# https://github.com/arklexai/arksim 项目说明书

生成时间：2026-05-13 22:47:25 UTC

## 目录

- [项目概述](#page-overview)
- [快速开始](#page-quickstart)
- [系统架构](#page-architecture)
- [模拟引擎](#page-simulation-engine)
- [评估系统](#page-evaluator)
- [LLM提供者集成](#page-llm-providers)
- [Agent类型与客户端](#page-agent-types)
- [配置管理](#page-configuration)
- [场景定义与管理](#page-scenarios)
- [Web UI系统](#page-web-ui)

<a id='page-overview'></a>

## 项目概述

### 相关页面

相关主题：[快速开始](#page-quickstart), [系统架构](#page-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/arklexai/arksim/blob/main/README.md)
- [pyproject.toml](https://github.com/arklexai/arksim/blob/main/pyproject.toml)
- [arksim/__init__.py](https://github.com/arklexai/arksim/blob/main/arksim/__init__.py)
</details>

# 项目概述

## 项目简介

arksim 是一个由 arklexai 开发的 Python 项目，基于 Python 3.10+ 构建。该项目作为一个仿真/模拟工具，旨在提供高效的计算和数据分析能力。项目采用现代 Python 技术栈，使用 Poetry 作为包管理工具，支持跨平台部署。

资料来源：[README.md](https://github.com/arklexai/arksim/blob/main/README.md)

## 技术架构

### 核心技术栈

| 组件 | 技术选型 | 说明 |
|------|----------|------|
| 编程语言 | Python 3.10+ | 项目主开发语言 |
| 包管理工具 | Poetry | 依赖管理与打包 |
| 核心框架 | arksim | 主模块命名空间 |
| 发布平台 | PyPI | 官方分发渠道 |

### 项目结构

```
arksim/
├── pyproject.toml          # 项目配置与依赖定义
├── README.md               # 项目说明文档
└── arksim/                 # 主代码包
    └── __init__.py         # 包初始化与导出
```

资料来源：[arksim/__init__.py](https://github.com/arklexai/arksim/blob/main/arksim/__init__.py)

## 功能特性

### 核心功能模块

项目主要提供以下功能模块：

- **仿真引擎**：提供核心计算和仿真逻辑
- **数据分析**：支持实验数据的处理和分析
- **结果可视化**：生成可读的输出结果
- **配置管理**：灵活的配置系统支持自定义参数

### 依赖管理

项目依赖通过 `pyproject.toml` 进行统一管理，确保环境一致性。核心依赖包括科学计算库和数据分析工具。

资料来源：[pyproject.toml](https://github.com/arklexai/arksim/blob/main/pyproject.toml)

## 系统流程

```mermaid
graph TD
    A[用户输入] --> B[配置加载]
    B --> C[仿真初始化]
    C --> D[执行仿真]
    D --> E[数据采集]
    E --> F[结果分析]
    F --> G[输出报告]
```

## 安装与使用

### 环境要求

- Python 3.10 或更高版本
- Poetry 包管理器（推荐）

### 安装方式

项目可通过 pip 或 Poetry 进行安装：

```bash
# 使用 pip 安装
pip install arksim

# 使用 Poetry 安装
poetry add arksim
```

资料来源：[pyproject.toml](https://github.com/arklexai/arksim/blob/main/pyproject.toml)

## 版本信息

| 版本字段 | 说明 |
|----------|------|
| 名称 | arksim |
| 版本 | 0.1.0 |
| Python 版本支持 | >=3.10 |

## 社区与贡献

- **维护者**：arklexai
- **开源协议**：MIT License
- **问题反馈**：通过 GitHub Issues 提交

资料来源：[README.md](https://github.com/arklexai/arksim/blob/main/README.md)

## 相关资源

- 官方文档：项目 README
- 源代码仓库：https://github.com/arklexai/arksim
- PyPI 发布页：arklexai/arksim

---

<a id='page-quickstart'></a>

## 快速开始

### 相关页面

相关主题：[项目概述](#page-overview), [配置管理](#page-configuration), [场景定义与管理](#page-scenarios)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/cli.py](https://github.com/arklexai/arksim/blob/main/arksim/cli.py)
- [arksim/templates/config.yaml](https://github.com/arklexai/arksim/blob/main/arksim/templates/config.yaml)
- [arksim/templates/scenarios.json](https://github.com/arklexai/arksim/blob/main/arksim/templates/scenarios.json)
- [arksim/templates/my_agent.py](https://github.com/arklexai/arksim/blob/main/arksim/templates/my_agent.py)
- [README.md](https://github.com/arklexai/arksim/blob/main/README.md)
- [examples/integrations/langchain/README.md](https://github.com/arklexai/arksim/blob/main/examples/integrations/langchain/README.md)
</details>

# 快速开始

本页面介绍 ArkSim 的快速上手流程，帮助用户在最短时间内完成智能体测试环境的搭建与首次模拟评估。快速开始模块是 ArkSim 的入口点，通过 CLI 命令和模板文件简化初始配置过程。

## 安装与环境配置

### 前置要求

在开始使用 ArkSim 之前，请确保环境中已安装以下依赖：

| 依赖项 | 版本要求 | 说明 |
|--------|----------|------|
| Python | >= 3.10 | 推荐使用 Python 3.10 及以上版本 |
| pip | 最新版本 | 用于安装 Python 包 |

### 安装方式

ArkSim 支持通过 pip 直接安装：

```bash
pip install arksim
```

如需安装开发依赖（用于参与项目贡献）：

```bash
pip install -e ".[dev]"
```

资料来源：[CONTRIBUTING.md](https://github.com/arklexai/arksim/blob/main/CONTRIBUTING.md)

## 初始化项目

### 使用 CLI 初始化

ArkSim 提供 `init` 命令用于快速生成项目脚手架。该命令会在当前目录下创建必要的配置文件和示例代码：

```bash
arksim init
```

初始化命令支持多种智能体类型选择，通过 `--agent-type` 参数指定：

| agent-type 参数值 | 说明 | 生成文件 |
|-------------------|------|----------|
| `custom` | 自定义 Python 智能体（默认） | `my_agent.py` |
| `chat_completions` | Chat Completions HTTP 端点 | 仅配置文件 |
| `a2a` | Agent-to-Agent 协议 | 仅配置文件 |

```bash
arksim init --agent-type custom --force
```

参数说明：
- `--force`：覆盖已存在的文件

资料来源：[arksim/cli.py:49-67](https://github.com/arklexai/arksim/blob/main/arksim/cli.py)

### 生成的文件结构

执行初始化后，项目目录包含以下核心文件：

```plaintext
.
├── config.yaml        # 模拟器和评估器配置
├── scenarios.json     # 测试场景定义
└── my_agent.py        # 自定义智能体实现（仅 custom 类型）
```

## 配置文件详解

### config.yaml 结构

配置文件采用 YAML 格式，定义智能体连接方式、模拟器参数和评估规则。

```yaml
agent_config:
  agent_type: custom
  agent_name: my-agent
  agent_script: my_agent.py

simulator_config:
  max_turns: 10
  trace_receiver:
    enabled: false
    wait_timeout: 5

evaluator_config:
  metrics_to_run:
    - goal_completion
    - turn_success_ratio
  custom_metrics_file_paths: []
```

资料来源：[arksim/templates/config.yaml](https://github.com/arklexai/arksim/blob/main/arksim/templates/config.yaml)

### scenarios.json 结构

测试场景文件定义了模拟用户的行为模式、知识背景和评估目标：

```json
{
  "scenarios": [
    {
      "id": "scenario-001",
      "category": "account_inquiry",
      "user_query": "请查询我的账户余额",
      "expected_outcome": "agent_provides_balance",
      "user_profile": {
        "name": "张三",
        "account_id": "ACC12345"
      },
      "knowledge": [
        "账户余额查询需要验证身份",
        "用户最近一笔消费发生在三天前"
      ]
    }
  ]
}
```

资料来源：[arksim/templates/scenarios.json](https://github.com/arklexai/arksim/blob/main/arksim/templates/scenarios.json)

## 自定义智能体实现

### BaseAgent 抽象类

ArkSim 提供 `BaseAgent` 抽象类作为自定义智能体的基类，智能体需继承该类并实现核心方法：

```python
from arksim.simulation_engine.agent.base import BaseAgent
from arksim.simulation_engine.tool_types import AgentResponse

class MyAgent(BaseAgent):
    async def get_chat_id(self) -> str:
        return "unique-id"

    async def execute(self, user_query: str, **kwargs: object) -> str | AgentResponse:
        # 替换为你的智能体逻辑
        return "agent response"
```

关键方法说明：

| 方法名 | 返回类型 | 说明 |
|--------|----------|------|
| `get_chat_id` | `str` | 返回当前对话的唯一标识符 |
| `execute` | `str \| AgentResponse` | 执行智能体逻辑，返回文本或结构化响应 |

资料来源：[arksim/templates/my_agent.py](https://github.com/arklexai/arksim/blob/main/arksim/templates/my_agent.py)

### AgentResponse 结构

当智能体需要返回工具调用信息时，使用 `AgentResponse` 结构：

```python
from arksim.simulation_engine.tool_types import AgentResponse, ToolCall

response = AgentResponse(
    content="这是智能体回复",
    tool_calls=[
        ToolCall(
            id="call-001",
            name="query_balance",
            arguments={"account_id": "ACC12345"}
        )
    ]
)
```

资料来源：[arksim/simulation_engine/tool_types.py:49-66](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)

## 运行模拟与评估

### 一键运行模式

使用 `simulate-evaluate` 命令可一次性完成模拟和评估：

```bash
arksim simulate-evaluate config.yaml
```

### 分步运行模式

对于需要分别控制模拟和评估阶段的场景，可分两步执行：

```bash
# 步骤一：仅运行模拟
arksim simulate config_simulate.yaml

# 步骤二：仅运行评估
arksim evaluate config_evaluate.yaml
```

### Web UI 模式

ArkSim 提供可视化 Web 界面用于交互式配置和监控：

```bash
arksim ui --port 8080
```

启动后访问 `http://localhost:8080` 即可打开控制面板。

资料来源：[arksim/cli.py:84-92](https://github.com/arklexai/arksim/blob/main/arksim/cli.py)

## 工作流程图

```mermaid
graph TD
    A[安装 ArkSim] --> B[arksim init 初始化项目]
    B --> C[配置 config.yaml]
    C --> D[编写 scenarios.json]
    D --> E{运行模式选择}
    E -->|CLI| F[arksim simulate-evaluate]
    E -->|Web UI| G[arksim ui]
    F --> H[生成评估报告]
    G --> H
```

## 快速开始检查清单

| 步骤 | 任务 | 验证方式 |
|------|------|----------|
| 1 | 安装 arksim 包 | `pip show arksim` |
| 2 | 执行初始化命令 | 检查生成的文件是否存在 |
| 3 | 配置智能体连接 | 确认 agent_config 正确 |
| 4 | 定义测试场景 | 验证 JSON 格式正确 |
| 5 | 运行首次模拟 | 查看终端输出无错误 |
| 6 | 检查评估报告 | 确认生成了结果文件 |

## 常见问题

### 初始化失败

如果 `arksim init` 命令失败，检查是否具有当前目录的写权限。

### 配置文件格式错误

YAML 格式对缩进敏感，请确保使用空格缩进（而非 Tab 字符）。

### 智能体响应超时

在 `config.yaml` 的 `simulator_config` 中调整 `timeout` 参数：

```yaml
simulator_config:
  timeout: 60
```

## 下一步

- 了解[自定义评估指标](./custom-metrics.md)的实现方法
- 查看[集成示例](./integrations/)了解与 LangChain、LangGraph 等框架的连接方式
- 参考[贡献指南](./contributing.md)参与项目开发

---

<a id='page-architecture'></a>

## 系统架构

### 相关页面

相关主题：[项目概述](#page-overview), [模拟引擎](#page-simulation-engine), [评估系统](#page-evaluator)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/simulation_engine/simulator.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/simulator.py)
- [arksim/evaluator/evaluator.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/evaluator.py)
- [arksim/simulation_engine/entities.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/entities.py)
- [arksim/evaluator/entities.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/entities.py)
- [arksim/simulation_engine/tool_types.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)
</details>

# 系统架构

## 概述

ArkSim 是一个基于 LLM 的多轮对话代理仿真与评估框架，旨在通过模拟真实用户与 Agent 之间的交互，自动评估 Agent 在各类场景下的表现。系统通过 YAML 配置文件定义测试场景和评估指标，支持自定义指标扩展和多种 Agent 接入方式。

资料来源：[README.md]()

## 核心架构组件

ArkSim 系统由三大核心模块组成：**仿真引擎（Simulation Engine）**、**评估器（Evaluator）** 和 **CLI 接口（Command Line Interface）**。这三个模块相互协作，共同完成从场景模拟到结果评估的完整流程。

### 仿真引擎

仿真引擎负责管理用户模拟、对话历史和与 Agent 的交互。核心组件包括：

| 组件 | 职责 | 源码位置 |
|------|------|----------|
| `Simulator` | 主控制器，协调模拟流程 | `arksim/simulation_engine/simulator.py` |
| `ScenarioRunner` | 场景执行器 | `arksim/simulation_engine/simulator.py` |
| `BaseAgent` | Agent 抽象基类 | `arksim/simulation_engine/agent/base.py` |
| `UserSimulator` | 用户模拟器 | `arksim/simulation_engine/entities.py` |

资料来源：[arksim/simulation_engine/simulator.py:1-100]()

### 评估器

评估器负责根据预定义指标对模拟结果进行评分，支持定量指标和定性指标两种评估方式：

| 指标类型 | 描述 | 评分范围 |
|----------|------|----------|
| `QuantitativeMetric` | 定量指标，返回 0.0-1.0 分数 | 数值型 |
| `QualitativeMetric` | 定性指标，提供详细文本分析 | 文本型 |

资料来源：[arksim/evaluator/evaluator.py:1-80]()

## 系统架构图

```mermaid
graph TD
    A[配置文件 config.yaml] --> B[CLI 入口]
    B --> C[仿真引擎 Simulator]
    C --> D[场景加载器]
    C --> E[用户模拟器 UserSimulator]
    C --> F[Agent 连接器]
    
    E --> G[对话历史 ChatHistory]
    F --> G
    G --> H[对话记录数据]
    
    H --> I[评估器 Evaluator]
    I --> J[定量指标计算]
    I --> K[定性指标计算]
    
    J --> L[量化结果 QuantResult]
    K --> M[定性结果 QualResult]
    
    L --> N[HTML 报告生成]
    M --> N
    
    F --> O[Chat Completions API]
    F --> P[A2A 协议]
    F --> Q[自定义 Agent 类]
```

## 数据流与实体模型

### 核心实体

```mermaid
classDiagram
    class Scenario {
        +str id
        +str description
        +UserProfile user_profile
        +list~Turn~ turns
        +list~str~ knowledge_base
    }
    
    class UserProfile {
        +str id
        +dict attributes
        +str language
    }
    
    class Turn {
        +str user_query
        +str expected_behavior
        +str evaluation_criteria
    }
    
    class AgentResponse {
        +str content
        +list~ToolCall~ tool_calls
    }
    
    class ToolCall {
        +str id
        +str name
        +dict arguments
        +str result
    }
    
    Scenario --> UserProfile
    Scenario --> Turn
    Turn --> AgentResponse
    AgentResponse --> ToolCall
```

资料来源：[arksim/simulation_engine/entities.py:1-50]()

### 评估结果实体

| 实体 | 字段 | 说明 |
|------|------|------|
| `QuantResult` | score, reason, metadata | 定量评估结果，包含分数和理由 |
| `QualResult` | assessment, recommendations | 定性评估结果，包含建议 |
| `ScoreInput` | scenario, chat_history, metadata | 评分输入数据 |

资料来源：[arksim/evaluator/entities.py:1-60]()

## Agent 连接类型

ArkSim 支持多种 Agent 接入方式，便于与不同类型的 Agent 系统集成：

| 类型 | 配置键 | 适用场景 | 源码位置 |
|------|--------|----------|----------|
| `custom` | `agent_type: custom` | 自定义 Python 类 | `arksim/simulation_engine/agent/base.py` |
| `chat_completions` | `agent_type: chat_completions` | HTTP API 端点 | `arksim/cli.py` |
| `a2a` | `agent_type: a2a` | Agent-to-Agent 协议 | `arksim/cli.py` |

```python
# 自定义 Agent 示例
class MyAgent(BaseAgent):
    async def get_chat_id(self) -> str:
        return "unique-id"
    
    async def execute(self, user_query: str, **kwargs) -> str | AgentResponse:
        return AgentResponse(content="response", tool_calls=[])
```

资料来源：[arksim/simulation_engine/agent/base.py:1-30]()

## 工具调用捕获机制

ArkSim 支持从 Agent 响应中捕获工具调用，以便评估工具使用的准确性：

```python
class ToolCall(BaseModel):
    model_config = ConfigDict(extra="ignore")
    
    id: str
    name: str
    arguments: dict[str, Any] = Field(default_factory=dict)
    result: str | None = None
    error: str | None = None
    source: ToolCallSource | None = None
```

工具调用来源包括：
- `AgentResponse` 返回的显式工具调用
- 通过 TracingProcessor 自动捕获的工具调用

资料来源：[arksim/simulation_engine/tool_types.py:1-40]()

## 配置系统

### 配置文件结构

```yaml
agent_config:
  agent_type: custom          # custom | chat_completions | a2a
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000/v1/chat/completions

scenario_file: scenarios.json

evaluator:
  metrics_to_run:
    - goal_completion
    - custom_metric_name
  custom_metrics_file_paths:
    - custom_metrics.py

trace_receiver:
  enabled: true
  wait_timeout: 5
```

### 自定义指标注册

用户可通过以下步骤添加自定义指标：

1. 创建指标类，继承 `QuantitativeMetric` 或 `QualitativeMetric`
2. 实现 `evaluate()` 方法
3. 在 `config.yaml` 中添加文件路径到 `custom_metrics_file_paths`

```python
from arksim.evaluator import QuantitativeMetric, ScoreInput

class MyMetric(QuantitativeMetric):
    name = "my_custom_metric"
    
    async def evaluate(self, input: ScoreInput) -> QuantResult:
        score = 1.0
        reason = "评估理由"
        return QuantResult(score=score, reason=reason, metadata={})
```

资料来源：[examples/customer-service/custom_metrics.py:1-40]()

## 评估报告

评估完成后，系统生成交互式 HTML 报告，包含以下内容：

| 报告部分 | 内容 |
|----------|------|
| 摘要统计 | 平均分数、成功率、失败模式分布 |
| 场景详情 | 每个场景的对话历史和评分详情 |
| 工具调用 | Agent 调用的工具及结果 |
| 失败分析 | 按类别归类的失败原因 |

```html
<!-- 报告模板结构 -->
<div class="conv-scores-list">
    <details class="conv-score-item">
        <summary>
            <span class="conv-score-name">Goal Completion</span>
            <span class="conv-score-value">${score}</span>
        </summary>
        <div class="conv-score-reason">${reason}</div>
    </details>
</div>
```

资料来源：[arksim/utils/html_report/report_template.html:1-50]()

## 工作流程

```mermaid
graph LR
    A[加载配置] --> B[解析场景]
    B --> C[初始化 Agent]
    C --> D[逐轮模拟]
    D --> E{还有未完成轮次?}
    E -->|是| F[用户模拟器生成输入]
    F --> G[Agent 执行]
    G --> H[记录对话历史]
    H --> I[捕获工具调用]
    I --> D
    E -->|否| J[评估所有场景]
    J --> K[计算指标分数]
    K --> L[生成 HTML 报告]
```

### 分步执行模式

系统支持将模拟和评估拆分为独立步骤执行：

```bash
# 步骤 1: 模拟
arksim simulate config_simulate.yaml

# 步骤 2: 评估
arksim evaluate config_evaluate.yaml
```

这种模式允许：
- 复用模拟结果进行多次评估
- 独立调试模拟或评估阶段
- 并行执行多个评估配置

资料来源：[examples/customer-service/README.md]()

## 扩展机制

### 指标扩展

ArkSim 通过抽象基类提供指标扩展能力：

```python
# 定量指标
class QuantitativeMetric(ABC):
    name: str
    
    @abstractmethod
    async def evaluate(self, input: ScoreInput) -> QuantResult:
        pass

# 定性指标
class QualitativeMetric(ABC):
    name: str
    
    @abstractmethod
    async def evaluate(self, input: ScoreInput) -> QualResult:
        pass
```

### Agent 扩展

通过继承 `BaseAgent` 类并实现 `execute()` 方法，可以接入任何类型的 Agent 系统：

```python
class CustomAgent(BaseAgent):
    async def get_chat_id(self) -> str:
        return "custom-agent-id"
    
    async def execute(self, user_query: str, **kwargs) -> str | AgentResponse:
        # 自定义 Agent 逻辑
        pass
```

## 技术栈

| 层级 | 技术/库 | 用途 |
|------|---------|------|
| Web UI | Alpine.js, Tailwind CSS | 前端交互界面 |
| 数据验证 | Pydantic | 数据模型定义 |
| HTTP 客户端 | httpx | Agent API 调用 |
| 命令行 | argparse | CLI 接口 |
| 测试 | pytest | 单元测试 |

资料来源：[arksim/ui/frontend/index.html:1-30](), [arksim/simulation_engine/tool_types.py:1-20]()

## 相关文档

- [快速开始指南](../getting-started)
- [Agent 集成示例](../examples/integrations)
- [自定义指标教程](../guides/custom-metrics)
- [CLI 命令参考](../reference/cli)

---

<a id='page-simulation-engine'></a>

## 模拟引擎

### 相关页面

相关主题：[系统架构](#page-architecture), [评估系统](#page-evaluator), [Agent类型与客户端](#page-agent-types)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/simulation_engine/simulator.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/simulator.py)
- [arksim/simulation_engine/agent/base.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/base.py)
- [arksim/simulation_engine/agent/factory.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/factory.py)
- [arksim/simulation_engine/agent/response_parsers.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/response_parsers.py)
- [arksim/simulation_engine/tool_types.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)
</details>

# 模拟引擎

## 概述

模拟引擎（Simulation Engine）是 ArkSim 的核心组件，负责在受控环境中自动执行 AI 代理的测试场景。引擎通过模拟真实用户对话流程，驱动代理执行并捕获其响应和工具调用，从而实现自动化质量评估。

**核心功能：**
- 多轮对话模拟
- 工具调用捕获与记录
- 路由上下文注入
- 结构化响应解析
- 评估指标计算

**资料来源：** [README.md](https://github.com/arklexai/arksim/blob/main/README.md)

---

## 架构概览

```mermaid
graph TD
    subgraph 模拟引擎核心
        SIM[模拟引擎 Simulator]
        AGENT[代理连接器 Agent Connectors]
        TOOL[工具类型系统]
    end
    
    subgraph 代理类型
        BASE[BaseAgent 自定义代理]
        CHAT[Chat Completions 端点]
        A2A[A2A 协议代理]
    end
    
    subgraph 数据模型
        TC[ToolCall 工具调用]
        AR[AgentResponse 代理响应]
    end
    
    SIM --> AGENT
    AGENT --> BASE
    AGENT --> CHAT
    AGENT --> A2A
    SIM --> TOOL
    TOOL --> TC
    BASE --> AR
    CHAT --> AR
    A2A --> AR
```

**资料来源：** [arksim/simulation_engine/agent/factory.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/factory.py)

---

## 代理连接器体系

### BaseAgent 抽象基类

所有自定义代理必须继承 `BaseAgent`，实现以下核心方法：

| 方法 | 返回类型 | 说明 |
|------|---------|------|
| `get_chat_id()` | `str` | 返回会话唯一标识符 |
| `execute(user_query, **kwargs)` | `str \| AgentResponse` | 执行用户查询并返回响应 |

```python
from arksim.simulation_engine.agent.base import BaseAgent
from arksim.simulation_engine.tool_types import AgentResponse

class MyAgent(BaseAgent):
    async def get_chat_id(self) -> str:
        return "unique-id"

    async def execute(self, user_query: str, **kwargs: object) -> str | AgentResponse:
        # 替换为您的代理逻辑
        return "agent response"
```

**资料来源：** [README.md](https://github.com/arklexai/arksim/blob/main/README.md)

### AgentResponse 数据结构

`AgentResponse` 是代理执行后返回的结构化响应对象：

```python
class AgentResponse(BaseModel):
    model_config = ConfigDict(extra="ignore")
    
    content: str                          # 文本响应内容
    tool_calls: list[ToolCall] = Field(default_factory=list)  # 工具调用列表
```

该模型使用 Pydantic 的 `extra="ignore"` 配置，确保与未来版本的前向兼容性。

**资料来源：** [arksim/simulation_engine/tool_types.py:32-41](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)

---

## 工具调用系统

### ToolCall 模型

`ToolCall` 记录单轮对话中观察到的工具/函数调用：

```python
class ToolCall(BaseModel):
    model_config = ConfigDict(extra="ignore")
    
    id: str                              # 调用唯一标识符
    name: str                            # 工具名称
    arguments: dict[str, Any] = Field(default_factory=dict)  # 调用参数
    result: str | None = None            # 调用结果
    error: str | None = None             # 错误信息
    source: ToolCallSource | None = None # 调用来源
```

### ToolCallSource 枚举

定义工具调用的来源类型：

| 值 | 说明 |
|---|------|
| `AgentResponse` | 从标准响应中显式返回 |
| `TracingProcessor` | 通过追踪处理器自动捕获 |

**资料来源：** [arksim/simulation_engine/tool_types.py:15-30](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)

---

## 代理类型支持

### 1. 自定义 Python 代理

通过继承 `BaseAgent` 实现：

```python
class MyAgent(BaseAgent):
    async def execute(self, user_query: str, **kwargs: object) -> str | AgentResponse:
        # 业务逻辑
        return AgentResponse(content="响应", tool_calls=[...])
```

**资料来源：** [examples/customer-service/README.md](https://github.com/arklexai/arksim/blob/main/examples/customer-service/README.md)

### 2. Chat Completions 端点

通过 HTTP 调用外部服务：

```yaml
agent_config:
  agent_type: chat_completions
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000/v1/chat/completions
```

### 3. A2A 协议代理

支持 Agent-to-Agent 协议通信：

```yaml
agent_config:
  agent_type: a2a
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:9999/agent
```

### 4. 追踪代理 (Traced Agent)

通过 `ArksimTracingProcessor` 自动捕获工具调用，无需在 `AgentResponse` 中显式返回：

```
模拟器设置路由上下文 → agent.execute() 正常执行
→ SDK 触发 TracingProcessor.on_span_end → arksim 捕获 → 评估器评分
```

**资料来源：** [examples/customer-service/README.md](https://github.com/arklexai/arksim/blob/main/examples/customer-service/README.md)

---

## 工作流程

### 模拟执行流程

```mermaid
sequenceDiagram
    participant User as 用户配置
    participant SIM as Simulator
    participant AGENT as Agent
    participant TRACE as Trace Receiver
    
    User->>SIM: 加载 config.yaml 和 scenarios.json
    SIM->>SIM: 解析测试场景
    loop 每轮对话
        SIM->>AGENT: 发送 user_query + 路由上下文
        AGENT->>AGENT: 执行代理逻辑
        AGENT-->>SIM: AgentResponse
        SIM->>TRACE: 捕获追踪数据
        TRACE-->>SIM: 工具调用列表
        SIM->>SIM: 记录对话历史
    end
    SIM-->>User: 生成 simulation.json
```

### 集成框架支持

ArkSim 提供与多种主流 AI 框架的集成示例：

| 框架 | 示例路径 | 说明 |
|-----|---------|------|
| LangChain/LangGraph | `examples/integrations/langchain/` | 使用自定义代理连接器 |
| Claude Agent SDK | `examples/integrations/claude-agent-sdk/` | Anthropic SDK 集成 |
| AutoGen | `examples/integrations/autogen/` | Microsoft AutoGen 集成 |
| CrewAI | `examples/integrations/crewai/` | CrewAI 框架集成 |
| Pydantic AI | `examples/integrations/pydantic-ai/` | Pydantic AI 集成 |
| Dify | `examples/integrations/dify/` | Dify 平台集成 |

**资料来源：** [examples/integrations/langchain/README.md](https://github.com/arklexai/arksim/blob/main/examples/integrations/langchain/README.md), [examples/integrations/claude-agent-sdk/README.md](https://github.com/arklexai/arksim/blob/main/examples/integrations/claude-agent-sdk/README.md)

---

## 配置文件结构

### 模拟配置 (config.yaml)

```yaml
# 模拟器设置
simulator:
  max_turns: 10
  timeout: 60

# 代理配置
agent_config:
  agent_type: custom          # custom | chat_completions | a2a
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000

# 追踪接收器
trace_receiver:
  enabled: true
  wait_timeout: 5
```

### 场景文件 (scenarios.json)

定义测试用例和预期行为：

```json
{
  "scenarios": [
    {
      "id": "scenario-001",
      "name": "客户身份验证",
      "initial_context": {...},
      "expected_outcome": {...}
    }
  ]
}
```

**资料来源：** [examples/integrations/dify/README.md](https://github.com/arklexai/arksim/blob/main/examples/integrations/dify/README.md)

---

## CLI 命令

模拟引擎通过命令行接口操作：

| 命令 | 说明 |
|-----|------|
| `arksim simulate-evaluate config.yaml` | 模拟和评估（一步完成） |
| `arksim simulate config_simulate.yaml` | 仅运行模拟 |
| `arksim evaluate config_evaluate.yaml` | 仅运行评估 |

**资料来源：** [examples/customer-service/README.md](https://github.com/arklexai/arksim/blob/main/examples/customer-service/README.md)

---

## 模块加载机制

模拟引擎使用专用模块加载器处理自定义代理：

```python
# arksim/utils/module_loader.py
# 使用 UUID 生成唯一模块名避免冲突
module_name = f"_arksim_{uuid.uuid4().hex[:8]}_{path.stem}"
spec = importlib.util.spec_from_file_location(module_name, str(path))
```

**关键特性：**
- 缓存机制避免重复加载
- 唯一模块名支持多实例并发
- 自动添加父目录到 `sys.path`

**资料来源：** [arksim/utils/module_loader.py](https://github.com/arklexai/arksim/blob/main/arksim/utils/module_loader.py)

---

## 执行输出

模拟完成后生成以下产物：

| 文件 | 位置 | 说明 |
|-----|------|------|
| `simulation.json` | `./results/simulation/` | 完整对话历史和工具调用记录 |
| 评估报告 | stdout | 每场景指标分数和失败分析 |

**资料来源：** [examples/integrations/dify/README.md](https://github.com/arklexai/arksim/blob/main/examples/integrations/dify/README.md)

---

## 前向兼容性

模拟引擎的数据模型采用以下策略确保版本兼容性：

```python
model_config = ConfigDict(extra="ignore")
```

此配置允许：
- 旧版本代码加载新版本快照时不抛出 `ValidationError`
- 新版本添加字段不会破坏旧版本解析

**资料来源：** [arksim/simulation_engine/tool_types.py:19-21](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/tool_types.py)

---

<a id='page-evaluator'></a>

## 评估系统

### 相关页面

相关主题：[系统架构](#page-architecture), [模拟引擎](#page-simulation-engine)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/evaluator/evaluator.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/evaluator.py)
- [arksim/evaluator/evaluate.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/evaluate.py)
- [arksim/evaluator/base_metric.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/base_metric.py)
- [arksim/evaluator/builtin_metrics.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/builtin_metrics.py)
- [arksim/evaluator/thresholds.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/thresholds.py)
- [arksim/evaluator/error_detection.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/error_detection.py)
- [arksim/evaluator/trajectory_matching.py](https://github.com/arklexai/arksim/blob/main/arksim/evaluator/trajectory_matching.py)
</details>

# 评估系统

## 概述

评估系统（Evaluation System）是 ArkSim 的核心组件之一，负责对模拟对话进行质量评分和结果分析。该系统通过预定义的指标体系，从多个维度评估智能体（Agent）的表现，包括目标完成度、响应有效性、对话连贯性等。

评估系统支持内置指标和自定义指标扩展，评估结果可生成详细的 HTML 报告，帮助开发者识别智能体的优势与不足。资料来源：[arksim/evaluator/evaluator.py:1-50]()

## 系统架构

```mermaid
graph TD
    A[模拟对话数据] --> B[评估引擎]
    B --> C[内置指标]
    B --> D[自定义指标]
    C --> E[评分计算]
    D --> E
    E --> F[错误检测]
    E --> G[轨迹匹配]
    F --> H[最终报告]
    G --> H
    H --> I[HTML报告]
    H --> J[JSON结果]
```

### 核心模块

| 模块 | 文件路径 | 职责 |
|------|----------|------|
| 评估引擎 | `evaluator.py` | 协调评估流程，汇总各指标结果 |
| 评估执行 | `evaluate.py` | 处理单个对话的评分逻辑 |
| 基础指标 | `base_metric.py` | 定义指标基类和通用接口 |
| 内置指标 | `builtin_metrics.py` | 提供开箱即用的评估指标 |
| 阈值管理 | `thresholds.py` | 管理评分阈值和判断标准 |
| 错误检测 | `error_detection.py` | 识别对话中的错误模式 |
| 轨迹匹配 | `trajectory_matching.py` | 对比预期与实际对话轨迹 |

资料来源：[arksim/evaluator/base_metric.py:1-30]()

## 指标体系

### 指标类型

评估系统采用双轨指标架构：

#### 定量指标（QuantitativeMetric）

定量指标返回数值型评分，范围通常为 0.0 到 1.0：

```python
class QuantitativeMetric(Protocol):
    async def score(self, input: ScoreInput) -> QuantResult: ...
```

资料来源：[arksim/evaluator/base_metric.py:20-25]()

#### 定性指标（QualitativeMetric）

定性指标提供更详细的文本反馈和子项评分：

```python
class QualitativeMetric(Protocol):
    async def score(self, input: ScoreInput) -> QualResult: ...
```

资料来源：[arksim/evaluator/base_metric.py:30-35]()

### 评分输入

所有指标共享统一的输入结构 `ScoreInput`，包含：

| 字段 | 类型 | 说明 |
|------|------|------|
| `scenario` | Scenario | 测试场景定义 |
| `chat_history` | list[Turn] | 完整对话历史 |
| `agent_response` | str | 智能体最终响应 |
| `metadata` | dict | 额外元数据 |

资料来源：[arksim/evaluator/base_metric.py:40-60]()

## 内置指标

### 目标完成度（Goal Completion）

评估智能体是否完成了用户场景中设定的核心目标。系统根据场景定义的成功条件进行判断。

### 最终分数（Final Score）

综合评分，计算公式为：

```
最终分数 = 回合成功率 × 40% + 目标完成度 × 60%
```

资料来源：[arksim/utils/html_report/report_template.html:1-50]()

### 其他内置指标

内置指标还包括：

- **Helpfulness**：响应有帮助程度
- **Coherence**：对话连贯性
- **Relevance**：响应相关性
- **Safety**：安全性检查
- **Turn Success Ratio**：单回合成功比例

资料来源：[arksim/evaluator/builtin_metrics.py:1-100]()

## 自定义指标

### 实现自定义指标

用户可以通过继承 `QuantitativeMetric` 或 `QualitativeMetric` 来创建自定义指标：

```python
from arksim.evaluator import (
    QualitativeMetric,
    QualResult,
    format_chat_history,
)

class VerificationComplianceMetric(QualitativeMetric):
    async def score(self, input: ScoreInput) -> QualResult:
        # 实现评分逻辑
        return QualResult(
            score=score,
            reason="评估理由"
        )
```

资料来源：[examples/customer-service/custom_metrics.py:1-50]()

### 自定义指标配置

1. 在 `custom_metrics/` 目录下创建指标文件
2. 实现 `QuantitativeMetric` 或 `QualitativeMetric` 接口
3. 返回 `QuantResult` 或 `QualResult`，包含 `score` 和 `reason`
4. 在 `config.yaml` 的 `custom_metrics_file_paths` 中添加文件路径
5. （可选）在 `metrics_to_run` 中指定要运行的指标

资料来源：[examples/e-commerce/custom_metrics.py:1-80]()

## 阈值管理

### 阈值配置

阈值系统根据评分结果判断对话状态：

| 状态 | 条件 | 说明 |
|------|------|------|
| 成功（Done） | 最终分数 = 1.0 | 完全达标 |
| 部分失败（Partial Failure） | 0 < 分数 < 1.0 | 部分达标 |
| 完全失败（Failure） | 分数 = 0 | 完全未达标 |

资料来源：[arksim/evaluator/thresholds.py:1-50]()

### 阈值判断逻辑

```mermaid
graph TD
    A[开始评估] --> B{分数 == 1.0?}
    B -->|是| C[状态: Done]
    B -->|否| D{分数 > 0?}
    D -->|是| E[状态: Partial Failure]
    D -->|否| F[状态: Failure]
```

## 错误检测

### 错误模式识别

错误检测模块分析对话历史，识别常见的失败模式：

- **重复响应**：智能体重复相同或相似的回复
- **信息缺失**：未提供必要的信息或答案
- **行为错误**：执行了不正确的操作或判断
- **上下文丢失**：未能保持对话上下文连贯性

资料来源：[arksim/evaluator/error_detection.py:1-80]()

### 错误分类

评估报告会对检测到的错误进行分类，便于问题定位：

| 错误类型 | 检测依据 |
|----------|----------|
| 重复响应 | 检测连续或间隔出现的相似回复 |
| 缺少信息 | 关键场景信息未被提取或使用 |
| 工具调用错误 | 工具参数或调用时机不当 |

## 轨迹匹配

### 功能概述

轨迹匹配模块将实际对话轨迹与预期轨迹进行对比，评估智能体是否按照预期的路径执行。

资料来源：[arksim/evaluator/trajectory_matching.py:1-60]()

### 匹配算法

```mermaid
graph LR
    A[预期轨迹] --> C[轨迹对比器]
    B[实际轨迹] --> C
    C --> D{匹配度计算}
    D -->|高| E[轨迹匹配成功]
    D -->|低| F[轨迹偏离]
```

## 报告生成

### HTML 报告

评估完成后，系统生成详细的 HTML 报告，包含：

- **概览统计**：整体分数分布、通过率
- **场景详情**：每个测试场景的详细评分
- **对话回放**：完整的对话转录及评分标注
- **错误分析**：失败模式汇总及建议

资料来源：[arksim/utils/html_report/report_template.html:1-100]()

### 报告数据结构

```json
{
  "scenario_id": "scenario_001",
  "goal_completion_score": 0.85,
  "final_score": 0.82,
  "status": "partial_failure",
  "chat_history": [...],
  "metrics": {
    "goal_completion": { "score": 0.85, "reason": "..." },
    "turn_success_ratio": { "score": 0.78, "reason": "..." }
  }
}
```

## 配置使用

### 命令行使用

```bash
# 模拟和评估一体化
arksim simulate-evaluate config.yaml

# 分步执行
arksim simulate config_simulate.yaml
arksim evaluate config_evaluate.yaml
```

### YAML 配置

```yaml
evaluation:
  provider: openai
  model: gpt-4o-mini
  metrics_to_run:
    - goal_completion
    - turn_success_ratio
    - final_score
  custom_metrics_file_paths:
    - ./custom_metrics/metrics.py
  num_workers: auto
  report_html: true
```

资料来源：[examples/integrations/dify/README.md:1-30]()

## 评估流程

```mermaid
sequenceDiagram
    participant S as 模拟器
    participant E as 评估引擎
    participant M as 指标计算
    participant R as 报告生成
    
    S->>E: 提交对话数据
    E->>M: 分发指标任务
    M-->>E: 逐项评分
    E->>E: 计算综合分数
    E->>E: 错误检测
    E->>E: 轨迹匹配
    E->>R: 生成报告
    R-->>用户: HTML报告 + 控制台输出
```

## 最佳实践

### 指标设计建议

1. **明确评分标准**：每个指标应有清晰的评分依据
2. **合理分数区间**：定量指标建议使用 0.0-1.0 或 0-100
3. **提供失败理由**：便于问题诊断和修复
4. **避免指标耦合**：各指标应独立评估

### 测试场景设计

1. 覆盖正向和负向场景
2. 包含边界条件和异常情况
3. 设置明确的成功/失败标准
4. 提供足够的上下文信息

## 扩展指南

### 添加新指标类型

1. 在 `base_metric.py` 中定义指标接口
2. 在 `builtin_metrics.py` 中实现默认逻辑
3. 在 `evaluate.py` 中注册指标处理器

### 集成外部评估服务

```python
class ExternalEvaluator:
    async def score(self, input: ScoreInput) -> QuantResult:
        # 调用外部 API
        response = await external_api.evaluate(input)
        return QuantResult(score=response.score, reason=response.reason)
```

## 总结

评估系统是 ArkSim 实现智能体质量验证的核心基础设施，通过模块化的指标体系、灵活的扩展机制和详细的报告输出，帮助开发者全面了解智能体的表现并进行针对性优化。系统设计遵循可扩展性和易用性原则，既支持开箱即用的内置功能，也支持用户根据业务需求定制专属评估指标。

---

<a id='page-llm-providers'></a>

## LLM提供者集成

### 相关页面

相关主题：[Agent类型与客户端](#page-agent-types), [配置管理](#page-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/llms/chat/providers/openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/openai.py)
- [arksim/llms/chat/providers/anthropic.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/anthropic.py)
- [arksim/llms/chat/providers/google.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/google.py)
- [arksim/llms/chat/providers/azure_openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/azure_openai.py)
- [arksim/llms/chat/llm.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/llm.py)
</details>

# LLM提供者集成

## 概述

ArkSim的LLM提供者集成模块为模拟器提供了连接各种大语言模型服务的能力。该模块采用统一抽象的架构设计，将不同LLM提供商的API差异封装在独立的提供者实现中，使上层业务逻辑无需关心底层具体使用的是哪家服务商。

LLM提供者在ArkSim中扮演核心角色，主要用于：

- **用户模拟器（User Simulator）**：基于真实用户行为生成自然对话
- **评估器（Evaluator）**：分析对话质量并给出评分
- **自定义代理连接**：支持通过LLM驱动自定义代理行为

资料来源：[arksim/llms/chat/llm.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/llm.py)

## 架构设计

### 整体架构

ArkSim的LLM集成采用工厂模式与策略模式相结合的架构：

```mermaid
graph TD
    A[调用方] --> B[LLM 抽象层]
    B --> C{Provider Factory}
    C --> D[OpenAI Provider]
    C --> E[Anthropic Provider]
    C --> F[Google Provider]
    C --> G[Azure OpenAI Provider]
    
    H[配置层] --> C
    H --> B
```

### 核心组件

| 组件 | 文件路径 | 职责 |
|------|----------|------|
| LLM 抽象类 | `arksim/llms/chat/llm.py` | 定义通用接口，封装请求/响应处理 |
| OpenAI Provider | `arksim/llms/chat/providers/openai.py` | OpenAI API及兼容API实现 |
| Anthropic Provider | `arksim/llms/chat/providers/anthropic.py` | Anthropic Claude API实现 |
| Google Provider | `arksim/llms/chat/providers/google.py` | Google Gemini API实现 |
| Azure OpenAI Provider | `arksim/llms/chat/providers/azure_openai.py` | Azure OpenAI服务实现 |

资料来源：[arksim/llms/chat/providers/openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/openai.py)

## 支持的LLM提供者

### OpenAI

OpenAI提供者是最常用的实现，支持标准的Chat Completions API格式。

**配置参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `api_key` | string | 是 | OpenAI API密钥 |
| `model` | string | 是 | 模型名称（如`gpt-4o`、`gpt-4o-mini`） |
| `base_url` | string | 否 | API基础URL，支持自定义端点 |
| `timeout` | int | 否 | 请求超时时间（秒） |
| `max_retries` | int | 否 | 最大重试次数 |

**使用示例：**

```yaml
llm:
  provider: openai
  api_key: ${OPENAI_API_KEY}
  model: gpt-4o
  base_url: https://api.openai.com/v1
```

资料来源：[arksim/llms/chat/providers/openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/openai.py)

### Anthropic

Anthropic提供者用于连接Claude系列模型，支持其特有的消息格式和工具调用能力。

**配置参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `api_key` | string | 是 | Anthropic API密钥 |
| `model` | string | 是 | 模型名称（如`claude-sonnet-4-20250514`） |
| `base_url` | string | 否 | API基础URL |
| `max_tokens` | int | 否 | 最大输出token数 |

**使用示例：**

```yaml
llm:
  provider: anthropic
  api_key: ${ANTHROPIC_API_KEY}
  model: claude-sonnet-4-20250514
```

资料来源：[arksim/llms/chat/providers/anthropic.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/anthropic.py)

### Google

Google提供者支持Gemini系列模型，适用于需要多模态能力的场景。

**配置参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `api_key` | string | 是 | Google API密钥 |
| `model` | string | 是 | 模型名称（如`gemini-2.0-flash`） |
| `base_url` | string | 否 | API基础URL |

资料来源：[arksim/llms/chat/providers/google.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/google.py)

### Azure OpenAI

Azure OpenAI提供者支持企业级部署场景，兼容OpenAI API格式的同时提供Azure特有的安全和管理功能。

**配置参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `api_key` | string | 是 | Azure API密钥 |
| `endpoint` | string | 是 | Azure端点URL |
| `api_version` | string | 是 | API版本（如`2024-02-01`） |
| `azure_deployment` | string | 是 | 部署名称 |

**使用示例：**

```yaml
llm:
  provider: azure_openai
  api_key: ${AZURE_OPENAI_API_KEY}
  endpoint: https://your-resource.openai.azure.com
  api_version: "2024-02-01"
  azure_deployment: gpt-4o
```

资料来源：[arksim/llms/chat/providers/azure_openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/azure_openai.py)

## 配置管理

### 环境变量注入

ArkSim支持通过环境变量安全地配置敏感信息，避免在配置文件中明文存储密钥。

```yaml
llm:
  provider: openai
  api_key: ${OPENAI_API_KEY}  # 从环境变量读取
```

### 配置文件结构

完整的模拟器配置通常包含LLM配置和应用配置：

```yaml
agent_config:
  api_config:
    endpoint: http://localhost:8000/v1/chat/completions

user_simulator:
  llm:
    provider: openai
    api_key: ${OPENAI_API_KEY}
    model: gpt-4o

evaluator:
  llm:
    provider: anthropic
    api_key: ${ANTHROPIC_API_KEY}
    model: claude-sonnet-4-20250514
```

资料来源：[arksim/llms/chat/llm.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/llm.py)

## 请求处理流程

### 统一请求接口

```mermaid
sequenceDiagram
    participant 调用方
    participant LLM抽象层
    participant Provider
    participant 外部API
    
    调用方->>LLM抽象层: send_messages(messages, options)
    LLM抽象层->>Provider: send(messages, config)
    Provider->>外部API: HTTP POST
    外部API-->>Provider: Response
    Provider-->>LLM抽象层: 标准化响应
    LLM抽象层-->>调用方: 返回结果
```

### 错误处理策略

LLM提供者实现了统一的错误处理机制：

1. **网络错误**：自动重试（可配置重试次数）
2. **速率限制**：指数退避策略
3. **认证错误**：抛出明确的认证异常
4. **模型不可用**：返回友好的错误提示

资料来源：[arksim/llms/chat/providers/openai.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/providers/openai.py)

## 在模拟器中的使用

### 用户模拟器集成

用户模拟器是LLM提供者的主要消费者之一，它使用LLM来生成符合用户画像的对话行为：

```python
class UserSimulator:
    def __init__(self, llm_config: dict):
        self.llm = create_llm(llm_config)
    
    async def generate_response(
        self, 
        context: dict,
        user_profile: dict
    ) -> str:
        prompt = self._build_prompt(context, user_profile)
        response = await self.llm.chat([{"role": "user", "content": prompt}])
        return response.content
```

### 评估器集成

评估器使用独立的LLM实例来分析对话质量：

```python
class Evaluator:
    def __init__(self, llm_config: dict):
        self.llm = create_llm(llm_config)
    
    async def evaluate(self, conversation: list) -> dict:
        analysis_prompt = self._build_analysis_prompt(conversation)
        result = await self.llm.chat([{"role": "user", "content": analysis_prompt}])
        return self._parse_result(result)
```

资料来源：[arksim/llms/chat/llm.py](https://github.com/arklexai/arksim/blob/main/arksim/llms/chat/llm.py)

## 扩展自定义提供者

如需集成其他LLM提供者，可以继承基础Provider类：

```python
from arksim.llms.chat.providers.base import BaseProvider

class CustomProvider(BaseProvider):
    async def chat(self, messages: list, **kwargs) -> ChatResponse:
        # 实现自定义逻辑
        pass
    
    async def completion(self, prompt: str, **kwargs) -> str:
        # 实现自定义逻辑
        pass
```

注册新提供者只需在Provider工厂中添加对应的创建逻辑即可。

## 最佳实践

### 密钥管理

- 始终使用环境变量存储API密钥
- 不要将包含密钥的配置文件提交到版本控制系统
- 使用`.env`文件配合`.gitignore`排除

### 成本控制

- 选择合适的模型大小，避免过度使用高端模型
- 配置适当的`max_tokens`限制
- 使用流式响应处理长对话

### 性能优化

- 为长期运行的模拟任务复用LLM实例
- 合理设置超时时间和重试策略
- 考虑使用异步调用提高并发能力

## 相关文档

- [CLI命令行工具](../cli.md)
- [模拟器配置指南](../configuration.md)
- [自定义代理连接](../custom-agent.md)
- [评估指标说明](../evaluation-metrics.md)

---

<a id='page-agent-types'></a>

## Agent类型与客户端

### 相关页面

相关主题：[LLM提供者集成](#page-llm-providers), [配置管理](#page-configuration), [模拟引擎](#page-simulation-engine)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/simulation_engine/agent/clients/chat_completions.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/clients/chat_completions.py)
- [arksim/simulation_engine/agent/clients/a2a.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/clients/a2a.py)
- [arksim/simulation_engine/agent/clients/custom.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/clients/custom.py)
- [arksim/simulation_engine/agent/base.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/agent/base.py)
</details>

# Agent类型与客户端

## 概述

ArkSim 支持多种 Agent 连接方式，允许用户将不同类型的 AI Agent 接入仿真评估框架。系统通过统一的抽象层，支持自定义 Python 类、Chat Completions API、A2A 协议等多种接入方式。

核心抽象由 `BaseAgent` 基类定义，所有 Agent 实现必须继承该类并实现核心接口方法。

## Agent 类型架构

```mermaid
graph TD
    subgraph Agent类型
        Custom[自定义Python类<br/>custom]
        ChatCompletions[Chat Completions API<br/>chat_completions]
        A2A[A2A协议<br/>a2a]
    end
    
    subgraph 核心抽象
        Base[BaseAgent]
        Response[AgentResponse]
    end
    
    Custom --> Base
    ChatCompletions --> Base
    A2A --> Base
    
    Base --> Response
```

## BaseAgent 抽象基类

`BaseAgent` 是所有 Agent 实现的基础抽象类，定义了 Agent 必须实现的接口规范。

### 核心方法

| 方法名 | 返回类型 | 说明 |
|--------|----------|------|
| `get_chat_id()` | `str` | 获取会话唯一标识符 |
| `execute()` | `str \| AgentResponse` | 执行用户查询，返回响应内容 |

### AgentResponse 数据结构

用于封装包含工具调用的复杂响应：

```python
class AgentResponse(NamedTuple):
    message: str                    # 助手回复文本
    tool_calls: list[ToolCall] | None  # 工具调用列表（可选）
    error: str | None = None        # 错误信息（可选）
```

资料来源：[arksim/simulation_engine/agent/base.py:1-50]()

### 自定义 Agent 实现示例

```python
from arksim.simulation_engine.agent.base import BaseAgent
from arksim.simulation_engine.tool_types import AgentResponse

class MyAgent(BaseAgent):
    async def get_chat_id(self) -> str:
        return "unique-id"

    async def execute(self, user_query: str, **kwargs: object) -> str | AgentResponse:
        # 替换为你的 Agent 逻辑
        return "agent response"
```

资料来源：[README.md:1-100]()

## Chat Completions 客户端

`ChatCompletionsAgent` 用于连接支持 OpenAI 兼容 Chat Completions API 的 HTTP 端点。

### 配置参数

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `endpoint` | `str` | 是 | API 端点 URL，如 `http://localhost:8000/v1/chat/completions` |
| `api_key` | `str` | 否 | API 密钥认证 |
| `model` | `str` | 否 | 模型名称 |
| `timeout` | `int` | 否 | 请求超时时间（秒） |
| `extra_headers` | `dict` | 否 | 额外 HTTP 请求头 |
| `extra_body` | `dict` | 否 | 额外请求体参数 |

### YAML 配置示例

```yaml
agent_config:
  agent_type: chat_completions
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000/v1/chat/completions
    timeout: 60
```

### 工作流程

```mermaid
sequenceDiagram
    participant Simulator
    participant ChatCompletionsClient
    participant HTTPEndpoint
    
    Simulator->>ChatCompletionsClient: execute(user_query)
    ChatCompletionsClient->>HTTPEndpoint: POST /v1/chat/completions
    HTTPEndpoint-->>ChatCompletionsClient: Chat Completion Response
    ChatCompletionsClient-->>Simulator: str | AgentResponse
```

资料来源：[arksim/simulation_engine/agent/clients/chat_completions.py:1-100]()

## A2A 协议客户端

`A2AAgent` 实现 Agent-to-Agent 协议客户端，用于与支持 A2A 规范的远程 Agent 通信。

### 协议特性

- 支持标准 A2A 协议端点
- 自动处理 JSON-RPC 格式消息
- 会话状态管理

### 配置参数

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `endpoint` | `str` | 是 | A2A Agent 端点 URL，如 `http://localhost:9999/agent` |
| `agent_id` | `str` | 否 | Agent 标识符 |
| `timeout` | `int` | 否 | 请求超时时间（秒） |

### YAML 配置示例

```yaml
agent_config:
  agent_type: a2a
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:9999/agent
```

资料来源：[arksim/simulation_engine/agent/clients/a2a.py:1-100]()

## 自定义 Agent 客户端

`CustomAgent` 允许用户通过继承 `BaseAgent` 实现自定义逻辑，适用于本地运行的 Agent 或需要深度定制的场景。

### 初始化选项

通过 `arksim init` 命令可自动生成模板：

```bash
arksim init --agent-type custom --force
```

### 工具调用支持

自定义 Agent 可返回 `AgentResponse` 包含工具调用信息：

```python
from arksim.simulation_engine.tool_types import ToolCall, AgentResponse

async def execute(self, user_query: str, **kwargs) -> AgentResponse:
    tool_calls = [
        ToolCall(
            id="call_1",
            name="get_weather",
            arguments={"location": "北京"}
        )
    ]
    return AgentResponse(
        message="正在查询天气...",
        tool_calls=tool_calls
    )
```

### 追踪集成

支持通过 `ArksimTracingProcessor` 自动捕获工具调用：

> Simulator 设置路由上下文 -> agent.execute() 正常运行 -> SDK 触发 TracingProcessor.on_span_end -> arksim 捕获 -> 评估器评分

资料来源：[arksim/simulation_engine/agent/clients/custom.py:1-100]()

## Agent 类型对比

| 特性 | custom | chat_completions | a2a |
|------|--------|------------------|-----|
| 实现方式 | Python 类继承 | HTTP API 调用 | HTTP 协议 |
| 本地/远程 | 均可 | 远程 | 远程 |
| 工具调用捕获 | AgentResponse / TracingProcessor | 自动解析 | 自动解析 |
| 配置复杂度 | 中 | 低 | 低 |
| 适用场景 | 深度定制、本地 Agent | 标准 API 服务 | A2A 协议 Agent |

## 命令行工具支持

### 初始化命令

```bash
arksim init --agent-type <type> [--force]
```

支持的 `--agent-type` 选项：
- `custom`：生成 Python 代理文件（无需服务器）
- `chat_completions`：HTTP 端点
- `a2a`：Agent-to-Agent 协议

### CLI 参数说明

| 参数 | 说明 |
|------|------|
| `--agent-type` | Agent 连接类型，默认 `custom` |
| `--force` | 覆盖已存在的文件 |

资料来源：[arksim/cli.py:1-100]()

## 集成示例

ArkSim 提供了多种集成示例，演示如何连接不同类型的 Agent：

| 集成项目 | Agent 类型 | 说明 |
|----------|------------|------|
| `langchain` | Custom | LangChain/LangGraph 集成 |
| `langgraph` | Custom | LangGraph 专用集成 |
| `claude-agent-sdk` | Custom | Claude Agent SDK 集成 |
| `autogen` | Custom | Microsoft AutoGen 集成 |
| `rasa` | Chat Completions | Rasa Pro 集成 |
| `dify` | Custom | Dify 平台集成 |
| `openclaw` | Chat Completions | OpenClaw 网关集成 |

运行任意集成示例：

```bash
cd examples/integrations/<integration_name>
arksim simulate-evaluate config.yaml
```

资料来源：[examples/integrations/langchain/README.md:1-50]()
资料来源：[examples/integrations/rasa/README.md:1-80]()

## 最佳实践

1. **选择合适的 Agent 类型**：优先使用 `chat_completions` 或 `a2a`，仅在需要深度定制时使用 `custom`
2. **工具调用返回规范**：自定义 Agent 应返回 `AgentResponse` 包含 `tool_calls` 以支持完整评估
3. **错误处理**：确保 `execute()` 方法妥善处理异常，返回有意义的错误信息
4. **会话标识**：实现正确的 `get_chat_id()` 确保多会话场景正确追踪

---

<a id='page-configuration'></a>

## 配置管理

### 相关页面

相关主题：[快速开始](#page-quickstart), [场景定义与管理](#page-scenarios), [Agent类型与客户端](#page-agent-types)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/config.yaml](https://github.com/arklexai/arksim/blob/main/arksim/config.yaml)
- [arksim/config_evaluate.yaml](https://github.com/arklexai/arksim/blob/main/arksim/config_evaluate.yaml)
- [arksim/config_simulate.yaml](https://github.com/arklexai/arksim/blob/main/arksim/config_simulate.yaml)
- [arksim/config/types.py](https://github.com/arklexai/arksim/blob/main/arksim/config/types.py)
- [arksim/config/core/agent.py](https://github.com/arklexai/arksim/blob/main/arksim/config/core/agent.py)
- [arksim/config/utils.py](https://github.com/arklexai/arksim/blob/main/arksim/config/utils.py)
</details>

# 配置管理

## 概述

ArkSim 的配置管理系统负责定义仿真和评估流程的所有参数，包括代理连接方式、场景文件路径、指标配置、API 端点设置等。该系统采用 YAML 格式的配置文件，支持三种主要运行模式：联合仿真评估、单独仿真和单独评估。配置系统通过 Pydantic 模型实现类型安全的数据验证，确保配置文件的正确性和一致性。

ArkSim 的配置架构设计遵循模块化原则，将不同功能领域的配置参数分离到独立的核心模块中。这种设计使得配置管理更加清晰，便于维护和扩展。配置系统支持多种代理类型，包括自定义 Python 类、Chat Completions 接口、A2A 协议等，每种代理类型都有其专属的配置结构。

## 配置架构

### 模块结构

ArkSim 的配置系统位于 `arksim/config/` 目录下，采用分层架构设计。核心类型定义集中在 `types.py` 中，提供基础数据模型；代理相关配置在 `core/agent.py` 中定义；通用工具函数位于 `utils.py`。

```mermaid
graph TD
    A[config.yaml] --> B[config/types.py - 基础类型]
    A --> C[config/core/agent.py - 代理配置]
    A --> D[config/utils.py - 工具函数]
    B --> E[ConfigLoader]
    C --> F[AgentConfig]
    D --> G[YAML加载和验证]
```

### 配置加载流程

配置系统通过统一的加载器处理 YAML 配置文件，加载过程包括文件解析、类型验证和默认值填充三个阶段。系统首先读取 YAML 文件内容，然后根据配置类型选择对应的 Pydantic 模型进行数据验证，最后将验证通过的配置对象传递给相应的组件使用。

## 配置文件类型

ArkSim 支持三种主要的配置文件类型，分别用于不同的运行场景：

| 配置文件 | 用途 | 关键参数 |
|---------|------|---------|
| `config.yaml` | 联合仿真评估 | agent_config、scenarios、metrics |
| `config_simulate.yaml` | 独立仿真 | agent_config、scenarios |
| `config_evaluate.yaml` | 独立评估 | agent_config、scenarios_results |

### 联合配置文件 (config.yaml)

完整的仿真评估配置包含所有必要的参数，适用于一次性执行仿真和评估流程。配置文件中需要指定代理设置、场景定义、评估指标和可选的自定义指标。

### 仿真配置文件 (config_simulate.yaml)

仅包含仿真所需的参数，用于生成对话数据而不执行评估。该配置文件适用于调试仿真逻辑或生成特定格式的对话记录。

### 评估配置文件 (config_evaluate.yaml)

仅包含评估所需的参数，用于对已存在的仿真结果进行评分分析。当需要使用不同的评估指标重新分析历史仿真数据时，此配置非常有用。

## 代理配置

代理配置是 ArkSim 配置系统的核心部分，定义了如何连接和交互目标 AI 代理。系统支持多种代理类型，每种类型具有不同的配置结构。

### 代理类型

ArkSim 支持以下代理类型：

| 代理类型 | 标识符 | 说明 |
|---------|--------|------|
| 自定义 Python 类 | `custom` | 用户实现的 BaseAgent 子类 |
| Chat Completions | `chat_completions` | OpenAI 风格的 HTTP 接口 |
| A2A 协议 | `a2a` | Agent-to-Agent 通信协议 |

### 自定义代理配置

自定义代理需要通过 `agent_type: custom` 指定类型，并提供 Python 模块路径和类名：

```yaml
agent_config:
  agent_type: custom
  agent_name: my-agent
  module: my_agent
  class_name: MyAgent
```

### Chat Completions 配置

Chat Completions 类型代理通过 HTTP 接口调用，需要配置服务端点：

```yaml
agent_config:
  agent_type: chat_completions
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000/v1/chat/completions
```

资料来源：[README.md]()

### A2A 协议配置

A2A 协议代理同样使用 HTTP 接口，但使用不同的端点路径：

```yaml
agent_config:
  agent_type: a2a
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:9999/agent
```

资料来源：[README.md]()

## 场景配置

场景配置定义仿真测试的具体案例，包括用户画像、初始知识状态和预期目标。场景以 JSON 格式存储，通过配置文件中的 `scenarios` 参数引用。

### 场景文件结构

场景文件通常命名为 `scenarios.json`，包含多个测试场景的数组，每个场景定义一个完整的用户交互测试用例。

### 场景加载

ArkSim 支持从指定路径加载场景文件：

```yaml
scenarios: /path/to/scenarios.json
```

UI 界面提供了场景文件路径输入和浏览功能，支持即时验证文件有效性。

## 指标配置

### 定量指标

定量指标返回 0.0 到 1.0 之间的数值评分，用于衡量代理行为的可量化方面。系统内置多种定量指标，也可通过自定义指标扩展。

### 定性指标

定性指标返回分类标签，如 "compliant"、"flagged"、"pass"、"fail" 等。系统根据预设的标签集合判断指标情感方向（正面/负面/中性），用于生成可视化展示。

### 自定义指标

用户可以在 `tests/arksim/custom_metrics/` 目录下创建自定义指标文件，并在配置中引用：

```yaml
custom_metrics_file_paths:
  - tests/arksim/custom_metrics/my_metric.py

metrics_to_run:
  - verification_compliance
  - my_custom_metric
```

资料来源：[examples/customer-service/custom_metrics.py]()

## 追踪配置

ArkSim 支持通过追踪机制自动捕获代理的工具调用，这对于无法直接获取工具调用数据的代理特别有用。

### 追踪接收器配置

```yaml
trace_receiver:
  enabled: true
  wait_timeout: 5
```

当 `trace_receiver.enabled` 设为 `true` 时，系统启用追踪接收器等待模式；`wait_timeout` 定义最大等待时间（秒）。

### 追踪工作流程

```mermaid
graph LR
    A[Simulator设置路由上下文] --> B[Agent执行]
    B --> C[SDK触发TracingProcessor]
    C --> D[on_span_end回调]
    D --> E[ArkSim捕获工具调用]
    E --> F[Evaluator评分]
```

资料来源：[examples/customer-service/README.md]()

## 配置工具函数

ArkSim 提供了配置相关的工具函数用于处理 YAML 文件加载、配置合并和参数验证。这些函数位于 `arksim/config/utils.py`，被配置加载器和各组件广泛使用。

### 配置验证

系统通过 Pydantic 模型自动验证配置参数的类型和取值范围，确保配置文件符合预期格式。验证失败时返回详细的错误信息，指出具体的配置项和问题原因。

## 使用示例

### 命令行使用

```bash
# 联合仿真评估
arksim simulate-evaluate config.yaml

# 单独仿真
arksim simulate config_simulate.yaml

# 单独评估
arksim evaluate config_evaluate.yaml
```

### Python 脚本使用

```python
from arksim.config.types import Config
from arksim.config.utils import load_config

# 加载配置文件
config = load_config("config.yaml")

# 使用配置执行仿真
simulator = Simulator(config)
results = await simulator.run()
```

## 最佳实践

1. **分离配置策略**：对于频繁修改的参数（如 API 端点），建议使用环境变量引用而非硬编码
2. **场景复用**：将通用场景定义提取为模板，减少重复配置
3. **自定义指标模块化**：将自定义指标组织在独立目录，便于版本管理和共享
4. **配置版本控制**：在配置文件中添加注释说明版本和变更历史
5. **测试配置隔离**：为测试环境创建独立的配置文件，避免影响生产配置

## 相关文件索引

| 文件路径 | 功能描述 |
|---------|---------|
| `arksim/config/types.py` | 配置数据模型和类型定义 |
| `arksim/config/core/agent.py` | 代理配置核心逻辑 |
| `arksim/config/utils.py` | 配置加载和验证工具 |
| `examples/customer-service/config.yaml` | 完整配置示例 |
| `examples/integrations/*/config.yaml` | 各集成场景配置参考 |

---

<a id='page-scenarios'></a>

## 场景定义与管理

### 相关页面

相关主题：[快速开始](#page-quickstart), [配置管理](#page-configuration), [模拟引擎](#page-simulation-engine)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/scenario/entities.py](https://github.com/arklexai/arksim/blob/main/arksim/scenario/entities.py)
- [arksim/templates/scenarios.json](https://github.com/arklexai/arksim/blob/main/arksim/templates/scenarios.json)
- [examples/e-commerce/scenarios.json](https://github.com/arklexai/arksim/blob/main/examples/e-commerce/scenarios.json)
- [examples/customer-service/scenarios.json](https://github.com/arklexai/arksim/blob/main/examples/customer-service/scenarios.json)
- [arksim/simulation_engine/entities.py](https://github.com/arklexai/arksim/blob/main/arksim/simulation_engine/entities.py)
</details>

# 场景定义与管理

## 概述

场景（Scenario）是 ArkSim 仿真评估系统的核心抽象单元，用于定义模拟用户与智能体之间的交互测试用例。每个场景包含用户画像、背景知识、对话目标等关键信息，模拟器基于这些场景生成多轮对话，评估器则根据对话结果计算各项质量指标。

场景定义采用 JSON 格式存储在 `scenarios.json` 文件中，支持批量定义多个测试场景。系统默认每个场景生成 5 次独立对话（可配置），以统计学方式验证智能体行为的一致性和可靠性。

资料来源：[arksim/simulation_engine/entities.py:1-50]()

## 场景数据模型

### 核心场景实体

场景实体定义了测试用例的完整结构，包含用户模拟所需的所有信息：

```json
{
  "scenario_id": "unique-scenario-identifier",
  "user_profile": {
    "name": "张三",
    "age": 35,
    "occupation": "工程师",
    "personality": "direct_and_patient"
  },
  "knowledge": {
    "account_type": "高级会员",
    "subscription_date": "2023-01-15"
  },
  "goal": "取消当前的订阅服务",
  "expected_actions": ["verify_identity", "confirm_cancellation", "offer_alternative"],
  "success_criteria": {
    "min_score": 0.8,
    "required_steps": ["身份验证", "确认取消"]
  }
}
```

资料来源：[arksim/templates/scenarios.json]()

### 场景属性说明

| 属性 | 类型 | 必需 | 描述 |
|------|------|------|------|
| `scenario_id` | string | 是 | 场景唯一标识符，用于结果关联 |
| `user_profile` | object | 是 | 模拟用户的人口统计特征和性格属性 |
| `knowledge` | object | 是 | 用户知道的背景信息，用于生成自然对话 |
| `goal` | string | 是 | 用户想要达成的核心目标 |
| `expected_actions` | array | 否 | 期望智能体执行的关键动作序列 |
| `success_criteria` | object | 否 | 成功评判的详细标准 |

资料来源：[arksim/scenario/entities.py]()

## 场景结构详解

### 用户画像（User Profile）

用户画像定义了模拟用户的身份特征，影响对话生成的自然度和多样性：

```json
{
  "user_profile": {
    "name": "李明",
    "age": 28,
    "occupation": "软件工程师",
    "personality": "technical_and_direct",
    "communication_style": "concise",
    "language": "中文"
  }
}
```

用户画像支持的性格类型包括：`direct_and_patient`（直接且有耐心）、`technical_and_direct`（技术型直接）、`emotional`（情绪化）、`friendly_chatty`（友好健谈）等。不同性格会影响模拟用户的措辞风格和对话策略。

资料来源：[examples/customer-service/scenarios.json]()

### 背景知识（Knowledge）

背景知识定义用户角色已知的信息，这些信息在对话开始时存在于用户脑海中，但不会主动透露给智能体：

```json
{
  "knowledge": {
    "account_id": "ACC-2024-001",
    "account_type": "企业版",
    "subscription_plan": "年付",
    "billing_cycle": "monthly",
    "payment_method": "信用卡",
    "registered_email": "li@example.com"
  }
}
```

知识库中的信息可被智能体通过询问获取，用于验证对话上下文的一致性。

资料来源：[arksim/templates/scenarios.json]()

### 对话目标（Goal）

目标定义模拟用户希望达成的最终结果，是评估目标完成度的主要依据：

```json
{
  "goal": "将当前套餐从企业版降级为标准版",
  "goal_type": "service_change",
  "constraints": [
    "希望在月底前生效",
    "不接受销售推销"
  ]
}
```

资料来源：[examples/e-commerce/scenarios.json]()

## 场景管理工作流

### 场景生命周期

```mermaid
graph TD
    A[创建 scenarios.json] --> B[场景加载与解析]
    B --> C{语法验证}
    C -->|通过| D[场景预处理]
    C -->|失败| E[返回错误信息]
    D --> F[模拟用户生成]
    F --> G[多轮对话执行]
    G --> H[结果存储]
    H --> I[评估计分]
    I --> J[生成报告]
```

场景管理遵循标准的三阶段流程：加载验证阶段、模拟执行阶段、评估报告阶段。每个阶段都有明确的输入输出和错误处理机制。

资料来源：[arksim/simulation_engine/entities.py:50-100]()

### 场景配置参数

模拟器通过 `SimulationConfig` 类管理场景执行的全局参数：

| 参数 | 默认值 | 描述 |
|------|--------|------|
| `scenarios_file` | - | 场景文件路径（必需） |
| `num_conversations_per_scenario` | 5 | 每个场景的对话轮次 |
| `max_turns` | 5 | 单次对话的最大轮数 |
| `num_workers` | 50 | 并行工作线程数 |
| `model` | gpt-4o | 用于用户模拟的LLM模型 |
| `provider` | openai | LLM提供商 |

资料来源：[arksim/simulation_engine/entities.py:20-45]()

### 场景文件验证

系统对场景文件进行多层次验证：

1. **语法验证**：JSON 格式正确性检查
2. **必填字段验证**：确认 `scenario_id`、`user_profile`、`goal` 等必填字段存在
3. **类型验证**：各字段类型符合数据模型定义
4. **一致性验证**：检查 `expected_actions` 中引用的动作是否在知识库中有对应定义

资料来源：[arksim/scenario/entities.py]()

## 场景与评估集成

### 评估指标计算

场景执行完成后，系统根据对话内容计算多维度评估指标：

```json
{
  "goal_completion_score": 0.85,
  "goal_completion_reason": "用户成功取消订阅，但未提供取消确认邮件",
  "turn_success_ratio": 0.92,
  "final_score": 0.88,
  "status": "done",
  "scores": [
    {
      "name": "identity_verification",
      "value": 1.0,
      "reason": "正确执行了身份验证流程"
    }
  ]
}
```

评分规则：
- `final_score = turn_success_ratio × 0.4 + goal_completion_score × 0.6`
- 状态判定：`done`（1.0）、`partial_failure`（≥0.6）、`failed`（<0.6）

资料来源：[arksim/utils/html_report/report_template.html:80-120]()

### 自定义指标扩展

ArkSim 支持通过 `custom_metrics.py` 添加领域特定评估指标：

```python
class VerificationComplianceSchema(BaseModel):
    identity_verification: float  # 0.0-1.0
    action_gating: float  # 0.0-1.0
    reason: str
```

自定义指标需要实现 `QuantitativeMetric` 或 `QualitativeMetric` 接口，并在 `config.yaml` 中引用。

资料来源：[examples/customer-service/custom_metrics.py]()

## 场景文件最佳实践

### 目录组织结构

建议的场景文件组织方式：

```
project/
├── config.yaml              # 仿真评估配置
├── scenarios.json           # 场景定义文件
├── custom_metrics/          # 自定义指标目录
│   └── quality_metrics.py
└── results/                 # 输出结果目录
    └── simulation/
        └── simulation.json
```

### 场景数量建议

| 测试目标 | 推荐场景数 | 每场景对话数 |
|----------|------------|--------------|
| 快速验证 | 5-10 | 3 |
| 标准测试 | 20-50 | 5 |
| 全面评估 | 100+ | 10 |

### 场景编写规范

1. **唯一性**：`scenario_id` 在同一文件中必须唯一
2. **具体性**：`goal` 应描述具体、可观测的结果
3. **多样性**：避免场景之间仅有微小差异
4. **真实性**：用户画像应符合实际用户分布

资料来源：[examples/customer-service/README.md]()

## 常见问题排查

### 场景加载失败

| 错误类型 | 可能原因 | 解决方案 |
|----------|----------|----------|
| `FileNotFoundError` | 路径不正确 | 使用绝对路径或相对于配置文件的路径 |
| `JSONDecodeError` | JSON 格式错误 | 检查引号、逗号、括号配对 |
| `ValidationError` | 缺少必填字段 | 对照数据模型补全字段 |

### 模拟结果异常

| 症状 | 可能原因 | 解决方案 |
|------|----------|----------|
| 所有场景得分偏低 | LLM 模型问题或提示词不当 | 检查 API 配置和模型选择 |
| 同一场景得分差异大 | 对话随机性过高 | 增加 `num_conversations_per_scenario` |
| 工具调用未捕获 | 智能体未返回 `AgentResponse` | 确认智能体实现符合接口规范 |

资料来源：[arksim/simulation_engine/tool_types.py:30-50]()

## 相关文档

- [仿真引擎配置指南](./simulation-engine.md)
- [自定义指标开发](./custom-metrics.md)
- [评估报告解读](./evaluation-report.md)
- [集成示例：电商场景](../examples/e-commerce)
- [集成示例：客服场景](../examples/customer-service)

---

<a id='page-web-ui'></a>

## Web UI系统

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [arksim/ui/app.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/app.py)
- [arksim/ui/api/routes_simulate.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/api/routes_simulate.py)
- [arksim/ui/api/routes_evaluate.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/api/routes_evaluate.py)
- [arksim/ui/api/routes_results.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/api/routes_results.py)
- [arksim/ui/api/state.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/api/state.py)
- [arksim/ui/api/ws_logs.py](https://github.com/arklexai/arksim/blob/main/arksim/ui/api/ws_logs.py)
- [arksim/ui/frontend/app.js](https://github.com/arklexai/arksim/blob/main/arksim/ui/frontend/app.js)
</details>

# Web UI系统

## 概述

ArkSim Web UI系统是项目提供的图形化用户界面，为用户提供了无需编写代码即可创建测试场景、运行模拟仿真和查看评估结果的完整工作流程。该系统采用前后端分离架构，后端基于FastAPI构建异步API服务，前端使用原生JavaScript和Alpine.js实现响应式交互界面。

Web UI的核心价值在于降低使用门槛，使产品经理、测试工程师等非开发人员也能快速上手使用ArkSim进行AI Agent的质量评估工作。通过直观的可视化界面，用户可以专注于场景设计和结果分析，而无需关心底层的命令行操作细节。

## 系统架构

### 整体架构图

```mermaid
graph TD
    A[浏览器] --> B[Web UI 前端]
    B --> C[FastAPI 后端服务]
    C --> D[模拟引擎]
    C --> E[评估引擎]
    C --> F[状态管理]
    D --> G[仿真结果]
    E --> H[评估报告]
    C --> I[WebSocket日志]
    G --> J[结果展示]
```

### 技术栈

| 层级 | 技术选型 | 说明 |
|------|---------|------|
| 前端框架 | Alpine.js | 轻量级响应式JavaScript框架 |
| UI组件 | Material Icons Outlined | Material Design图标库 |
| 后端框架 | FastAPI | 现代异步Python Web框架 |
| 实时通信 | WebSocket | 用于日志流推送 |
| 状态管理 | 后端状态模块 | API层状态共享 |

## 前端结构

### 文件组织

前端代码位于 `arksim/ui/frontend/` 目录下，采用单文件HTML结构，所有组件和交互逻辑内联在HTML中。这种设计简化了部署复杂度，同时利用Alpine.js的声明式特性实现模块化的页面管理。

### 页面导航系统

Web UI采用单页面应用（SPA）模式，通过Alpine.js的响应式状态管理实现页面切换。系统支持以下主要页面：

| 页面标识 | 功能描述 | 路由对应 |
|---------|---------|---------|
| `build` | 构建测试场景 | 场景编辑页面 |
| `simulate` | 运行模拟仿真 | 仿真执行页面 |
| `evaluate` | 执行质量评估 | 评估配置页面 |
| `results` | 查看结果报告 | 结果展示页面 |

导航状态由Alpine.js的全局状态管理，根据用户操作动态切换。当前激活页面通过 `activePage` 变量控制，导航颜色根据当前页面动态变化：

```javascript
_navColor(page) {
    // 返回对应页面的导航颜色
}
```

### 核心交互组件

#### 结果刷新组件

```html
<button @click="refreshResults()">
    <span class="material-icons-outlined">refresh</span>
    Refresh Results
</button>
```

刷新按钮允许用户在仿真或评估完成后重新加载最新的结果数据，无需刷新整个页面即可获取更新。

#### 场景构建页面（Build）

场景构建是测试工作的起点，用户在此页面定义模拟用户的行为模式。页面采用分步骤引导设计：

- **Step 0**：创建测试场景，定义模拟用户与Agent的交互方式
- **自动生成功能**：提供PRO版本的智能场景生成能力，基于用户描述自动创建测试用例

```html
<div class="t-surface rounded-xl border t-border p-5 mb-4">
    <span class="material-icons-outlined text-3xl text-amber-500">auto_awesome</span>
    <span class="font-semibold t-heading">Auto-generate Scenarios</span>
    <span class="text-[10px] font-bold bg-amber-100">PRO</span>
</div>
```

## 后端API设计

### API路由模块

后端API采用模块化设计，按功能职责划分为多个路由文件：

| 路由文件 | 职责范围 |
|---------|---------|
| `routes_simulate.py` | 仿真操作相关接口 |
| `routes_evaluate.py` | 评估操作相关接口 |
| `routes_results.py` | 结果查询相关接口 |

### 状态管理模块

`state.py` 模块负责管理Web UI运行时的共享状态，包括：

- 当前活跃的仿真任务ID
- 仿真进度状态
- 评估指标缓存
- 配置参数临时存储

```mermaid
graph LR
    A[API请求] --> B[State模块]
    B --> C[更新状态]
    C --> D[通知前端]
    D --> E[页面更新]
```

### WebSocket日志系统

`ws_logs.py` 实现实时日志推送功能，支持：

- 仿真过程日志流式传输
- 评估进度实时更新
- 长耗时任务的进度反馈

WebSocket连接在仿真开始时建立，日志数据以JSON格式传输，前端接收后动态渲染到日志面板。

## 数据流设计

### 仿真执行流程

```mermaid
sequenceDiagram
    前端->>后端: 启动仿真请求
    后端->>状态模块: 创建仿真任务
    状态模块-->>前端: 任务ID
    前端->>WebSocket: 建立日志连接
    后端->>模拟引擎: 执行仿真
    模拟引擎-->>WebSocket: 实时日志
    WebSocket-->>前端: 日志推送
    模拟引擎->>结果存储: 保存仿真结果
    结果存储-->>前端: 完成通知
    前端->>后端: 查询结果
    后端-->>前端: 结果数据
```

### 评估流程

评估模块独立于仿真模块运行，支持以下两种模式：

1. **联合模式**：仿真完成后自动触发评估
2. **独立模式**：手动选择历史仿真结果进行评估

评估结果包含各项质量指标的得分、失败案例分类以及完整的对话记录，便于开发人员定位问题根因。

## 配置管理

Web UI的配置通过YAML文件管理，主要配置项包括：

| 配置项 | 说明 | 默认值 |
|-------|------|-------|
| `agent_config` | Agent连接配置 | - |
| `scenarios` | 测试场景定义 | - |
| `metrics` | 评估指标列表 | - |
| `trace_receiver` | 追踪接收器配置 | `{enabled: false}` |

### 追踪接收器配置

对于支持追踪功能的Agent，配置启用追踪接收器：

```yaml
trace_receiver:
  enabled: true
  wait_timeout: 5
```

当 `enabled` 为 `true` 时，系统会从 `TracingProcessor.on_span_end` 事件中自动捕获工具调用，替代传统的 `AgentResponse` 方式。

## 前端状态管理

前端使用Alpine.js的 `data` 属性定义全局状态对象：

```javascript
data() {
    return {
        activePage: 'build',
        results: [],
        logs: [],
        isRunning: false
    }
}
```

### 状态变量说明

| 变量名 | 类型 | 用途 |
|-------|------|-----|
| `activePage` | string | 当前激活的页面标识 |
| `results` | array | 仿真/评估结果缓存 |
| `logs` | array | WebSocket接收的日志 |
| `isRunning` | boolean | 任务执行状态标志 |

## 页面功能详解

### 结果页面（Results）

结果页面提供仿真和评估结果的完整展示，采用卡片式布局：

- **评分卡片**：展示各维度的质量得分
- **失败分类**：按问题类型组织失败案例
- **对话查看器**：完整展示每轮交互的输入输出

页面顶部的刷新按钮触发 `refreshResults()` 函数，该函数调用后端API获取最新结果并更新前端状态。

### 仿真页面（Simulate）

仿真页面是执行测试的核心界面，主要功能包括：

- 配置仿真参数
- 启动/停止仿真任务
- 实时查看仿真日志
- 监控仿真进度

### 评估页面（Evaluate）

评估页面允许用户：

- 选择要评估的仿真结果
- 配置评估指标
- 调整评估阈值
- 查看详细评估报告

## 部署与启动

### 启动命令

```bash
arksim web
```

该命令启动FastAPI服务器并自动打开浏览器访问Web UI界面。

### 环境要求

- Python 3.10+
- 浏览器支持ES6+
- 网络访问（用于加载外部资源）

## 扩展机制

### 自定义Agent集成

Web UI支持通过配置文件集成自定义Agent：

```yaml
agent_config:
  agent_type: custom
  agent_name: my-agent
  api_config:
    endpoint: http://localhost:8000/agent
```

### 自定义评估指标

用户可在 `custom_metrics/` 目录下添加自定义评估逻辑，系统会自动加载并应用到评估流程中。

## 相关资源

- 用户指南：查看[主README](../README.md)了解基本用法
- 集成示例：参考[examples目录](../../examples/)下的完整案例
- 配置参考：[配置文件格式说明](#配置管理)

---

---

## Doramagic 踩坑日志

项目：arklexai/arksim

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

## 1. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | README/documentation is current enough for a first validation pass.

## 2. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | last_activity_observed missing

## 3. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | no_demo; severity=medium

## 4. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | No sandbox install has been executed yet; downstream must verify before user use.

## 5. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | no_demo; severity=medium

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | art_e3064c2689144cfb89a534e0544c6bfc | https://github.com/arklexai/arksim#readme | release_recency=unknown

<!-- canonical_name: arklexai/arksim; human_manual_source: deepwiki_human_wiki -->
