PHP SDK 使用开发指南
pigagent/pig 是 100% 纯 PHP 开发的编码智能体引擎。您可以通过标准的 Composer 依赖引入,在任何 PHP 8.3+ 项目中原生调用和嵌入 pig agent 的会话、大模型、工具、Skills 和上下文工程系统。
原生进程内深度集成,全套 API 强类型面向对象驱动。
安装依赖
#composer require pigagent/pig
确保系统满足基础 PHP 扩展要求:ext-json、ext-mbstring、ext-openssl、ext-pcntl、ext-pcre。
pig 的 I/O 运行在 PHP Fiber 和单个事件循环之上。所有与模型通信或运行工具的调用都必须在 Pig\Async\Async::run() 内进行;它会启动事件循环,并在闭包及其启动的所有任务完成后返回。
快速上手:一键创建 Agent 会话
#CodingAgent::session() 以与 bin/pig 相同的方式组装会话:它会发现工作区上下文(AGENTS.md / CLAUDE.md、SYSTEM.md、Skills 技能、提示词模板和扩展),并根据参数和设置解析模型。设置和凭据由调用方传入,因此由调用方决定它们的来源:
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Pig\Async\Async;
use Pig\CodingAgent\Auth;
use Pig\CodingAgent\CodingAgent;
use Pig\CodingAgent\CustomModels;
use Pig\CodingAgent\Settings;
Async::run(static function (): void {
$cwd = getcwd();
// 1. Settings (~/.pig/agent/settings.json and .pig/settings.json) and credentials
// (auth.json, then the providers' environment variables)
$settings = Settings::load($cwd);
$auth = Auth::discover(settings: $settings);
// Optional: models.json, so custom providers and models resolve
CustomModels::discover()->install($auth);
// 2. The session
$started = CodingAgent::session(
$cwd,
$settings,
$auth,
model: 'claude-opus-5-5',
thinking: 'medium',
);
foreach ($started->warnings as $warning) {
fwrite(STDERR, "warning: {$warning}\n");
}
$session = $started->session;
// 3. Send a prompt; returns once the turn, its tool calls, and any queued messages are done
$session->prompt('List files in the current directory and check for issues');
// 4. The latest assistant text
echo $session->lastAssistantText() . PHP_EOL;
// 5. Drop listeners and let go of the agent
$session->dispose();
});
model 接受与 --model 相同的模式(sonnet、anthropic/claude-opus-5-5、sonnet:high);provider 用于限定查找范围。其他命名参数与命令行一一对应:tools、excludeTools、noTools、readOnly、models、resume(一个会话文件)、continue、save、sessionId、systemPrompt、appendSystemPrompt、extensionPaths、skillPaths、promptTemplatePaths、withExtensions、withSkills、withPromptTemplates、withContextFiles 和 projectTrusted。Settings::load($cwd, projectTrusted: false) 和 projectTrusted: false 可以排除项目自身的文件。
CodingAgent::session() 会抛出 CodingAgentError,其消息可以直接展示给用户,例如没有任何模型具备凭据时。
$started(一个 StartedSession)还携带解析后的 model、thinking、contextFiles、skills、extensionRunner、customTools、store 和 extensions。
轻量级底座:自定义构建 Agent(不带会话持久化)
#如果您需要在守护进程、Web API 或脚本中运行只读/临时任务,可以直接使用 CodingAgent::create():它会构建一个带有 pig 工具和系统提示词的裸 Pig\Agent\Agent,不包含设置、会话或扩展:
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Pig\Agent\ThinkingLevel;
use Pig\Agent\ToolExecutionEndEvent;
use Pig\Agent\ToolExecutionStartEvent;
use Pig\Ai\Models;
use Pig\Async\Async;
use Pig\CodingAgent\CodingAgent;
use Pig\CodingAgent\Tools\ToolSet;
// Resolve a model from the catalog
$model = Models::find('anthropic', 'claude-opus-5-5');
// Read-only agent: read, grep, find, ls
$agent = CodingAgent::create(
model: $model,
cwd: '/path/to/project',
tools: ToolSet::READ_ONLY,
apiKey: getenv('ANTHROPIC_API_KEY') ?: null,
thinking: ThinkingLevel::High,
);
// Subscribe to execution lifecycle events
$agent->subscribe(static function ($event): void {
if ($event instanceof ToolExecutionStartEvent) {
echo "Executing tool: {$event->toolName}...\n";
}
if ($event instanceof ToolExecutionEndEvent) {
echo "Tool {$event->toolName} " . ($event->isError ? 'failed' : 'completed') . "\n";
}
});
// Run the prompt
Async::run(static fn () => $agent->prompt('Find all files with TODO comments'));
if ($agent->state->error !== null) {
fwrite(STDERR, $agent->state->error . "\n");
}
ToolSet::CODING(默认)为 read、bash、edit、write;ToolSet::READ_ONLY 为 read、grep、find、ls;ToolSet::ALL 额外加入 powershell 及其余工具。CodingAgent::model($id) 仅凭 ID 查找模型。完整脚本请参阅 examples/agent.php。
会话持久化与分支管理 (SessionManager)
#默认情况下,CodingAgent::session() 会将对话自动保存为只追加的 JSONL 树状文件(保存在 ~/.pig/agent/sessions/ 下)。
1. 纯内存会话(不写入磁盘)
#$started = CodingAgent::session(
$cwd,
$settings,
$auth,
save: false, // nothing is written; the session still has an ID (sessionId: sets it)
);
2. 多分支时光机与树状回溯 (/tree)
#AgentSession 支持在同一会话文件中创建非破坏性分支树。goTo() 需要已保存的会话:
// The current branch, root to leaf
$branch = $session->store()->branch();
// Jump back to a historical entry ID (returns a TreeJump)
$jump = $session->goTo($targetEntryId, summarise: true);
if ($jump->cancelled) {
echo "An extension cancelled the navigation\n";
} elseif ($jump->moved) {
echo "Jumped to historical entry.\n";
if ($jump->summary !== null) {
echo "Branch summary:\n" . $jump->summary->summary . "\n";
}
// Going back to a user message lands before it and hands its text back
if ($jump->editorText !== null) {
echo "Re-ask: {$jump->editorText}\n";
}
}
goTo() 还接受 instructions、replaceInstructions 和 label,与 RPC 的 navigate_tree 相同。
3. 会话压缩 (compact)
#当上下文超过阈值时,pig 会自动进行压缩。手动压缩方式如下:
// Returns the CompactionSummary entry it wrote, or null when it was called off
$compaction = $session->compact('Focus on database schema and authentication changes');
if ($compaction !== null) {
echo "Compacted {$compaction->tokensBefore} tokens into:\n{$compaction->summary}\n";
}
当 agent 正在工作、没有可压缩的内容、扩展取消了压缩(Compaction cancelled)或模型调用失败时,compact() 会抛出 AgentError。
Codemode 与 MCP
#SDK 会话不会加载内置扩展(builtin:mcp、builtin:llama.cpp、builtin:codemode、builtin:tool-search、builtin:schedule)。请通过 extensionPaths 传入需要的扩展,并接好 runner,让扩展能收到 session_start——MCP 扩展正是在此时连接其服务器:
use Pig\CodingAgent\Extensions\BuiltinExtensions;
use Pig\CodingAgent\Extensions\Events\SessionStartEvent;
use Pig\CodingAgent\Extensions\NoUi;
$started = CodingAgent::session($cwd, $settings, $auth, extensionPaths: array_filter([
BuiltinExtensions::pathOf('mcp'), // mcp.json servers
BuiltinExtensions::pathOf('codemode'), // `codemode` / `codemode-deferred` exposure
BuiltinExtensions::pathOf('tool-search'), // `deferred` exposure
]));
$started->extensionRunner->wire($started->session, new NoUi());
$started->extensionRunner->emit(new SessionStartEvent());
Pig\CodingAgent\PrintMode 会替你完成这些接线:(new PrintMode($session, 'text', $started->extensionRunner, $started->customTools))->run(['your prompt']) 会发送提示词、输出回答,并返回与 pig -p 相同的退出码。
异步协程与中断并发控制
#pig 基于原生 PHP Fiber 协程调度与 stream_select,所有长时间操作(流式输出、工具执行、HTTP 网络等待)均可在协程中随时安全中断:
// From another fiber, a signal handler, or a hook: stop the prompt in progress.
// abort() returns a Future that resolves once the session is idle.
$session->abort()->await();
$session->isIdle(); // true
steer($text) 和 followUp($text) 会在提示词运行期间将消息排入队列;prompt($text, streamingBehavior: 'steer') 对在回合中途发送的提示词起同样的作用。
消息类型参考与协议对齐
#UserMessage:用户消息,支持文本(TextContent)与多模态图片(ImageContent)。AssistantMessage:助手回复,包含文本、思考块(ThinkingContent)与工具调用(ToolCall)。ToolResultMessage:工具执行返回结果。- 更多数据结构契约与字段定义,请参阅 消息类型文档。