app

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(v bool) *bool

func DetectSearchIntent

func DetectSearchIntent(text string) (hasIntent bool, query string)

DetectSearchIntent checks if a prompt has search intent and returns the query.

func DiscardLogger

func DiscardLogger() *slog.Logger

DiscardLogger returns a logger that discards all output (for testing).

func ExtractSearchQuery

func ExtractSearchQuery(text string) string

ExtractSearchQuery extracts the search query from a prompt.

func ExtractURLs

func ExtractURLs(text string) []string

ExtractURLs extracts all URLs from the given text.

func Float64Ptr

func Float64Ptr(v float64) *float64

Helper functions for creating pointers to literals (exported for use in cmd package)

func FormatSearchForContext

func FormatSearchForContext(results []SearchResult) string

FormatSearchForContext formats search results as XML context for prompt augmentation. This is used by the --search flag to prepend search results to prompts.

func FormatSearchResultsForChat

func FormatSearchResultsForChat(results []SearchResult, query string) string

FormatSearchResultsForChat formats search results for inclusion in chat prompts.

func FormatWebContent

func FormatWebContent(url, title, content string) string

FormatWebContent formats web content for inclusion in chat prompts.

func IntPtr

func IntPtr(v int) *int

func IsSearchPrompt

func IsSearchPrompt(text string) bool

IsSearchPrompt checks if the prompt is requesting a web search.

func IsValidWebURL

func IsValidWebURL(raw string) bool

IsValidWebURL checks if a string is a valid web URL.

func IsWebContentPrompt

func IsWebContentPrompt(text string) bool

IsWebContentPrompt checks if the prompt is asking for web content.

func NewLogger

func NewLogger(verbose bool) *slog.Logger

NewLogger creates a slog.Logger for the application. If verbose is true, logs at Debug level; otherwise Info level.

func OpenWith

func OpenWith(target string) error

OpenWith opens a file or URL with the system's default handler. On macOS: uses `open`, Linux: `xdg-open`, Windows: `cmd /c start`.

Types

type APIError added in v0.1.1

type APIError struct {
	StatusCode int
	Body       string
}

APIError represents an error response from the Z.AI API. Use errors.As to extract this type from wrapped errors.

func (*APIError) Error added in v0.1.1

func (e *APIError) Error() string

type AudioClient

type AudioClient interface {
	TranscribeAudio(ctx context.Context, audioPath string, opts TranscriptionOptions) (*TranscriptionResponse, error)
}

AudioClient interface for audio transcription (ISP compliance).

type CacheStats

type CacheStats struct {
	TotalEntries   int    `json:"total_entries"`
	ExpiredEntries int    `json:"expired_entries"`
	SizeBytes      int64  `json:"size_bytes"`
	CacheDir       string `json:"cache_dir"`
}

CacheStats provides statistics about the cache.

type ChatClient

type ChatClient interface {
	Chat(ctx context.Context, prompt string, opts ChatOptions) (string, error)
}

ChatClient interface for testability (ISP compliance). Provides the main chat functionality.

type ChatOptions

type ChatOptions struct {
	Model       string   // Override default model
	Temperature *float64 // Override default temperature
	MaxTokens   *int     // Override default max tokens
	TopP        *float64 // Override default top_p
	Thinking    *bool    // Enable thinking mode
	WebEnabled  *bool    // Enable web content fetching
	WebTimeout  *int     // Web fetch timeout in seconds

	// Legacy fields for backward compatibility
	FilePath     string    // Optional file to include in context
	Context      []Message // Previous messages for context
	Think        bool      // Enable thinking/reasoning mode (legacy)
	SystemPrompt string    // Custom system prompt
}

ChatOptions configures chat requests.

func DefaultChatOptions

func DefaultChatOptions() ChatOptions

DefaultChatOptions returns sensible defaults for CLI usage.

type ChatRequest

type ChatRequest struct {
	Model       string    `json:"model"`
	Messages    []Message `json:"messages"`
	Stream      bool      `json:"stream"` // Reserved for future streaming API support
	Temperature float64   `json:"temperature,omitempty"`
	MaxTokens   int       `json:"max_tokens,omitempty"`
	TopP        float64   `json:"top_p,omitempty"`
	Thinking    *Thinking `json:"thinking,omitempty"`
}

ChatRequest represents the API request payload.

type ChatResponse

type ChatResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
	Usage   Usage    `json:"usage"`
}

ChatResponse represents the API response.

type Choice

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

Choice represents a response choice.

