当前位置:首页>php>PHP+AI实战(四):Neuron-AI框架深度解析,从工具调用到多模型切换

PHP+AI实战(四):Neuron-AI框架深度解析,从工具调用到多模型切换

  • 2026-09-08 13:58:10
PHP+AI实战(四):Neuron-AI框架深度解析,从工具调用到多模型切换

前几期我们用原生 PHP 实现了 Agent 雏形。有读者问:有没有更专业的 PHP AI 框架?

答案是:Neuron-AI —— PHP 生态中最完整的 Agentic 框架,支持工具调用、对话记忆、多 Provider 无缝切换。

今天带你跑通 Neuron-AI 核心功能。

一、安装与配置

bashcomposer require neuron-core/neuron-ai

不需要额外 Laravel 包,纯 PHP 8.1+ 即可。

二、创建第一个 Agent(带记忆)

php<?phprequire 'vendor/autoload.php';use NeuronAI\Agent\Agent;use NeuronAI\Providers\DeepSeek\DeepSeek;use NeuronAI\Chat\Messages\UserMessage;classMyAgentextendsAgent{    protected function provider()    {        return new DeepSeek(            apiKey: getenv('DEEPSEEK_API_KEY'),            model: 'deepseek-chat'        );    }    public function instructions(): string    {        return "你是一个友好的助手,记住用户说过的重要信息。";    }}$agent = new MyAgent();$agent->chat(new UserMessage("我叫老杨"))->getMessage();$response = $agent->chat(new UserMessage("我叫什么?"))->getMessage();echo $response; // 输出:你叫老杨

对话记忆默认开启,无需额外代码。

三、给 Agent 装工具(Tool Calling)

以查天气为例,创建一个工具类:

phpuse NeuronAI\Tools\Tool;use NeuronAI\Tools\ToolProperty;classWeatherToolextendsTool{    public function __construct()    {        $this->name = 'get_weather';        $this->description = '获取城市天气';        $this->properties = [            ToolProperty::make('city')                ->type('string')                ->description('城市名')                ->required(true),        ];    }    protected function handle(array $params, ?callable $sendUpdate = null): string    {        $city = $params['city'];        // 调用真实 API 或返回模拟数据        return "{$city},晴天 26°C";    }}

在 Agent 中注册工具:

phpclass MyAgent extends Agent{    // ... provider, instructions ...    public function tools(): array    {        return [new WeatherTool()];    }}

测试:$agent->chat(new UserMessage("深圳天气")); → Agent 自动调用工具并回答。

四、一行代码切换 AI 模型

Neuron-AI 支持 OpenAI、DeepSeek、Anthropic、Gemini、Ollama 等。只需更换 Provider:

// 切换到 OpenAIuse NeuronAI\Providers\OpenAI\OpenAI;protected function provider(){    return new OpenAI(        apiKey: getenv('OPENAI_API_KEY'),        model: 'gpt-3.5-turbo'    );}

其他代码零改动,工具调用、对话记忆全部通用。

五、在 Laravel 中优雅使用

虽然不需要 neuron-laravel,但可以封装一个服务:

// app/Services/AIAgent.phpnamespace App\Services;use NeuronAI\Agent\Agent;use NeuronAI\Providers\DeepSeek\DeepSeek;classAIAgentextendsAgent{    protected function provider()    {        return new DeepSeek(            apiKey: config('services.deepseek.key'),            model: 'deepseek-chat'        );    }}

// 在任何地方调用

$agent = new AIAgent();$answer = $agent->chat(new UserMessage("问题"))->getMessage();

六、进阶:多 Agent 协作

Neuron-AI 支持 Workflow 编排,让多个 Agent 分工合作(一个查数据,一个写报告,一个审核)。后续单独开篇。

下期预告

用 Neuron-AI + RAG 构建企业级知识库问答系统,支持上传 PDF、Word。

最新文章

随机文章