インターフェース
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 がリファレンスです。パターン:
- 缶詰の JSON を返すハンドラで
httptest.NewServerを開始します。 BaseURLをテストサーバーに向けてプロバイダを構築します。- 缶詰の
RequestでCompleteを呼び出します。 - 返された
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で妥当なデフォルトを設定してください。- リトライポリシーでループをブロックする。 リトライはエージェントループではなく、プロバイダアダプタに属します。境界を設定してください。ハングよりも早く失敗する方が優れています。