> For the complete documentation index, see [llms.txt](https://docs.neuron-ai.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neuron-ai.dev/neuron-v3-zh/agent/async.md).

# 异步

Neuron 支持异步执行和代理并行处理，使你能够高效地同时处理多个操作。Neuron 的异步执行方式提供了以下几个优势：

**框架无关**：你可以通过一个简单的适配器，让代理和 RAG 适配最常见的异步环境，无需对你的实现做任何修改。

**提供商兼容性**：无论你使用哪种提供商，我们的方案都能正常工作。你可以让使用不同提供商和模型的工作流或多智能体系统在异步循环中平稳运行。

**可扩展性**：处理大量数据的应用（商品分类、内容审核、数据标注）能显著受益于并发处理能力。

### 并发 vs 异步

并发是管理任务的高层概念，它可以涉及多个线程/核心（并行），而异步则使用事件循环/回调，让任务无序执行，非常适合 I/O 密集型工作，无需等待。

并发是关于同时管理许多事物，而异步则是一种让单线程高效管理多个 I/O 操作的方式。

AI 代理通常被视为 I/O 密集型软件，因为对模型进行推理的 HTTP 请求通常需要数秒才能完成。在标准 PHP 环境中，这段时间你的应用只会等待。在本文档的这一部分，我们为你提供了几个高效运行多个代理的解决方案。

## 并发

在并行运行多个代理时，你不需要 Neuron 提供任何特定功能。你只需要你的 PHP 应用能够扩展到多个进程，以便同时处理多个代理的执行。你可以使用 PHP 库，如 [spatie/fork](https://github.com/spatie/fork)，或者框架特定的方案，如 [Laravel 并发](https://laravel.com/docs/master/concurrency)，或者 [Symfony 进程](https://symfony.com/doc/current/components/process.html).

异步则是另一回事。

## 异步

Neuron 的前几个版本与 Guzzle 客户端强耦合，用于向提供商的 API 发起模型推理的 HTTP 请求。Guzzle 是一个很好的工具，但它与真正的异步事件循环并不兼容，例如像以下框架提供的那样： [Amp](https://github.com/amphp/amp) 和 [ReactPHP](https://github.com/reactphp/reactphp).

为了在这类异步环境中运行代理，需要与其特定实现集成。这就是 Neuron 附带一个简单的 `HttpClientInterface` ，它可以被实现，以允许 AI 提供商在异步循环中平稳地运行 HTTP 请求。

默认情况下，框架使用 Guzzle 实现，但你可以根据需要注入自定义 HTTP 客户端。我们已经为最常见的异步框架提供了实现。

### AmpHttpClient

如果你想使用 Amp 运行多个异步代理请求，你需要安装 `amphp/http-client` .

```bash
composer require amphp/http-client
```

现在你可以将内置的 `AmpHttpClient` 适配器注入到提供商中：

```php
namespace App\Neuron;

use NeuronAI\Agent\Agent;
use NeuronAI\\HttpClient\\AmpHttpClient;
use NeuronAI\Providers\Anthropic\Anthropic;

class MyAgent extends Agent
{
    protected function provider(): AIProviderInterface
    {
        // 对任何提供商都一样（Anthropic、OpenAI、Ollama、Gemini 等）
        return new Anthropic(
            key: 'ANTHROPIC_API_KEY',
            model: 'ANTHROPIC_MODEL',
            httpClient: new AmpHttpClient(),
        );
    }
}
```

现在你可以使用 Amp 的 async/await 模式运行多个代理请求，以异步方式运行多个代理：

```php
use Amp\Future;

use function Amp\async;

$handler1 = MyAgent::make()->chat(new UserMessage('你好！'));
$handler2 = MyAgent::make()->chat(new UserMessage('你好！'));
$handler3 = MyAgent::make()->chat(new UserMessage('你好！'));

// 并行运行三个请求
[$response1, $response2, $response3] = Future\await([
    async(fn() => $handler1->getMessage()), 
    async(fn() => $handler2->getMessage()),
    async(fn() => $handler3->getMessage()),
]);

// 打印内容
echo $response1->getContent();
echo $response2->getContent();
echo $response3->getContent();
```

### 异步 RAG

HTTP 客户端抽象也被所有其他框架组件接受，例如嵌入提供商和向量存储。你可以为所有这些组件提供异步客户端，并且还可以异步运行数据加载流水线。

```php
class MyChatBot extends RAG
{
    protected function provider(): AIProviderInterface
    {
        return new Anthropic(
            key: 'ANTHROPIC_API_KEY',
            model: 'ANTHROPIC_MODEL',
            httpClient: new AmpHttpClient(),
        );
    }
    
    protected function embeddings(): EmbeddingsProviderInterface
    {
        return new VoyageEmbeddingsProvider(
            key: 'OPENAI_API_KEY',
            model: 'OPENAI_MODEL'
            httpClient: new AmpHttpClient(),
        );
    }
    
    protected function vectorStore(): VectorStoreInterface
    {
        return new PineconeVectorStore(
            key: 'PINECONE_API_KEY',
            indexUrl: 'PINECONE_INDEX_URL',
            httpClient: new AmpHttpClient(),
        );
    }
}
```

### 护栏

能够异步执行代理，使得可以在主请求的同时运行输入护栏。通常你可以创建一个专门的代理来对用户输入执行安全检查，并使用结构化响应来获取结果。

你可以并行运行这两个请求，并在向用户返回响应之前检查护栏结果。并行运行这两个请求可以让你在不影响用户体验的情况下实施安全控制。

```php
use Amp\Future;
use function Amp\async;

$input = new UserMessage('你好！');

// 并行运行三个请求
[$response, $guardrail] = Future\await([
    async(fn() => MyAgent::make()->chat($input)->getMessage()), 
    async(fn() => GuardrailAgent::make()->structured($input, Guardrail::class)),
]);

if (! $guardrail->valid) {
    throw \Exception('内容策略违规。');
}

// 打印内容
echo $response->getContent();
```
