api

package
v0.46.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxImageSize 最大画像サイズ: 10MB
	MaxImageSize = 10 * 1024 * 1024
)

Variables

This section is empty.

Functions

func AskDeepSeekStream

func AskDeepSeekStream(query string, context string, model string) (string, error)

AskDeepSeekStream は従来のストリーミング質問(後方互換) Deprecated: 後方互換性のために残されています。ChatWithTools を使用してください。

func ChatWithTools

func ChatWithTools(systemPrompt string, history []Message, model string) (string, error)

ChatWithTools はツール対応の会話を行う(ストリーミング) Deprecated: 後方互換性のために残されています。Provider + Client を使用してください。

func FormatImageSize added in v0.29.0

func FormatImageSize(bytes int64) string

FormatImageSize はバイト数を人間が読みやすい形式に変換

func GetDefaultModel added in v0.42.0

func GetDefaultModel(model, providerName, fallback string) string

GetDefaultModel returns the model to use, checking config first, then falling back. providerName must match the config key (e.g., "openai", "claude", "deepseek")

func HandleHTTPError added in v0.31.0

func HandleHTTPError(resp *http.Response, spinner *ui.Spinner, providerName string) error

HandleHTTPError はHTTPエラーレスポンスを処理

func HandleNonStreamingResponse added in v0.31.0

func HandleNonStreamingResponse(resp *http.Response, spinner *ui.Spinner) (string, error)

HandleNonStreamingResponse は非ストリーミングレスポンスを処理

func HandleRateLimit added in v0.42.0

func HandleRateLimit(resp *http.Response) error

HandleRateLimit はレート制限エラーを処理

func LevelToBudgetTokens added in v0.42.0

func LevelToBudgetTokens(level string) int

LevelToBudgetTokens は Thinking Level を budget_tokens に変換(Claude/Gemini共通)

func ParseStreamingResponse

func ParseStreamingResponse(ctx context.Context, resp *http.Response, spinner *ui.Spinner, parser StreamParser) (string, error)

ParseStreamingResponse は共通のストリーミングレスポンス処理 コンテキストキャンセル、スピナー制御、エラーハンドリングを統一的に処理 アイドルタイムアウト方式: データ受信がない状態がN秒続くとタイムアウト ツールJSON部分は内部で記録するが表示しない

func RegisterProvider added in v0.42.0

func RegisterProvider(name string, factory ProviderFactory)

RegisterProvider はプロバイダーを登録する(init()から呼ばれる)

func SanitizeErrorMessage added in v0.42.0

func SanitizeErrorMessage(body []byte, statusCode int) error

SanitizeErrorMessage はエラーメッセージから機密情報を削除

func StartSpinner added in v0.31.0

func StartSpinner(message string) *ui.Spinner

StartSpinner はスピナーを開始

func StartThinkingSpinner added in v0.42.0

func StartThinkingSpinner(isImage bool, customSuffix string) *ui.Spinner

StartThinkingSpinner creates and starts a spinner with appropriate message. It checks config for thinking mode and adjusts the message accordingly. Parameters:

  • isImage: true for image analysis, false for normal chat
  • customSuffix: optional suffix like "Function Calling" or "Reasoner"

Returns the started spinner (caller must call Stop()).

func StopSpinner added in v0.31.0

func StopSpinner(spinner *ui.Spinner)

StopSpinner はスピナーを停止(nilセーフ)

func SupportsImages added in v0.29.0

func SupportsImages(providerName string) bool

SupportsImages はプロバイダー名から画像対応を判定

func ValidateChatResponse

func ValidateChatResponse(data []byte) error

ValidateChatResponse は非ストリーミングレスポンスの構造を検証

func ValidateErrorResponse

func ValidateErrorResponse(data []byte) (string, error)

ValidateErrorResponse はエラーレスポンスの構造を検証

func ValidateStreamResponse

func ValidateStreamResponse(data []byte) error

ValidateStreamResponse はストリーミングレスポンスの構造を検証

func ValidateToolCall

func ValidateToolCall(toolCall interface{}) error

