PHPackages                             kode/ai-agent - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. kode/ai-agent

ActiveLibrary

kode/ai-agent
=============

企业级 PHP AI Agent 层，兼容 Symfony AI 生态，支持协程、管道和 SSE 流式响应。新增文本生成图像、文本生成视频、数字人等多模态 API 支持，以及分工代理、主管 Agent 协调等高级功能。实现协程安全的执行上下文管理。

1.6.0(1mo ago)00Apache-2.0PHPPHP ^8.2

Since Mar 19Pushed 1mo agoCompare

[ Source](https://github.com/kodephp/ai-agent)[ Packagist](https://packagist.org/packages/kode/ai-agent)[ RSS](/packages/kode-ai-agent/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (14)Versions (4)Used By (0)

Kode AI Agent
=============

[](#kode-ai-agent)

企业级 PHP AI Agent 层，兼容 Symfony AI 生态，支持协程、管道和 SSE 流式响应。

[![PHP Version](https://camo.githubusercontent.com/9051b6544f57608ca691a918b38ad8c567657e0ecb6d4e960be274f287d171d8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3838393242462e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/a549a7a30bacba7bfceebdc207a8e86c3f2c02995a2527640dca30048fd2b64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d417061636865253230322e302d626c75652e737667)](https://opensource.org/licenses/Apache-2.0)

特性
--

[](#特性)

- **六边形架构**：核心逻辑与外部依赖解耦，依赖方向正确
- **多平台支持**：OpenAI、Anthropic Claude、DeepSeek、阿里云通义千问、Google Gemini、百度文心一言、腾讯混元、讯飞星火
- **API Key 轮换**：支持单 Key、双 Key（主备）、多 Key 轮换模式
- **工具调用循环**：自动处理 AI 工具调用，支持多轮调用
- **管道中间件**：灵活的请求处理管道，支持缓存、限流、重试
- **流式响应**：内置 SSE (Server-Sent Events) 支持
- **向量数据库**：内置向量存储接口，支持 Milvus、Pinecone、Qdrant 等
- **MCP 协议**：完整的 Model Context Protocol 支持
- **安全增强**：HTTPS 强制检查、API Key 格式验证、日志脱敏
- **PSR 标准**：完全兼容 PSR-7, PSR-18, PSR-17, PSR-3, PSR-11, PSR-16
- **PHP 8.5 就绪**：支持 `#[NoDiscard]` 属性和管道操作符
- **Kode 生态集成**：集成 kode/context、kode/facade、kode/http-client、kode/attributes
- **多模态支持**：文本生成图像、文本生成视频、数字人视频生成
- **文件上传**：支持视频、音频等媒体文件的安全上传
- **进度跟踪**：实时任务进度反馈和状态管理

安装
--

[](#安装)

```
composer require kode/ai-agent
```

依赖包
---

[](#依赖包)

本项目依赖以下 kode 系列包：

包名说明`kode/tools`响应体 Message、字符串 Str、数组 Arr、时间 Time`kode/context`协程安全的上下文管理`kode/facade`门面模式支持`kode/http-client`多运行时 HTTP 客户端`kode/attributes`注解解析器快速开始
----

[](#快速开始)

### 1. 使用适配器工厂（推荐）

[](#1-使用适配器工厂推荐)

```
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

// 快速创建 OpenAI 适配器
$adapter = AdapterFactory::openai('sk-xxx', [
    'model' => 'gpt-4o',
    'timeout' => 30,
]);

// 快速创建 Anthropic 适配器
$adapter = AdapterFactory::anthropic('sk-ant-xxx');

// 快速创建 Gemini 适配器
$adapter = AdapterFactory::gemini('AIza-xxx');

// 通用创建方式
$adapter = AdapterFactory::create('deepseek', [
    'api_key' => 'sk-xxx',
    'model' => 'deepseek-chat',
]);
```

### 2. 使用构建器

[](#2-使用构建器)

```
use Kode\AiAgent\Support\Builder\AgentBuilder;

// 构建适配器
$adapter = AgentBuilder::create()
    ->withPlatform('openai')
    ->withApiKey('sk-xxx')
    ->withModel('gpt-4o')
    ->withTemperature(0.7)
    ->withTimeout(60)
    ->withRetry(3, 1000)
    ->build();

// 构建 Agent（包含工具）
$agent = AgentBuilder::create()
    ->withPlatform('openai')
    ->withApiKey('sk-xxx')
    ->withSystemPrompt('你是一个有用的助手')
    ->withTool('calculator', '计算器', fn($a, $b) => $a + $b)
    ->withMaxToolCalls(5)
    ->buildAgent();
```

### 3. 使用门面类

[](#3-使用门面类)

```
use Kode\AiAgent\Support\Facade\Ai;
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

// 设置默认适配器
$adapter = AdapterFactory::openai('sk-xxx');
Ai::setDefaultAdapter($adapter);

// 发送消息
$response = Ai::chat('你好，世界！');
echo $response->content();

// 流式响应
foreach (Ai::stream('讲一个故事') as $chunk) {
    echo $chunk;
}
```

### 4. 多模型分工代理（总工/分析员/执行员）

[](#4-多模型分工代理总工分析员执行员)

```
use Kode\AiAgent\Agent\Agent;
use Kode\AiAgent\Agent\RoleAgentTeam;
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

$chief = new Agent(AdapterFactory::openai('sk-chief-xxx', ['model' => 'gpt-4o']));
$analyst = new Agent(AdapterFactory::deepseek('sk-analyst-xxx', ['model' => 'deepseek-chat']));
$executor = new Agent(AdapterFactory::anthropic('sk-exec-xxx', ['model' => 'claude-3-5-sonnet']));

$team = (new RoleAgentTeam())
    ->assign('总工', $chief)
    ->assign('分析员', $analyst)
    ->assign('执行员', $executor);

$result = $team->run('建设 MCP 工具链路', [
    ['role' => '总工', 'task' => '根据目标制定技术路线：{{goal}}'],
    ['role' => '分析员', 'task' => '拆解任务并识别风险'],
    ['role' => '执行员', 'task' => '按拆解结果输出实现步骤'],
]);

foreach ($result['outputs'] as $output) {
    echo "[{$output['role']}] {$output['content']}\n";
}

// 自动路由：根据任务内容命中角色
$team->routes([
    '架构|方案|设计' => '总工',
    '分析|风险|拆解' => '分析员',
    '开发|实现|修复' => '执行员',
]);

$auto = $team->auto('请先分析需求并识别风险');
echo $auto->content();
```

### 4.1 通过 Ai 门面快速构建团队

[](#41-通过-ai-门面快速构建团队)

```
use Kode\AiAgent\Support\Facade\Ai;
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

Ai::register('chief', AdapterFactory::openai('sk-chief-xxx'));
Ai::register('analyst', AdapterFactory::deepseek('sk-analyst-xxx'));
Ai::register('executor', AdapterFactory::anthropic('sk-exec-xxx'));

$team = Ai::team([
    '总工' => 'chief',
    '分析员' => 'analyst',
    '执行员' => 'executor',
]);
```

### 5. MCP Client/Server 协作

[](#5-mcp-clientserver-协作)

```
use Kode\AiAgent\MCP\MCPClient;
use Kode\AiAgent\MCP\MCPServer;

$server = new MCPServer(['name' => 'demo-mcp', 'version' => '1.0.0']);
$server->registerTool('sum', '求和', fn(array $args) => ($args['a'] ?? 0) + ($args['b'] ?? 0), [
    'a' => 'number',
    'b' => 'number',
]);

$client = new MCPClient(transport: fn(array $request) => $server->handle($request));
$client->connect('mcp://local');

$tools = $client->listTools();
$value = $client->callTool('sum', ['a' => 1, 'b' => 2]);
```

输入校验与安全策略
---------

[](#输入校验与安全策略)

- 主链路默认启用输入校验：提示词空值、长度、控制字符、常见参数范围会在调用前校验
- `chat/stream` 会先校验消息与 options，再进入适配器请求阶段
- 基础 URL 采用严格 HTTPS 策略：非 `https://` 地址会直接抛出配置异常
- 响应输出统一使用 `kode/tools` 的 Message 结构，便于业务层一致处理

支持的平台
-----

[](#支持的平台)

平台别名适配器认证方式默认模型OpenAI-`OpenAiAdapter`API Keygpt-4oAnthropicclaude`AnthropicAdapter`API Keyclaude-3-5-sonnetDeepSeek-`DeepSeekAdapter`API Keydeepseek-chat阿里云qwen, tongyi`AliyunAdapter`API Key / AppKey+AppSecretqwen-turboGooglegemini`GeminiAdapter`API Keygemini-2.0-flash百度wenxin, ernie`BaiduAdapter`API Key + Secret Keycompletions\_pro腾讯hunyuan`TencentAdapter`SecretId + SecretKeyhunyuan-lite讯飞spark, xinghuo`XunfeiAdapter`AppId + API Key + API Secretgeneralv3.5```
// 检查平台支持
AdapterFactory::supports('openai');    // true
AdapterFactory::supports('claude');    // true (别名)
AdapterFactory::supports('unknown');   // false

// 获取所有支持的平台
$platforms = AdapterFactory::supported();
// ['openai', 'anthropic', 'claude', 'deepseek', 'aliyun', 'qwen', 'tongyi',
//  'gemini', 'google', 'baidu', 'wenxin', 'ernie', 'tencent', 'hunyuan',
//  'xunfei', 'spark', 'xinghuo']
```

### 国内平台认证配置

[](#国内平台认证配置)

```
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

// 百度文心一言（需要 API Key + Secret Key 获取 Access Token）
$adapter = AdapterFactory::baidu('your-api-key', 'your-secret-key', [
    'model' => 'completions_pro',
]);

// 或直接使用 Access Token
$adapter = AdapterFactory::create('baidu', [
    'access_token' => 'your-access-token',
    'model' => 'completions_pro',
]);

// 腾讯混元（使用 TC3-HMAC-SHA256 签名）
$adapter = AdapterFactory::tencent('your-secret-id', 'your-secret-key', [
    'model' => 'hunyuan-lite',
    'region' => 'ap-guangzhou',
]);

// 讯飞星火（三元组认证：AppId + API Key + API Secret）
$adapter = AdapterFactory::xunfei('your-app-id', 'your-api-key', 'your-api-secret', [
    'model' => 'generalv3.5',
]);

// 阿里云通义千问（支持两种认证方式）
// 方式1: API Key
$adapter = AdapterFactory::aliyun('your-api-key');

// 方式2: AppKey + AppSecret（签名认证）
$adapter = AdapterFactory::create('aliyun', [
    'app_key' => 'your-app-key',
    'app_secret' => 'your-app-secret',
    'model' => 'qwen-turbo',
]);
```

API Key 管理
----------

[](#api-key-管理)

### 单 Key 模式

[](#单-key-模式)

```
use Kode\AiAgent\Domain\ValueObject\ApiKey;

$key = ApiKey::fromEnv('OPENAI_API_KEY');
// 或
$key = ApiKey::fromString('sk-1234567890abcdefghijklmnop');

echo $key->value();    // sk-1234567890abcdefghijklmnop
echo $key->masked();   // sk-1...mnop
echo $key->isValid();  // true
```

### 双 Key 模式（主备）

[](#双-key-模式主备)

```
$key = ApiKey::dual('sk-primary-xxx', 'sk-secondary-xxx');

echo $key->current();   // sk-primary-xxx (主 Key)
echo $key->strategy();  // failover

// 主 Key 失败时切换
$failed = $key->failover();
echo $failed->current(); // sk-secondary-xxx
```

### 多 Key 轮换模式

[](#多-key-轮换模式)

```
$key = ApiKey::rotating([
    'sk-key-one-xxx',
    'sk-key-two-xxx',
    'sk-key-three-xxx',
], 'round_robin');

echo $key->current();   // sk-key-one-xxx
echo $key->next();      // sk-key-two-xxx
echo $key->count();     // 3

// 轮换到下一个
$rotated = $key->rotate();
echo $rotated->current(); // sk-key-two-xxx
```

### AppKey + AppSecret 模式

[](#appkey--appsecret-模式)

适用于阿里云、百度、腾讯云等需要双凭证的平台：

```
// 创建 AppKey + AppSecret 凭证
$key = ApiKey::appSecret('app-key-xxx', 'app-secret-xxx', [
    'region' => 'cn-hangzhou',
    'account_id' => '123456',
]);

echo $key->appKey();        // app-key-xxx
echo $key->secret();     // app-secret-xxx
echo $key->extra('region'); // cn-hangzhou

// 检查模式
$key->isAppSecretMode();    // true

// 生成签名
$signature = $key->sign('POST', '/v1/chat', ['query' => 'hello']);

// 生成带签名的请求头
$headers = $key->signedHeaders('POST', '/v1/chat', ['query' => 'hello']);
// [
//     'X-App-Key' => 'app-key-xxx',
//     'X-Timestamp' => '1709512800',
//     'X-Nonce' => 'abc123...',
//     'X-Signature' => 'hmac-sha256...',
// ]

// 获取脱敏凭证信息
$masked = $key->maskedCredentials();
// ['app_key' => 'app-...-xxx', 'app_secret' => 'app-...-xxx']
```

### 从配置创建

[](#从配置创建)

```
// 单 Key
$key = ApiKey::fromArray([
    'api_key' => 'sk-xxx',
]);

// 多 Key 轮换
$key = ApiKey::fromArray([
    'keys' => ['sk-1', 'sk-2', 'sk-3'],
    'strategy' => 'round_robin',  // 或 'random', 'failover'
]);

// AppKey + AppSecret（阿里云、百度等）
$key = ApiKey::fromArray([
    'app_key' => 'your-app-key',
    'app_secret' => 'your-app-secret',
    'extra' => [
        'region' => 'cn-hangzhou',
        'account_id' => '123456',
    ],
]);
```

向量数据库 (Store 组件)
----------------

[](#向量数据库-store-组件)

### 内存向量存储（用于测试和简单场景）

[](#内存向量存储用于测试和简单场景)

```
use Kode\AiAgent\Store\MemoryVectorStore;

// 创建内存向量存储
$store = new MemoryVectorStore(dimension: 1536);

// 插入向量
$store->upsert('doc-1', [0.1, 0.2, 0.3], ['title' => '文档1']);
$store->upsert('doc-2', [0.4, 0.5, 0.6], ['title' => '文档2']);

// 批量插入
$store->upsertBatch([
    ['id' => 'doc-3', 'vector' => [0.7, 0.8, 0.9], 'metadata' => ['title' => '文档3']],
    ['id' => 'doc-4', 'vector' => [1.0, 1.1, 1.2], 'metadata' => ['title' => '文档4']],
]);

// 相似度搜索（余弦相似度）
$results = $store->search([0.1, 0.2, 0.3], limit: 5, filters: []);
// [
//     ['id' => 'doc-1', 'score' => 1.0, 'metadata' => ['title' => '文档1'],
//     ['id' => 'doc-2', 'score' => 0.95, 'metadata' => ['title' => '文档2'],
// ]

// 获取向量
$doc = $store->get('doc-1');

// 删除向量
$store->delete('doc-1');

// 获取向量数量
$count = $store->count();

// 清空所有向量
$store->clear();
```

MCP (模型上下文协议)
-------------

[](#mcp-模型上下文协议)

### MCP 服务器

[](#mcp-服务器)

```
use Kode\AiAgent\MCP\MCPServer;

// 创建 MCP 服务器
$server = new MCPServer([
    'name' => 'my-mcp-server',
    'version' => '1.0.0',
]);

// 注册工具
$server->registerTool(
    name: 'calculator',
    description: '执行数学计算',
    handler: function (array $args) {
        $a = $args['a'] ?? 0;
        $b = $args['b'] ?? 0;
        return $a + $b;
    },
    parameters: ['a' => 'number', 'b' => 'number']
);

// 注册资源
$server->registerResource(
    uri: 'file:///data/config.json',
    provider: fn() => file_get_contents('config.json'),
    mimeType: 'application/json'
);

// 处理 JSON-RPC 请求
$response = $server->handle([
    'jsonrpc' => '2.0',
    'method' => 'tools/call',
    'params' => ['name' => 'calculator', 'arguments' => ['a' => 1, 'b' => 2],
    'id' => 1,
]);
```

工具调用
----

[](#工具调用)

### 注册工具

[](#注册工具)

```
use Kode\AiAgent\Agent\Agent;

$agent = new Agent($adapter, [
    'system_prompt' => '你是一个有用的助手',
    'max_tool_calls' => 5,
]);

// 注册工具
$agent->registerTool('calculator', '执行数学计算', function (int $a, int $b, string $op = 'add'): int|float {
    return match($op) {
        'add' => $a + $b,
        'sub' => $a - $b,
        'mul' => $a * $b,
        'div' => $a / $b,
    };
});

// 发送消息（自动处理工具调用）
$response = $agent->chat('计算 10 + 5');
echo $response->content();
```

### 使用注解注册工具

[](#使用注解注册工具)

```
use Kode\AiAgent\Attribute\Tool;
use Kode\AiAgent\Agent\Agent;

class MyTools
{
    #[Tool(name: 'weather', description: '获取天气信息')]
    public function getWeather(string $city): string
    {
        return "{$city}今天晴，温度 25°C";
    }

    #[Tool(name: 'search', description: '搜索网络')]
    public function search(string $query): array
    {
        return ['results' => ["关于 {$query} 的结果..."];
    }
}

// 从类自动注册
$agent = Agent::fromClass(new MyTools(), $adapter);
```

对话管理
----

[](#对话管理)

```
use Kode\AiAgent\Chat\ChatSession;
use Kode\AiAgent\Infrastructure\Adapter\AdapterFactory;

$adapter = AdapterFactory::openai('sk-xxx');
$chat = new ChatSession($adapter, '你是一个有用的助手');

// 发送消息
$response = $chat->send('你好！');
echo $response->content();

// 继续对话（自动维护上下文）
$response = $chat->send('请继续');
echo $response->content();

// 流式对话
foreach ($chat->stream('讲个故事') as $chunk) {
    echo $chunk;
    flush();
}

// 查看对话历史
$messages = $chat->messages();
$count = $chat->count();

// 导出对话
$history = $chat->export();

// 清空历史
$chat->clear();
```

多模态功能
-----

[](#多模态功能)

Kode AI Agent 提供完整的多模态能力支持，包括文本生成图像、文本生成视频、数字人视频生成等多种功能。

### 架构概述

[](#架构概述)

多模态功能采用统一的架构设计：

- **能力发现**: 通过 `MultimodalCapability` 枚举定义和发现平台支持的能力
- **统一接口**: `MultimodalInterface` 整合图像、视频、数字人等所有能力
- **服务层**: `MultimodalService` 提供高级服务功能
- **门面调用**: `Multimodal` 门面类提供简洁的静态调用接口
- **辅助函数**: 提供 `ai_generate_image()`、`ai_generate_video()` 等快速方法

### 快速开始

[](#快速开始-1)

#### 1. 创建自定义多模态适配器

[](#1-创建自定义多模态适配器)

首先，创建一个继承自 `AbstractMultimodalAdapter` 的适配器：

```
