
# Neuronのストリーミングステップ

この例では、明確な役割分担を示します。Neuronはエージェントの応答をチャンクごとにストリーミングし、Queuetyは`StreamingStep`を通じて各チャンクを耐久性をもって永続化します。そのため、UIは下書きをリアルタイムで受け取りながら、ワークフローはワーカーのクラッシュや再試行後も継続できます。

## このパターンが役立つ場面

下書きや応答が長くリアルタイムでストリーミングしたい場合、ワーカー停止時にも途中までの出力を失いたくない場合、ストリーム完了後に最終成果物をワークフロー状態に保存したい場合に使います。

## Neuronエージェント

```php
namespace App\Neuron;

use NeuronAI\Agent\Agent;
use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\Providers\OpenAI\Responses\OpenAIResponses;
use NeuronAI\SystemPrompt;

final class DraftMemoAgent extends Agent
{
    protected function provider(): AIProviderInterface
    {
        return new OpenAIResponses(
            key: $_ENV['OPENAI_API_KEY'],
            model: $_ENV['OPENAI_MODEL'],
        );
    }

    public function instructions(): string
    {
        return (string) new SystemPrompt(
            background: [
                'You write crisp internal strategy memos.',
                'Prefer short sections and operationally useful language.',
            ],
        );
    }
}
```

## Queuetyのストリーミングステップ

```php
namespace App\Workflow\Steps;

use App\Neuron\DraftMemoAgent;
use NeuronAI\Chat\Messages\UserMessage;
use Queuety\Contracts\StreamingStep;
use Queuety\Heartbeat;

final class StreamMemoDraftStep implements StreamingStep
{
    public function stream(array $state, array $existing_chunks = []): \Generator
    {
        if (! empty($existing_chunks)) {
            return;
        }

        $handler = (new DraftMemoAgent())->stream(
            new UserMessage(sprintf(
                "Write a strategy memo about %s for account %d.",
                $state['topic'],
                $state['account_id'],
            ))
        );

        foreach ($handler->events() as $i => $chunk) {
            Heartbeat::beat(['chunks' => $i + 1]);

            // This example assumes the agent has no tools attached, so
            // Neuron will stream text/reasoning chunks only.
            yield $chunk->content;
        }
    }

    public function on_complete(array $chunks, array $state): array
    {
        return [
            'draft_markdown' => implode('', $chunks),
        ];
    }

    public function config(): array
    {
        return [
            'max_attempts' => 3,
        ];
    }
}
```

## ワークフローで使う

```php
use Queuety\Queuety;

Queuety::workflow('memo_drafting')
    ->then(BuildDraftBriefStep::class)
    ->then(StreamMemoDraftStep::class)
    ->then(StoreMemoStep::class)
    ->dispatch([
        'account_id' => 10,
        'topic' => 'pricing changes for enterprise accounts',
    ]);
```

## NeuronのストリームアダプターだけでなくQueuetyを使う理由

Neuronのストリームアダプターは、フロントエンドのプロトコルやトランスポートに役立ちます。Queuetyは別の機能を追加します。出力されたチャンクはすべて永続化され、再試行時には保存済みのチャンクから再開できます。完成した下書きはワークフロー状態にマージされ、ストリームはより大きなオーケストレーションの中で耐久性のある1つのステップになります。

このパターンは、単なるリクエスト／レスポンスUIではなく、複数段階のビジネスプロセスの一部としてストリームを使う場合に適しています。

## 注意点

Neuronエージェントがストリーミング中にツールを使う場合は、ストリーミングされるチャンクの種類を明示的に処理してください。Neuronの現行ストリーミングドキュメントでは、`TextChunk`、`ReasoningChunk`、`ToolCallChunk`、`ToolResultChunk`について説明しています。バックグラウンドで下書きを作成するワークフローでは、通常、ストリーミングエージェントをテキストのみで使うのが最も簡単です。

## 関連ドキュメント

- [ストリーミングステップ](https://queuety.inline0.dev/ja/docs/workflows/streaming)
- [エージェントのオーケストレーション](https://queuety.inline0.dev/ja/docs/workflows/agent-orchestration)