type CircuitBreaker added in v0.1.1

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

CircuitBreaker implements a circuit breaker pattern for API calls.

func NewCircuitBreaker added in v0.1.1

func NewCircuitBreaker(name string, config config.CircuitBreakerConfig, logger *slog.Logger) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func (*CircuitBreaker) Execute added in v0.1.1

func (cb *CircuitBreaker) Execute(fn func() error) error

Execute wraps a function call with circuit breaker protection.

func (*CircuitBreaker) Reset added in v0.1.1

func (cb *CircuitBreaker) Reset()

Reset manually resets the circuit breaker to closed state.

type CircuitBreakerState added in v0.1.1

type CircuitBreakerState int

CircuitBreaker states

const (
	Closed CircuitBreakerState = iota
	Open
	HalfOpen
)

func (CircuitBreakerState) String added in v0.1.1

func (s CircuitBreakerState) String() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client implements ChatClient with Z.AI API.

func NewClient

func NewClient(cfg ClientConfig, logger *slog.Logger, history HistoryStore, httpClient HTTPDoer) *Client

NewClient creates a client with injected dependencies. If deps is nil or fields are nil, default implementations are used.

func NewClientWithDeps

func NewClientWithDeps(cfg ClientConfig, logger *slog.Logger, history HistoryStore, deps *ClientDeps) *Client

NewClientWithDeps creates a client with full dependency injection. Allows injection of all dependencies for testing.

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, prompt string, opts ChatOptions) (string, error)

Chat sends a prompt and returns the response. Orchestrates content building, URL enrichment, and request execution.

func (*Client) FetchWebContent

func (c *Client) FetchWebContent(ctx context.Context, url string, opts *WebReaderOptions) (*WebReaderResponse, error)

FetchWebContent retrieves and processes web content from a URL.

func (*Client) GenerateImage

func (c *Client) GenerateImage(ctx context.Context, prompt string, opts ImageOptions) (*ImageResponse, error)

GenerateImage creates an image using the Z.AI image generation API.

func (*Client) GenerateVideo

func (c *Client) GenerateVideo(ctx context.Context, prompt string, opts VideoOptions) (*VideoGenerationResponse, error)

GenerateVideo creates a video using Z.AI's CogVideoX-3 API (async).

func (*Client) HTTPClient

func (c *Client) HTTPClient() HTTPDoer

HTTPClient returns the underlying HTTP client for connection reuse.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]Model, error)

ListModels fetches available models from the API.

func (*Client) RetrieveVideoResult

func (c *Client) RetrieveVideoResult(ctx context.Context, taskID string) (*VideoResultResponse, error)

RetrieveVideoResult polls for async video generation result.

func (*Client) SearchWeb

func (c *Client) SearchWeb(ctx context.Context, query string, opts SearchOptions) (*WebSearchResponse, error)

SearchWeb performs a web search using Z.AI's search API.

func (*Client) TranscribeAudio

func (c *Client) TranscribeAudio(ctx context.Context, audioPath string, opts TranscriptionOptions) (*TranscriptionResponse, error)

TranscribeAudio transcribes an audio file using Z.AI's ASR model.

func (*Client) Vision

func (c *Client) Vision(ctx context.Context, prompt string, imageBase64 string, opts VisionOptions) (string, error)

Vision analyzes an image using Z.AI's vision model (glm-4.6v). imageBase64 should be a data URI like "data:image/jpeg;base64,<base64-data>" or a raw base64 string.

type ClientConfig

type ClientConfig struct {
	APIKey         string
	BaseURL        string
	CodingBaseURL  string
	Model          string
	Timeout        time.Duration
	Verbose        bool
	RateLimit      RateLimitConfig
	RetryConfig    RetryConfig
	CircuitBreaker config.CircuitBreakerConfig
}

ClientConfig holds all configuration for the ZAI client. Injected at construction time - no global state.

type ClientDeps

type ClientDeps struct {
	HTTPClient HTTPDoer
	FileReader FileReader
}

ClientDeps holds optional dependencies for NewClient. Zero values mean "use default implementation".

type ContentPart

type ContentPart struct {
	Type     string           `json:"type"` // "text" or "image_url"
	Text     string           `json:"text,omitempty"`
	ImageURL *ImageURLContent `json:"image_url,omitempty"`
}

ContentPart represents a part of multimodal content (text or image).

type DownloadResult

type DownloadResult struct {
	FilePath string
	Size     int64
	Error    error
}

DownloadResult contains the result of a download operation.