ValidateToolCall はツール呼び出しレスポンスの構造を検証

Types

type BaseProvider added in v0.31.0

type BaseProvider struct {
	ProviderName string
	APIKey       string
	APIURL       string
	HTTPClient   *http.Client
}

BaseProvider は各プロバイダーの共通基盤

func NewBaseProvider added in v0.31.0

func NewBaseProvider(name, apiKey, defaultURL, envURLKey string) BaseProvider

NewBaseProvider は共通のプロバイダー基盤を作成

func (*BaseProvider) CreateAPIRequest added in v0.31.0

func (b *BaseProvider) CreateAPIRequest(ctx context.Context, body interface{}) (*http.Request, error)

CreateAPIRequest はAPIリクエストを作成

func (*BaseProvider) ExecuteRequest added in v0.31.0

func (b *BaseProvider) ExecuteRequest(req *http.Request) (*http.Response, error)

ExecuteRequest はHTTPリクエストを実行

func (*BaseProvider) SetAPIKeyAuth added in v0.31.0

func (b *BaseProvider) SetAPIKeyAuth(req *http.Request, headerName string)

SetAPIKeyAuth はカスタムヘッダーでAPIキー認証を設定

func (*BaseProvider) SetBearerAuth added in v0.31.0

func (b *BaseProvider) SetBearerAuth(req *http.Request)

SetBearerAuth はBearerトークン認証を設定

type ChatRequest

type ChatRequest struct {
	Model           string         `json:"model"`
	Messages        []Message      `json:"messages"`
	Stream          bool           `json:"stream"`
	StreamOptions   *StreamOptions `json:"stream_options,omitempty"`   // ストリーミング時のオプション
	ReasoningEffort string         `json:"reasoning_effort,omitempty"` // OpenAI Extended Thinking用
	Tools           []OpenAITool   `json:"tools,omitempty"`            // Function Calling用
	ToolChoice      string         `json:"tool_choice,omitempty"`      // "auto", "none", "required"
}

ChatRequest はAPIリクエスト(OpenAI互換形式)

type ChatResponse

type ChatResponse struct {
	Choices []Choice `json:"choices"`
}

ChatResponse は通常レスポンス

type Choice

type Choice struct {
	Message Message `json:"message"`
}

Choice は通常レスポンスの選択肢

type Client

type Client struct {
	Provider Provider
	Timeout  time.Duration
}

Client はLLM APIクライアント

func NewClient

func NewClient(provider Provider) *Client

NewClient は新しいClientを作成

func (*Client) ChatWithTools

func (c *Client) ChatWithTools(systemPrompt string, history []Message, model string) (string, error)

ChatWithTools はProviderに委譲

type CompactCapable added in v0.31.0

type CompactCapable interface {
	// CompactHistory は会話履歴を圧縮する
	CompactHistory(ctx context.Context, input []InputItem, model, instructions string) (*CompactResponse, error)

	// SupportsCompact は Compact API 対応を返す
	SupportsCompact() bool
}

CompactCapable は圧縮対応プロバイダーのオプショナルインターフェース 現時点では OpenAIProvider のみが実装

type CompactResponse added in v0.31.0

type CompactResponse struct {
	Output []InputItem   `json:"output"` // 圧縮済みアイテム(次の /responses に使用)
	Model  string        `json:"model"`
	Usage  *CompactUsage `json:"usage,omitempty"`
}

CompactResponse は /responses/compact レスポンス

type CompactUsage added in v0.31.0

type CompactUsage struct {
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
	TotalTokens  int `json:"total_tokens"`
}

CompactUsage はトークン使用量

type Delta

type Delta struct {
	Content   string           `json:"content,omitempty"`
	ToolCalls []OpenAIToolCall `json:"tool_calls,omitempty"` // Function Calling用
}

Delta はストリームレスポンスの差分

type GeminiFunctionCall added in v0.31.0

type GeminiFunctionCall struct {
	Name string         `json:"name"`
	Args map[string]any `json:"args"`
}

