Agent 是一种架构模式,跟用什么语言/框架实现无关。

chat

PHP、Python、Go、Java 都能实现,本质上就是:

1. 有一个 LLM 可以调用(API)
2. 有一组工具函数
3. 有一个循环:LLM 决策 → 执行工具 → 把结果喂回 LLM → 继续

 


用 PHP 实现一个最简 Agent

<?php

$tools = [
    'read_file' => fn($path) => file_get_contents($path),
    'write_file' => fn($path, $content) => file_put_contents($path, $content),
    'run_shell' => fn($cmd) => shell_exec($cmd),
    'http_get' => fn($url) => file_get_contents($url),
];

function callLLM(array $messages, array $toolDefinitions): array {
    $response = file_get_contents('<https://api.openai.com/v1/chat/completions>', false,
        stream_context_create(['http' => [
            'method' => 'POST',
            'header' => "Authorization: Bearer " . getenv('OPENAI_KEY') . "\nContent-Type: application/json",
            'content' => json_encode([
                'model' => 'gpt-4o',
                'messages' => $messages,
                'tools' => $toolDefinitions,
                'tool_choice' => 'auto',
            ])
        ]])
    );
    return json_decode($response, true);
}

// Agent 主循环
function runAgent(string $userGoal): string {
    global $tools;

    $messages = [['role' => 'user', 'content' => $userGoal]];

    while (true) {
        $result = callLLM($messages, getToolDefinitions());
        $choice = $result['choices'][0];

        // LLM 说"完成了"→ 退出循环
        if ($choice['finish_reason'] === 'stop') {
            return $choice['message']['content'];
        }

        // LLM 要调用工具 → 执行 → 结果喂回
        $messages[] = $choice['message'];

        foreach ($choice['message']['tool_calls'] as $toolCall) {
            $name = $toolCall['function']['name'];
            $args = json_decode($toolCall['function']['arguments'], true);

            // 动态决策:LLM 选了哪个工具就执行哪个
            $observation = call_user_func_array($tools[$name], $args);

            $messages[] = [
                'role' => 'tool',
                'tool_call_id' => $toolCall['id'],
                'content' => (string)$observation,
            ];
        }
        // 继续循环,LLM 看到结果后再决定下一步
    }
}

echo runAgent("帮我查一下 php.net 首页的标题是什么");

 


更直白地说

Agent 的核心就三样东西,跟语言无关:

组件PHP 里怎么做
调用 LLMfile_get_contents 请求 OpenAI API
执行工具普通 PHP 函数(读文件、跑命令、请求接口)
循环while(true) + 把结果塞回 $messages

甚至用 bash 脚本也能写一个简陋的 Agent,只要能发 HTTP 请求、能解析 JSON 就行。


一句话

Agent 不是某种特定技术,它是"让 LLM 驱动控制流"这种思想。任何能调 LLM API、能执行函数的环境,都可以实现。

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/3302/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Agent 是一种架构模式,跟用什么语言/框架实现无关。
PHP、Python、Go、Java 都能实现,本质上就是: 1. 有一个 LLM 可以调用(API) 2. 有一组工具函数 3. 有一个循环:LLM 决策 → 执行工具 → 把结果喂回 LLM ……
<<上一篇
下一篇>>
chat