type FileHistoryStore

type FileHistoryStore struct {
	// contains filtered or unexported fields
}

FileHistoryStore implements HistoryStore with JSONL file storage.

func NewFileHistoryStore

func NewFileHistoryStore(path string) *FileHistoryStore

NewFileHistoryStore creates a history store at the given path. If path is empty, uses default XDG location.

func (*FileHistoryStore) GetRecent

func (h *FileHistoryStore) GetRecent(limit int) ([]HistoryEntry, error)

GetRecent returns the most recent history entries.

func (*FileHistoryStore) Path

func (h *FileHistoryStore) Path() string

Path returns the history file path.

func (*FileHistoryStore) Save

func (h *FileHistoryStore) Save(entry HistoryEntry) error

Save appends an entry to the history file.

type FileReader

type FileReader = utils.FileReader

FileReader interface for file operations (DIP compliance, enables testing). Deprecated: Use utils.FileReader instead. Kept for backward compatibility.

type FileSearchCache

type FileSearchCache struct {
	// contains filtered or unexported fields
}

FileSearchCache implements persistent file-based caching.

func NewFileSearchCache

func NewFileSearchCache(dir string) *FileSearchCache

NewFileSearchCache creates a new file-based search cache.

func (*FileSearchCache) Cleanup

func (fsc *FileSearchCache) Cleanup() error

Cleanup removes expired entries.

func (*FileSearchCache) Clear

func (fsc *FileSearchCache) Clear() error

Clear removes all cached entries.

func (*FileSearchCache) Get

func (fsc *FileSearchCache) Get(query string, opts SearchOptions) ([]SearchResult, bool)

Get retrieves cached search results.

func (*FileSearchCache) Set

func (fsc *FileSearchCache) Set(query string, opts SearchOptions, results []SearchResult, ttl time.Duration) error

Set stores search results in cache.

func (*FileSearchCache) Stats

func (fsc *FileSearchCache) Stats() (*CacheStats, error)

Stats returns cache statistics.

type FullClient

FullClient composes all client interfaces into one (backward compatibility).

type HTTPDoer

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer interface for HTTP operations (DIP compliance, enables testing).

func NewRateLimitedClient added in v0.1.1

func NewRateLimitedClient(client HTTPDoer, rateLimitConfig RateLimitConfig, logger *slog.Logger) HTTPDoer

NewRateLimitedClient creates a new rate-limited HTTP client.

type HistoryEntry

type HistoryEntry struct {
	ID         string      `json:"id,omitempty"`
	Timestamp  time.Time   `json:"timestamp"`
	Prompt     string      `json:"prompt"`
	Response   interface{} `json:"response"` // Support string or complex response
	Model      string      `json:"model"`
	TokenUsage Usage       `json:"token_usage,omitempty"`

	// Image generation fields
	ImageURL    string `json:"image_url,omitempty"`
	ImageSize   string `json:"image_size,omitempty"`
	ImageFormat string `json:"image_format,omitempty"`
	Type        string `json:"type"` // "chat", "image", or "web"

	// Web reader fields
	WebSources []string `json:"web_sources,omitempty"`
}

HistoryEntry represents a single chat, image generation, or web reader history entry.

func NewAudioHistoryEntry

func NewAudioHistoryEntry(text string, model string) HistoryEntry

NewAudioHistoryEntry creates a history entry for audio transcription.

func NewChatHistoryEntry

func NewChatHistoryEntry(timestamp time.Time, prompt, response, model string, usage Usage) HistoryEntry

NewChatHistoryEntry creates a history entry for chat (sets type to "chat").

func NewImageHistoryEntry

func NewImageHistoryEntry(prompt string, imageData ImageData, model string) HistoryEntry

NewImageHistoryEntry creates a history entry for image generation.

func NewSearchHistoryEntry

func NewSearchHistoryEntry(timestamp time.Time, query string, resp *WebSearchResponse) HistoryEntry

NewSearchHistoryEntry creates a history entry for web search.

func NewWebHistoryEntry

func NewWebHistoryEntry(id, prompt string, resp *WebReaderResponse, sources []string) HistoryEntry

NewWebHistoryEntry creates a history entry for web content fetching.

type HistoryStore

type HistoryStore interface {
	Save(entry HistoryEntry) error
	GetRecent(limit int) ([]HistoryEntry, error)
}

HistoryStore interface for storage abstraction (ISP compliance).

type ImageClient

type ImageClient interface {
	GenerateImage(ctx context.Context, prompt string, opts ImageOptions) (*ImageResponse, error)
}