GeminiFunctionCall - Function Call response from Gemini

type GeminiFunctionDeclaration added in v0.31.0

type GeminiFunctionDeclaration struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  *GeminiParameterSchema `json:"parameters,omitempty"`
}

GeminiFunctionDeclaration - Gemini API用の関数宣言

func ConvertMCPToolToGeminiDeclaration added in v0.31.0

func ConvertMCPToolToGeminiDeclaration(name, description string, inputSchema json.RawMessage) GeminiFunctionDeclaration

ConvertMCPToolToGeminiDeclaration はMCPツールをGemini Function Declaration形式に変換 MCPのInputSchemaはJSON Schema形式でGeminiと互換性がある XELYON_DEBUG_GEMINI=1 でデバッグログを出力

type GeminiParameterSchema added in v0.31.0

type GeminiParameterSchema struct {
	Type       string                       `json:"type"`
	Properties map[string]GeminiPropertyDef `json:"properties,omitempty"`
	Required   []string                     `json:"required,omitempty"`
}

GeminiParameterSchema - パラメータスキーマ

type GeminiPropertyDef added in v0.31.0

type GeminiPropertyDef struct {
	Type        string             `json:"type"`
	Description string             `json:"description,omitempty"`
	Enum        []string           `json:"enum,omitempty"`
	Items       *GeminiPropertyDef `json:"items,omitempty"` // array型用
}

GeminiPropertyDef - プロパティ定義

type GeminiToolConfig added in v0.31.0

type GeminiToolConfig struct {
	FunctionDeclarations []GeminiFunctionDeclaration `json:"function_declarations"`
}

GeminiToolConfig - API リクエスト用ツール設定

type ImageData added in v0.29.0

type ImageData struct {
	Path      string // 元のファイルパス
	MediaType string // "image/png", "image/jpeg" 等
	Base64    string // Base64エンコードされた画像データ
	Size      int64  // ファイルサイズ(バイト)
}

ImageData は画像データを表す

func LoadImage added in v0.29.0

func LoadImage(path string) (*ImageData, error)

LoadImage は画像ファイルを読み込んでBase64エンコードする

type InputContentPart added in v0.31.0

type InputContentPart struct {
	Type     string `json:"type"`                // "input_text" or "input_image"
	Text     string `json:"text,omitempty"`      // type="input_text"の場合
	ImageURL string `json:"image_url,omitempty"` // type="input_image"の場合(data:image/...形式)
}

InputContentPart は Responses API のコンテンツパート(画像対応)

type InputItem added in v0.31.0

type InputItem struct {
	Type    string      `json:"type"`              // "message", "compacted", "function_call", "function_call_output"
	Role    string      `json:"role,omitempty"`    // "user", "assistant"
	Content interface{} `json:"content,omitempty"` // string or []InputContentPart

	// アシスタント応答の完全情報(Compact API用)
	ID     string `json:"id,omitempty"`     // "msg_xxx" (アシスタント応答のID)
	Status string `json:"status,omitempty"` // "completed"

	// 圧縮済みアイテム用
	Data string `json:"data,omitempty"` // 暗号化データ(type="compacted"の場合)

	// Function Calling 用(type="function_call"の場合)
	CallID    string `json:"call_id,omitempty"`   // ツール呼び出しID
	Name      string `json:"name,omitempty"`      // ツール名
	Arguments string `json:"arguments,omitempty"` // 引数(JSON文字列)

	// Function Calling 結果用(type="function_call_output"の場合)
	Output string `json:"output,omitempty"` // ツール実行結果
}

InputItem は Responses API の入力アイテム(Compact API対応拡張版) ユーザーメッセージ、アシスタント応答、圧縮済みアイテム、Function Calling を表現

func ConvertHistoryToInputItems added in v0.31.0

func ConvertHistoryToInputItems(history []Message) []InputItem

ConvertHistoryToInputItems は History を InputItem 形式に変換 Compact API に送信するためのフル会話ウィンドウを構築 Function Calling: assistant+ToolCalls は "function_call"、role="tool" は "function_call_output" 形式に変換

