api

package
v0.42.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 17 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"`
	ReasoningEffort string    `json:"reasoning_effort,omitempty"` // OpenAI Extended Thinking用
}

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"`
}

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" or "compacted"
	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"の場合)
}

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

func ConvertHistoryToInputItems added in v0.31.0

func ConvertHistoryToInputItems(history []Message) []InputItem

ConvertHistoryToInputItems は History を InputItem 形式に変換 Compact API に送信するためのフル会話ウィンドウを構築

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"`
}

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 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)
}

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"`
}

StreamChoice はストリームの選択肢

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"`
}

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

Directories

Path Synopsis
providers

Jump to

Keyboard shortcuts

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