ImageClient interface for image generation (ISP compliance).

type ImageData

type ImageData struct {
	URL           string `json:"url"`
	RevisedPrompt string `json:"revised_prompt,omitempty"`
	Width         int    `json:"width"`
	Height        int    `json:"height"`
	Format        string `json:"format"`
}

ImageData represents a generated image.

type ImageGenerationRequest

type ImageGenerationRequest struct {
	Model   string `json:"model"` // "glm-image"
	Prompt  string `json:"prompt"`
	Quality string `json:"quality,omitempty"` // "hd" or "standard"
	Size    string `json:"size,omitempty"`    // "1024x1024"
	UserID  string `json:"user_id,omitempty"` // Optional
}

ImageGenerationRequest represents the image generation API request.

type ImageModel

type ImageModel struct {
	ID          string `json:"id"`
	Object      string `json:"object"`
	Created     int64  `json:"created"`
	OwnedBy     string `json:"owned_by"`
	Description string `json:"description,omitempty"`
}

ImageModel represents an image generation model.

type ImageOptions

type ImageOptions struct {
	Quality string // "hd" or "standard"
	Size    string // "widthxheight" format
	UserID  string // Optional user ID for analytics
	Model   string // Override default model
}

ImageOptions configures image generation requests.

type ImageResponse

type ImageResponse struct {
	ID      string      `json:"id"`
	Object  string      `json:"object"`
	Created int64       `json:"created"`
	Model   string      `json:"model"`
	Data    []ImageData `json:"data"`
	Usage   Usage       `json:"usage,omitempty"`
}

ImageResponse represents the image generation API response.

type ImageURLContent

type ImageURLContent struct {
	URL string `json:"url"`
}

ImageURLContent contains image URL or base64 data.

type MediaDownloader

type MediaDownloader struct {
	// contains filtered or unexported fields
}

MediaDownloader handles downloading media files with DI support.

func NewMediaDownloader

func NewMediaDownloader(httpClient HTTPDoer) *MediaDownloader

NewMediaDownloader creates a MediaDownloader with the provided HTTP client. If httpClient is nil, a default http.Client is used.

func (*MediaDownloader) Download

func (d *MediaDownloader) Download(url, filePath string) *DownloadResult

Download fetches a URL and saves to file with directory creation.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message represents a chat message.

type Model

type Model struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	OwnedBy string `json:"owned_by"`
}

Model represents a single model in the list.

type ModelClient

type ModelClient interface {
	ListModels(ctx context.Context) ([]Model, error)
}

ModelClient interface for model listing (ISP compliance).

type ModelsResponse

type ModelsResponse struct {
	Object string  `json:"object"`
	Data   []Model `json:"data"`
}

ModelsResponse represents the /models API response.

type OSFileReader

type OSFileReader = utils.OSFileReader

OSFileReader implements FileReader using os.ReadFile. Deprecated: Use utils.OSFileReader instead. Kept for backward compatibility.

type RateLimitConfig added in v0.1.1

type RateLimitConfig struct {
	RequestsPerSecond int
	Burst             int
}

RateLimitConfig holds rate limiting configuration.

type RateLimitedClient added in v0.1.1

type RateLimitedClient struct {
	// contains filtered or unexported fields
}

RateLimitedClient implements HTTPDoer with rate limiting.

func (*RateLimitedClient) Do added in v0.1.1

func (c *RateLimitedClient) Do(req *http.Request) (*http.Response, error)

Do implements HTTPDoer interface with rate limiting.

type ReaderResult

type ReaderResult struct {
	Content           string                 `json:"content"`
	Description       string                 `json:"description"`
	Title             string                 `json:"title"`
	URL               string                 `json:"url"`
	ExternalResources map[string]interface{} `json:"external_resources,omitempty"`
	Metadata          map[string]interface{} `json:"metadata,omitempty"`
}

ReaderResult contains the web reader results.

type RetryConfig

type RetryConfig struct {
	MaxAttempts    int           // Maximum number of retry attempts (default: 3)
	InitialBackoff time.Duration // Initial backoff duration (default: 1s)
	MaxBackoff     time.Duration // Maximum backoff duration (default: 30s)
}

RetryConfig configures retry behavior for transient failures.

type SearchCache

type SearchCache interface {
	Get(query string, opts SearchOptions) ([]SearchResult, bool)
	Set(query string, opts SearchOptions, results []SearchResult, ttl time.Duration) error
	Clear() error
	Cleanup() error // Remove expired entries
}

SearchCache interface for search caching (ISP compliance).

type SearchCacheEntry

type SearchCacheEntry struct {
	Query     string         `json:"query"`
	Results   []SearchResult `json:"results"`
	CachedAt  time.Time      `json:"cached_at"`
	ExpiresAt time.Time      `json:"expires_at"`
	Hash      string         `json:"hash"` // SHA256 of query + options
}

SearchCacheEntry represents a cached search result.

type SearchOptions

type SearchOptions struct {
	Count         int    // Number of results (1-50)
	DomainFilter  string // Limit to specific domain
	RecencyFilter string // Time filter: oneDay, oneWeek, oneMonth, oneYear, noLimit
	RequestID     string // Unique request ID
	UserID        string // User ID for analytics
}

SearchOptions configures search requests.

type SearchOutputFormat

type SearchOutputFormat string

SearchOutputFormat represents the output format for search results.

const (
	SearchOutputTable    SearchOutputFormat = "table"
	SearchOutputDetailed SearchOutputFormat = "detailed"
	SearchOutputJSON     SearchOutputFormat = "json"
)

type SearchResult

type SearchResult struct {
	Title       string `json:"title"`
	Content     string `json:"content"`
	Link        string `json:"link"`
	Media       string `json:"media"`
	Icon        string `json:"icon"`
	Refer       string `json:"refer"`
	PublishDate string `json:"publish_date"`
}

SearchResult represents a single search result.

type Thinking

type Thinking struct {
	Type string `json:"type"`
}

Thinking configures the thinking/reasoning mode. Type: "enabled" or "disabled"

type TranscriptionOptions

type TranscriptionOptions struct {
	Model     string   // Override default model (default: glm-asr-2512)
	Prompt    string   // Context from prior transcriptions (max 8000 chars)
	Hotwords  []string // Domain vocabulary (max 100 items)
	Stream    bool     // Enable streaming via Event Stream
	UserID    string   // End user ID (6-128 characters)
	RequestID string   // Client-provided unique identifier
}

TranscriptionOptions configures audio transcription requests.

type TranscriptionResponse

type TranscriptionResponse struct {
	ID        string `json:"id"`
	Created   int64  `json:"created"`
	RequestID string `json:"request_id,omitempty"`
	Model     string `json:"model"`
	Text      string `json:"text"`
}

TranscriptionResponse represents the audio transcription API response.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage represents token usage statistics.

type VideoClient

type VideoClient interface {
	GenerateVideo(ctx context.Context, prompt string, opts VideoOptions) (*VideoGenerationResponse, error)
	RetrieveVideoResult(ctx context.Context, taskID string) (*VideoResultResponse, error)
}

VideoClient interface for video generation (ISP compliance).

type VideoGenerationRequest

type VideoGenerationRequest struct {
	Model     string   `json:"model"`                // "cogvideox-3"
	Prompt    string   `json:"prompt,omitempty"`     // Text description (max 512 chars)
	ImageURL  []string `json:"image_url,omitempty"`  // URL or base64, 1-2 images (first/last frame)
	Quality   string   `json:"quality,omitempty"`    // "quality" or "speed" (default: speed)
	WithAudio bool     `json:"with_audio,omitempty"` // AI sound effects (default: false)
	Size      string   `json:"size,omitempty"`       // 1280x720, 1920x1080, 3840x2160, etc.
	FPS       int      `json:"fps,omitempty"`        // 30 or 60 (default: 30)
	Duration  int      `json:"duration,omitempty"`   // 5 or 10 seconds (default: 5)
	RequestID string   `json:"request_id,omitempty"`
	UserID    string   `json:"user_id,omitempty"`
}

VideoGenerationRequest represents the video generation API request.

type VideoGenerationResponse

type VideoGenerationResponse struct {
	ID         string `json:"id"` // Task ID for polling
	Model      string `json:"model"`
	RequestID  string `json:"request_id"`
	TaskStatus string `json:"task_status"` // PROCESSING, SUCCESS, FAIL
}

VideoGenerationResponse represents the async video generation API response.

type VideoOptions

type VideoOptions struct {
	Model     string   // Override default model
	Quality   string   // "quality" or "speed"
	Size      string   // Resolution
	FPS       int      // Frame rate
	Duration  int      // Duration in seconds
	WithAudio bool     // Include AI sound effects
	ImageURLs []string // First/last frame images
	UserID    string   // User ID for analytics
	RequestID string   // Unique request ID
}