type MCPToolProvider added in v0.42.0

type MCPToolProvider interface {
	// SetMCPEnabled はMCPが有効かどうかを設定する(レガシー、互換性のため)
	SetMCPEnabled(enabled bool)

	// SetMCPTools はMCPツールの定義を設定する
	SetMCPTools(tools []GeminiFunctionDeclaration)
}

MCPToolProvider はMCPツール設定に対応するプロバイダーのオプショナルインターフェース 現時点では GeminiProvider のみが実装

type Message

type Message struct {
	Role       string           `json:"role"`
	Content    string           `json:"content"`
	ToolCallID string           `json:"tool_call_id,omitempty"` // Function Calling: ツール結果用
	ToolCalls  []OpenAIToolCall `json:"tool_calls,omitempty"`   // Function Calling: assistant の tool_calls
}

Message はチャットメッセージ

type ModelLister added in v0.42.0

type ModelLister interface {
	// ListModels はインストール済み/利用可能なモデルの一覧を取得
	ListModels() ([]string, error)
}

ModelLister はモデル一覧取得に対応するプロバイダーのオプショナルインターフェース 現時点では OllamaProvider のみが実装

type MultimodalMessage added in v0.29.0

type MultimodalMessage struct {
	Role    string     `json:"role"`
	Content string     `json:"content"`
	Image   *ImageData `json:"-"` // JSON保存しない(一時的なもの)
}

MultimodalMessage は画像を含むメッセージ

func (MultimodalMessage) HasImage added in v0.29.0

func (m MultimodalMessage) HasImage() bool

HasImage は画像が添付されているか

func (MultimodalMessage) ToMessage added in v0.29.0

func (m MultimodalMessage) ToMessage() Message

ToMessage は通常のMessageに変換(画像なし)

type OpenAIMCPToolProvider added in v0.44.0

type OpenAIMCPToolProvider interface {
	// SetMCPTools はMCPツールの定義を設定する
	SetMCPTools(tools []OpenAIToolFunction)
}

OpenAIMCPToolProvider はOpenAI用のMCPツール設定インターフェース OpenAI Chat Completions / Responses API の Function Calling で使用

type OpenAITool added in v0.44.0

type OpenAITool struct {
	Type     string              `json:"type"` // "function"
	Function *OpenAIToolFunction `json:"function"`
}

OpenAITool は OpenAI Chat Completions API 用のツール形式 リクエストの tools[] フィールドに使用

type OpenAIToolCall added in v0.44.0

type OpenAIToolCall struct {
	Index    int                    `json:"index"`    // ストリーミング用インデックス
	ID       string                 `json:"id"`       // ツール呼び出しID
	Type     string                 `json:"type"`     // "function"
	Function OpenAIToolCallFunction `json:"function"` // 関数呼び出し情報
}

OpenAIToolCall はレスポンスの tool_calls フィールド ストリーミングでは複数チャンクに分割されて送信される

type OpenAIToolCallFunction added in v0.44.0

type OpenAIToolCallFunction struct {
	Name      string `json:"name"`      // ツール名
	Arguments string `json:"arguments"` // 引数(JSON文字列)
}

OpenAIToolCallFunction は関数呼び出しの詳細

type OpenAIToolFunction added in v0.44.0

type OpenAIToolFunction struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
	Strict      bool                   `json:"strict,omitempty"`
}

OpenAIToolFunction はツール関数の定義

func ConvertMCPToolToOpenAIFunction added in v0.44.0

func ConvertMCPToolToOpenAIFunction(name, description string, inputSchema []byte) OpenAIToolFunction

ConvertMCPToolToOpenAIFunction はMCPツールをOpenAI Function形式に変換 MCPのInputSchemaはJSON Schema形式でOpenAIと互換性がある

type Provider

