?

インターフェース

internal/agent/provider.go (要約):

type Request struct {
    SessionID string
    System    string
    Messages  []Message
    Tools     []ToolDefinition
}

type Response struct {
    Message    Message
    StopReason StopReason
}

// Provider drives a single round-trip.
type Provider interface {
    Complete(ctx context.Context, req Request) (Response, error)
}

// StreamingProvider streams response deltas as they arrive.
type StreamingProvider interface {
    Provider
    CompleteStream(ctx context.Context, req Request) (StreamReader, error)
}

すべての LLM アダプタは少なくとも Provider を満たします。StreamingProvider はオプトインです — TUI とチャットトランスポートハンドラは、プロバイダが実装していない場合、非ストリーミングパスにフォールバックします。

StopReason は StopEndTurn、StopToolUse、StopMaxTokens のいずれかです。エージェントループは StopEndTurn を終端として扱い、StopToolUse を「モデルがツール呼び出しを要求している」として扱います。

新しいプロバイダのスケルトン

仮想的な Cohere Command R プロバイダを追加してみましょう。

ステップ 1 — ディレクトリ

internal/llm/cohere/
├── client.go        # Config, New
├── complete.go      # Provider.Complete
├── stream.go        # StreamingProvider.CompleteStream (optional)
└── *_test.go

ステップ 2 — client.go

// Package cohere implements the Cohere Command R provider.
package cohere

import (
    "net/http"
    "time"
)

// Config configures the Cohere provider.
type Config struct {
    APIKey    string
    Model     string
    BaseURL   string
    MaxTokens int64
}

// Provider is the Cohere adapter.
type Provider struct {
    cfg    Config
    client *http.Client
}

// New constructs a Provider.
func New(cfg Config) *Provider {
    if cfg.BaseURL == "" {
        cfg.BaseURL = "https://api.cohere.com/v1"
    }
    if cfg.MaxTokens == 0 {
        cfg.MaxTokens = 4096
    }
    return &Provider{
        cfg:    cfg,
        client: &http.Client{Timeout: 120 * time.Second},
    }
}

ステップ 3 — complete.go

Complete を実装します:

package cohere

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"

    "github.com/sebastienrousseau/rousseau-agent/internal/agent"
)

// Complete satisfies agent.Provider.
func (p *Provider) Complete(ctx context.Context, req agent.Request) (agent.Response, error) {
    body, err := p.encodeRequest(req)
    if err != nil {
        return agent.Response{}, fmt.Errorf("cohere: encode: %w", err)
    }

    httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, p.cfg.BaseURL+"/chat", bytes.NewReader(body))
    if err != nil {
        return agent.Response{}, err
    }
    httpReq.Header.Set("content-type", "application/json")
    httpReq.Header.Set("authorization", "Bearer "+p.cfg.APIKey)

    httpResp, err := p.client.Do(httpReq)
    if err != nil {
        return agent.Response{}, fmt.Errorf("cohere: transport: %w", err)
    }
    defer httpResp.Body.Close()

    if httpResp.StatusCode >= 400 {
        return agent.Response{}, fmt.Errorf("cohere: HTTP %d", httpResp.StatusCode)
    }

    var raw cohereResponse
    if err := json.NewDecoder(httpResp.Body).Decode(&raw); err != nil {
        return agent.Response{}, fmt.Errorf("cohere: decode: %w", err)
    }
    return p.decodeResponse(raw), nil
}

// Compile-time interface check.
var _ agent.Provider = (*Provider)(nil)

本体 encodeRequest、decodeResponse、および cohereResponse 形状は Cohere 固有です — rousseau のプロバイダ非依存の agent.Request および agent.Response 型を、Cohere のワイヤ形式との間で変換します。

ステップ 4 — ストリーミング (オプション)

Cohere が SSE スタイルのストリーミングをサポートする場合、CompleteStream を実装します。初回は省略してかまいません。エージェントループは自動的に非ストリーミングにフォールバックします。

ステップ 5 — 設定面

internal/config/config.go に CohereConfig を追加します:

type CohereConfig struct {
    APIKey    string `mapstructure:"api_key"`
    Model     string `mapstructure:"model"`
    BaseURL   string `mapstructure:"base_url"`
    MaxTokens int64  `mapstructure:"max_tokens"`
}

Config にフィールドを追加します:

Cohere CohereConfig `mapstructure:"cohere"`

setDefaults を妥当なモデルデフォルトで拡張します:

v.SetDefault("cohere.model", "command-r-plus")

ステップ 6 — CLI 配線

internal/cli/provider.go で buildProvider(cfg *config.Config) を拡張します:

func buildProvider(cfg *config.Config) (agent.Provider, error) {
    switch cfg.Provider {
    // ...existing cases...
    case "cohere":
        return cohere.New(cohere.Config{
            APIKey:    cfg.Cohere.APIKey,
            Model:     cfg.Cohere.Model,
            BaseURL:   cfg.Cohere.BaseURL,
            MaxTokens: cfg.Cohere.MaxTokens,
        }), nil
    default:
        return nil, fmt.Errorf("unknown provider %q", cfg.Provider)
    }
}

rousseau doctor (internal/cli/doctor.go) を拡張し、cfg.Provider == "cohere" のときに provider.cohere.* チェックブロックを追加します。既存の anthropic チェックを反映してください。

エージェントループが仮定する契約の詳細

  • Complete は ctx を尊重する。 長時間の HTTP リクエストはコンテキストキャンセルを尊重する必要があります。さもなければ、デーモンの SIGTERM シャットダウンがハングします。
  • ツール使用ラウンドトリップ。 モデルが tool_use ブロックを発行するとき、レスポンスの StopReason は StopToolUse でなければならず、メッセージコンテンツは要求された各呼び出しについて Content{Kind: ContentToolUse, ToolUse: &ToolUse{Name, Input, ID}} を含む必要があります。エージェントループは各々を Registry にルーティングし、実行し、結果を次の Complete 呼び出しにパイプします。
  • tool_result の処理。 次の呼び出しでは、req.Messages は、実行された各呼び出しについて Content{Kind: ContentToolResult, ToolResult: &ToolResult{ToolUseID, Output, IsError}} を含むユーザーメッセージを含みます。プロバイダはこれらを上流 API が期待する形状にレンダリングする必要があります。
  • コンパイル時インターフェースチェック。 パッケージスコープの var _ agent.Provider = (*Provider)(nil) は、ビルド時にインターフェースドリフトをキャッチします。

ストリーミング契約

StreamingProvider を実装する場合:

type StreamReader interface {
    Next(ctx context.Context) (StreamChunk, error)
    Close() error
}

type StreamChunk struct {
    Delta     string       // partial text delta
    Done      bool         // final chunk
    Response  *Response    // final Response, non-nil only on Done
}

TUI とチャットトランスポートハンドラは、到着するデルタを読み取ります。最終的な Response は、完全に構築されたアシスタントメッセージをセッションに追加するために使用されます。

プロンプトキャッシング

internal/llm/anthropic は、リクエストの最後の 2 つのメッセージに cache_control マーカーを配置します。プロバイダがプロンプトキャッシングをサポートしている場合、同じことをしてください — 圧縮 + リコール (圧縮 + リコール を参照) を、トークンを多く消費するパターンから安価なパターンに変えます。

テスト

httptest.NewServer を使ってフェイクの上流を立ち上げます。internal/llm/anthropic/*_test.go がリファレンスです。パターン:

  1. 缶詰の JSON を返すハンドラで httptest.NewServer を開始します。
  2. BaseURL をテストサーバーに向けてプロバイダを構築します。
  3. 缶詰の Request で Complete を呼び出します。
  4. 返された Response 形状に対してアサートします。

ストリーミングについては、httptest は Server-Sent Events もサポートします — internal/llm/anthropic/stream.go を参照してください。

ドキュメント

このドキュメントサイトに content/providers/cohere.md を追加します。content/providers/anthropic.md の形状に従ってください — 説明、設定面、認証詳細、プロバイダ固有の注意点。

よくある落とし穴

  • Messages を黙って書き換える。 エージェントループは会話状態の真実の源です。プロバイダはセマンティクスを変更せずに形状を変換する必要があります。
  • ツール使用 ID を失う。 レスポンス内のすべての ToolUse.ID は、次のリクエストの ToolResult.ToolUseID と一致する必要があります。プロバイダが独自の ID を割り当てる場合、慎重に変換してください。
  • MaxTokens を無視する。 一部のプロバイダは、明示的な制限なしのリクエストを拒否します。New で妥当なデフォルトを設定してください。
  • リトライポリシーでループをブロックする。 リトライはエージェントループではなく、プロバイダアダプタに属します。境界を設定してください。ハングよりも早く失敗する方が優れています。

次に

  • テスト — プロバイダの _test.go の書き方。
  • ツールの追加 — 最も小さな拡張ポイント。
  • 設定 — すべてのプロバイダが公開する設定面。

Type to search 150+ pages. Ranking: BM25 with title/description boost.