VideoOptions configures video generation requests.

type VideoResult

type VideoResult struct {
	URL           string `json:"url"`             // Video URL
	CoverImageURL string `json:"cover_image_url"` // Thumbnail URL
}

VideoResult represents a generated video.

type VideoResultResponse

type VideoResultResponse struct {
	Model       string        `json:"model"`
	VideoResult []VideoResult `json:"video_result"`
	TaskStatus  string        `json:"task_status"` // PROCESSING, SUCCESS, FAIL
	RequestID   string        `json:"request_id"`
}

VideoResultResponse represents the result retrieval API response.

type VisionClient

type VisionClient interface {
	Vision(ctx context.Context, prompt string, imageBase64 string, opts VisionOptions) (string, error)
}

VisionClient interface for image analysis (ISP compliance).

type VisionMessage

type VisionMessage struct {
	Role    string        `json:"role"`
	Content []ContentPart `json:"content"`
}

VisionMessage represents a message in vision API (supports multimodal content).

type VisionOptions

type VisionOptions struct {
	Model       string   // Override default model (e.g., "glm-4.6v")
	Temperature *float64 // Override default temperature
	MaxTokens   *int     // Override default max tokens
	TopP        *float64 // Override default top_p
}

VisionOptions configures vision/analysis requests.

type VisionRequest

type VisionRequest struct {
	Model       string          `json:"model"`
	Messages    []VisionMessage `json:"messages"`
	Stream      bool            `json:"stream"` // Reserved for future streaming API support
	Temperature float64         `json:"temperature,omitempty"`
	MaxTokens   int             `json:"max_tokens,omitempty"`
	TopP        float64         `json:"top_p,omitempty"`
}

VisionRequest represents a vision/image analysis API request.

type WebReaderClient

type WebReaderClient interface {
	FetchWebContent(ctx context.Context, url string, opts *WebReaderOptions) (*WebReaderResponse, error)
}

WebReaderClient interface for web content fetching (ISP compliance).

type WebReaderOptions

type WebReaderOptions struct {
	Timeout           *int
	NoCache           *bool
	ReturnFormat      string // "markdown" or "text"
	RetainImages      *bool
	NoGFM             *bool
	KeepImgDataURL    *bool
	WithImagesSummary *bool
	WithLinksSummary  *bool
}

WebReaderOptions configures web reader requests.

type WebReaderRequest

type WebReaderRequest struct {
	URL               string `json:"url"`
	Timeout           *int   `json:"timeout,omitempty"`             // default: 20
	NoCache           *bool  `json:"no_cache,omitempty"`            // default: false
	ReturnFormat      string `json:"return_format,omitempty"`       // default: "markdown"
	RetainImages      *bool  `json:"retain_images,omitempty"`       // default: true
	NoGFM             *bool  `json:"no_gfm,omitempty"`              // default: false
	KeepImgDataURL    *bool  `json:"keep_img_data_url,omitempty"`   // default: false
	WithImagesSummary *bool  `json:"with_images_summary,omitempty"` // default: false
	WithLinksSummary  *bool  `json:"with_links_summary,omitempty"`  // default: false
}

WebReaderRequest represents a web reader API request.

type WebReaderResponse

type WebReaderResponse struct {
	ID           string       `json:"id"`
	Created      int64        `json:"created"`
	ReaderResult ReaderResult `json:"reader_result"`
}

WebReaderResponse represents a web reader API response.

type WebSearchClient

type WebSearchClient interface {
	SearchWeb(ctx context.Context, query string, opts SearchOptions) (*WebSearchResponse, error)
}

WebSearchClient interface for web searching (ISP compliance).

type WebSearchRequest

type WebSearchRequest struct {
	SearchEngine        string  `json:"search_engine"` // "search-prime"
	SearchQuery         string  `json:"search_query"`
	Count               *int    `json:"count,omitempty"` // 1-50, default 10
	SearchDomainFilter  *string `json:"search_domain_filter,omitempty"`
	SearchRecencyFilter *string `json:"search_recency_filter,omitempty"` // oneDay/oneWeek/oneMonth/oneYear/noLimit
	RequestID           *string `json:"request_id,omitempty"`
	UserID              *string `json:"user_id,omitempty"`
}

WebSearchRequest represents a web search API request.

type WebSearchResponse

type WebSearchResponse struct {
	ID           string         `json:"id"`
	Created      int64          `json:"created"`
	SearchResult []SearchResult `json:"search_result"`
}

WebSearchResponse represents a web search API response.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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