type Provider interface {
	// Name はプロバイダー名を返す
	Name() string

	// ChatWithTools はツール対応の会話を行う(ストリーミング)
	ChatWithTools(ctx context.Context, systemPrompt string, history []Message, model string) (string, error)

	// SupportsImages はプロバイダーが画像入力に対応しているかを返す
	SupportsImages() bool

	// ChatWithImage は画像付きメッセージで会話を行う
	// imageがnilまたはプロバイダーが画像非対応の場合、テキストのみで会話する
	ChatWithImage(ctx context.Context, systemPrompt string, history []Message, userMessage string, image *ImageData, model string) (string, error)

	// IsFunctionCallingEnabled は Function Calling が有効かを返す
	// true の場合、System Prompt からツール定義を削除して重複を避ける
	IsFunctionCallingEnabled() bool
}

Provider はLLMプロバイダーの共通インターフェース

func NewClaudeProvider

func NewClaudeProvider(apiKey string) Provider

NewClaudeProvider は新しい Claude Provider を作成(後方互換)

func NewDeepSeekProvider

func NewDeepSeekProvider(apiKey string) Provider

NewDeepSeekProvider は新しい DeepSeek Provider を作成(後方互換) 戻り値は Provider インターフェースです。

func NewGeminiProvider

func NewGeminiProvider(apiKey string) Provider

NewGeminiProvider は新しい Gemini Provider を作成(後方互換)

func NewGroqProvider

func NewGroqProvider(apiKey string) Provider

NewGroqProvider は新しい Groq Provider を作成(後方互換)

func NewOllamaProvider

func NewOllamaProvider(baseURL string) Provider

NewOllamaProvider は新しい Ollama Provider を作成(後方互換)

func NewOpenAIProvider

func NewOpenAIProvider(apiKey string) Provider

NewOpenAIProvider は新しい OpenAI Provider を作成(後方互換)

func NewProvider added in v0.29.0

func NewProvider(providerName string) (Provider, error)

NewProvider はプロバイダー名から Provider インスタンスを生成

type ProviderFactory added in v0.42.0

type ProviderFactory func(apiKey string) (Provider, error)

ProviderFactory はプロバイダーを生成するファクトリ関数

type StreamChoice

type StreamChoice struct {
	Delta        Delta  `json:"delta"`
	FinishReason string `json:"finish_reason,omitempty"` // "stop", "tool_calls" など
}

StreamChoice はストリームの選択肢

type StreamOptions added in v0.46.0

type StreamOptions struct {
	IncludeUsage bool `json:"include_usage"` // trueでusage情報を最終チャンクに含める
}

StreamOptions はストリーミング時のオプション

type StreamParser

type StreamParser func(line string) (content string, done bool, err error)

StreamParser はストリーミングレスポンスの1行をパースする関数型 戻り値: (content string, done bool, err error)

  • content: この行から抽出されたテキストコンテンツ
  • done: ストリームの終了を示すフラグ
  • err: パースエラー

type StreamResponse

type StreamResponse struct {
	Choices []StreamChoice   `json:"choices"`
	Usage   *StreamUsageInfo `json:"usage,omitempty"` // 最終チャンクに含まれる
}

StreamResponse はストリームレスポンス

type StreamUsageInfo added in v0.46.0

type StreamUsageInfo struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
}

StreamUsageInfo はストリーミングレスポンスの使用量情報

type Usage added in v0.46.0

type Usage struct {
	InputTokens  int
	OutputTokens int

	// キャッシュ関連(プロバイダーにより対応状況が異なる)
	CachedInputTokens   int // キャッシュから読み取ったトークン数(割引対象)
	CacheCreationTokens int // キャッシュ作成に使用したトークン数(Claude: 1.25x課金)
}

Usage はAPIレスポンスのトークン使用量

type UsageCallback added in v0.46.0

type UsageCallback func(usage Usage)

UsageCallback は usage 受信時に呼ばれるコールバック

type UsageReporter added in v0.46.0

type UsageReporter interface {
	// SetUsageCallback は使用量レポートのコールバックを設定する
	SetUsageCallback(callback UsageCallback)
}

UsageReporter はトークン使用量レポートに対応するプロバイダーのオプショナルインターフェース

Directories

Path Synopsis
providers

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL