Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyImageGenerationOptions(opts *ImageGenerationOptions, options ...ImageGenerationOption)
- func CheckMedia(ctx context.Context, options *GenerateOptions, provider string, ...) error
- func HasMedia(parts []*Part) bool
- func PartsText(parts []*Part) string
- func PromptText(prompt string, options *GenerateOptions) string
- func ValidateParts(parts []*Part) error
- func WithIncludeIntermediateMessages(include bool) func(*StreamConfig)
- type AdminConversationMemory
- type AgentEventType
- type AgentResponse
- type AgentStreamEvent
- type AgentTaskServiceInterface
- type Blob
- type CacheConfig
- type CollectionRef
- type Content
- type ConversationMemory
- type DataStore
- type DeleteOption
- type DeleteOptions
- type Document
- type Embedder
- type Entity
- type EntityTypeSchema
- type ExecutionSummary
- type ExtractionOption
- func WithDedupThreshold(threshold float32) ExtractionOption
- func WithExtractionEntityTypes(types ...string) ExtractionOption
- func WithExtractionRelationshipTypes(types ...string) ExtractionOption
- func WithMaxEntities(max int) ExtractionOption
- func WithMinConfidence(confidence float32) ExtractionOption
- func WithSchemaGuided(guided bool) ExtractionOption
- type ExtractionOptions
- type ExtractionResult
- type FileData
- type GenerateOption
- func WithDisableFinalSummary(disable bool) GenerateOption
- func WithFrequencyPenalty(frequencyPenalty float64) GenerateOption
- func WithMaxIterations(maxIterations int) GenerateOption
- func WithMaxTokens(maxTokens int) GenerateOption
- func WithMemory(memory Memory) GenerateOption
- func WithParts(parts ...*Part) GenerateOption
- func WithPresencePenalty(presencePenalty float64) GenerateOption
- func WithReasoning(enabled bool, budget ...int) GenerateOption
- func WithResponseFormat(format ResponseFormat) GenerateOption
- func WithStopSequences(stopSequences []string) GenerateOption
- func WithStreamConfig(config StreamConfig) GenerateOption
- func WithSystemMessage(systemMessage string) GenerateOption
- func WithTemperature(temperature float64) GenerateOption
- func WithTopP(topP float64) GenerateOption
- type GenerateOptions
- type GeneratedImage
- type GetMessagesOption
- type GetMessagesOptions
- type GraphContext
- type GraphPath
- type GraphRAGStore
- type GraphSchema
- type GraphSearchMode
- type GraphSearchOption
- func WithEntityTypes(types ...string) GraphSearchOption
- func WithIncludeRelationships(include bool) GraphSearchOption
- func WithMaxDepth(depth int) GraphSearchOption
- func WithMinGraphScore(score float32) GraphSearchOption
- func WithRelationshipTypes(types ...string) GraphSearchOption
- func WithSearchMode(mode GraphSearchMode) GraphSearchOption
- func WithSearchTenant(tenant string) GraphSearchOption
- type GraphSearchOptions
- type GraphSearchResult
- type GraphStoreOption
- type GraphStoreOptions
- type Guardrails
- type ImageData
- type ImageEditOptions
- type ImageEditResponse
- type ImageEditSession
- type ImageEditSessionOptions
- type ImageEditTurn
- type ImageGenerationOption
- type ImageGenerationOptions
- type ImageGenerationRequest
- type ImageGenerationResponse
- type ImageGenerator
- type ImageReference
- type ImageUsage
- type InternalTool
- type JSONSchema
- type LLM
- type LLMConfig
- type LLMResponse
- type MCPContent
- type MCPMessage
- type MCPModelHint
- type MCPModelPreferences
- type MCPPrompt
- type MCPPromptArgument
- type MCPPromptCapabilities
- type MCPPromptMessage
- type MCPPromptResult
- type MCPResource
- type MCPResourceCapabilities
- type MCPResourceContent
- type MCPResourceType
- type MCPResourceUpdate
- type MCPResourceUpdateType
- type MCPSamplingRequest
- type MCPSamplingResponse
- type MCPServer
- type MCPServerCapabilities
- type MCPServerInfo
- type MCPTokenUsage
- type MCPTool
- type MCPToolCapabilities
- type MCPToolResponse
- type Memory
- type MemoryUnwrapper
- type Message
- type MessageRole
- type MultiTurnImageEditor
- type ParameterSpec
- type Part
- type PropertySchema
- type QueryOption
- type QueryOptions
- type Relationship
- type RelationshipDirection
- type RelationshipTypeSchema
- type ResponseFormat
- type ResponseFormatType
- type RetryPolicy
- type SearchOption
- func WithBM25(useBM25 bool) SearchOption
- func WithEmbedding(useEmbedding bool) SearchOption
- func WithFields(fields ...string) SearchOption
- func WithFilters(filters map[string]interface{}) SearchOption
- func WithKeyword(useKeyword bool) SearchOption
- func WithMinScore(score float32) SearchOption
- func WithNearText(useNearText bool) SearchOption
- func WithTenantSearch(tenant string) SearchOption
- type SearchOptions
- type SearchResult
- type Span
- type StoreOption
- type StoreOptions
- type StreamConfig
- type StreamEvent
- type StreamEventType
- type StreamForwarder
- type StreamingAgent
- type StreamingLLM
- type TaskExecutordeprecated
- type TaskOptions
- type TaskPlanner
- type TaskResult
- type TaskService
- type TokenUsage
- type Tool
- type ToolCall
- type ToolCallEvent
- type ToolRegistry
- type ToolWithDisplayName
- type Tracer
- type Transaction
- type VectorStore
- type VectorStoreConfig
Constants ¶
const ( // MetadataKeyUsage holds a *TokenUsage for the completed run. MetadataKeyUsage = "usage" // MetadataKeyModel holds the primary model name as a string. MetadataKeyModel = "model" // MetadataKeyExecutionSummary holds an ExecutionSummary value. MetadataKeyExecutionSummary = "execution_summary" )
Metadata keys carried on an AgentEventComplete event.
Token accounting rides on the completion event so that a consumer wrapping an agent -- notably a sub-agent tool -- can recover usage without running the agent a second time.
Variables ¶
var ( // ErrImageGenerationNotSupported indicates the model doesn't support image generation ErrImageGenerationNotSupported = errors.New("image generation not supported by this model") // ErrContentBlocked indicates the content was blocked by safety filters ErrContentBlocked = errors.New("content blocked by safety filters") // ErrRateLimitExceeded indicates rate limiting triggered ErrRateLimitExceeded = errors.New("rate limit exceeded") // ErrInvalidPrompt indicates an invalid or empty prompt ErrInvalidPrompt = errors.New("invalid or empty prompt") // ErrStorageUploadFailed indicates failed to upload image to storage ErrStorageUploadFailed = errors.New("failed to upload image to storage") // ErrSessionNotFound indicates the image editing session was not found ErrSessionNotFound = errors.New("image editing session not found") // ErrSessionExpired indicates the image editing session has expired ErrSessionExpired = errors.New("image editing session has expired") // ErrMultiTurnNotSupported indicates multi-turn image editing is not supported ErrMultiTurnNotSupported = errors.New("multi-turn image editing not supported by this model") )
Image generation errors
var ErrContentUnsupported = errors.New("content part is not supported")
ErrContentUnsupported is returned by a provider, or by an agent path, that cannot send a part to the model. The part is refused instead of dropped.
var StreamForwarderKey = streamForwarderContextKey{}
StreamForwarderKey is the exported context key for stream forwarders
Functions ¶
func ApplyImageGenerationOptions ¶ added in v0.2.35
func ApplyImageGenerationOptions(opts *ImageGenerationOptions, options ...ImageGenerationOption)
ApplyImageGenerationOptions applies a list of options to ImageGenerationOptions
func CheckMedia ¶ added in v0.2.84
func CheckMedia(ctx context.Context, options *GenerateOptions, provider string, supported func(*Part) bool) error
CheckMedia returns ErrContentUnsupported, naming the provider and the MIME type, for the first non-text part of the request that supported rejects. Providers call it before building a request, so a part they cannot send is refused instead of dropped. A nil supported rejects every non-text part.
func PromptText ¶ added in v0.2.84
func PromptText(prompt string, options *GenerateOptions) string
PromptText returns the text of the current user turn, for a provider that sends text only: the text parts set with WithParts when there is no memory and parts are set, or prompt otherwise.
func ValidateParts ¶ added in v0.2.84
ValidateParts validates every part and names the first invalid one.
func WithIncludeIntermediateMessages ¶ added in v0.0.46
func WithIncludeIntermediateMessages(include bool) func(*StreamConfig)
WithIncludeIntermediateMessages returns a StreamConfig option to include intermediate messages
Types ¶
type AdminConversationMemory ¶ added in v0.1.7
type AdminConversationMemory interface {
ConversationMemory
// GetAllConversationsAcrossOrgs returns all conversation IDs from all organizations
GetAllConversationsAcrossOrgs() (map[string][]string, error) // map[orgID][]conversationID
// GetConversationMessagesAcrossOrgs finds conversation in any org and returns messages
GetConversationMessagesAcrossOrgs(conversationID string) ([]Message, string, error) // messages, orgID, error
// GetMemoryStatisticsAcrossOrgs returns memory statistics across all organizations
GetMemoryStatisticsAcrossOrgs() (totalConversations, totalMessages int, err error)
}
AdminConversationMemory extends ConversationMemory with cross-org operations
func AsAdminConversationMemory ¶ added in v0.2.71
func AsAdminConversationMemory(m Memory) (AdminConversationMemory, bool)
AsAdminConversationMemory reports whether m, or any Memory it decorates, supports cross-organization conversation operations.
type AgentEventType ¶ added in v0.0.34
type AgentEventType string
AgentEventType represents the type of agent streaming event
const ( AgentEventContent AgentEventType = "content" AgentEventThinking AgentEventType = "thinking" AgentEventToolCall AgentEventType = "tool_call" AgentEventToolResult AgentEventType = "tool_result" AgentEventError AgentEventType = "error" AgentEventComplete AgentEventType = "complete" )
type AgentResponse ¶ added in v0.1.13
type AgentResponse struct {
Content string
Usage *TokenUsage
AgentName string
Model string
ExecutionSummary ExecutionSummary
Metadata map[string]interface{}
}
type AgentStreamEvent ¶ added in v0.0.34
type AgentStreamEvent struct {
Type AgentEventType `json:"type"`
Content string `json:"content,omitempty"`
ToolCall *ToolCallEvent `json:"tool_call,omitempty"`
ThinkingStep string `json:"thinking_step,omitempty"`
Error error `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
AgentStreamEvent represents a streaming event from an agent
type AgentTaskServiceInterface ¶ added in v0.0.3
type AgentTaskServiceInterface[AgentTask any, AgentCreateRequest any, AgentApproveRequest any, AgentTaskUpdate any] interface { // CreateTask creates a new task CreateTask(ctx context.Context, req AgentCreateRequest) (AgentTask, error) // GetTask gets a task by ID GetTask(ctx context.Context, taskID string) (AgentTask, error) // ListTasks returns all tasks for a user ListTasks(ctx context.Context, userID string) ([]AgentTask, error) // ApproveTaskPlan approves or rejects a task plan ApproveTaskPlan(ctx context.Context, taskID string, req AgentApproveRequest) (AgentTask, error) // UpdateTask updates an existing task with new steps or modifications UpdateTask(ctx context.Context, taskID string, conversationID string, updates []AgentTaskUpdate) (AgentTask, error) // AddTaskLog adds a log entry to a task AddTaskLog(ctx context.Context, taskID string, message string, level string) error }
AgentTaskServiceInterface is a generic interface for agent task services
type Blob ¶ added in v0.2.84
type Blob struct {
MIMEType string `json:"mimeType"`
Data []byte `json:"data"`
// DisplayName optionally names the data, such as a file name. Providers
// that label files, such as OpenAI for PDFs, send it.
DisplayName string `json:"displayName,omitempty"`
}
Blob is raw data with its MIME type.
type CacheConfig ¶ added in v0.2.32
type CacheConfig struct {
// CacheSystemMessage marks the system message for caching
CacheSystemMessage bool
// CacheTools marks all tool definitions for caching (cache_control on last tool)
CacheTools bool
// CacheConversation marks conversation history for caching (cache_control on last message)
// Each new turn just appends to the cached prefix
CacheConversation bool
}
CacheConfig contains configuration for prompt caching (Anthropic only) Cache breakpoints cache everything UP TO AND INCLUDING the marked block. Order: tools → system → messages
type CollectionRef ¶
type CollectionRef interface {
// Insert inserts a document into the collection
Insert(ctx context.Context, data map[string]interface{}) (string, error)
// Get retrieves a document by ID
Get(ctx context.Context, id string) (map[string]interface{}, error)
// Update updates a document by ID
Update(ctx context.Context, id string, data map[string]interface{}) error
// Delete deletes a document by ID
Delete(ctx context.Context, id string) error
// Query queries documents in the collection
Query(ctx context.Context, filter map[string]interface{}, options ...QueryOption) ([]map[string]interface{}, error)
}
CollectionRef represents a reference to a collection/table
type Content ¶ added in v0.2.84
type Content struct {
// Role is the sender of the content. Run input must be from the user; an
// empty role means user.
Role MessageRole `json:"role,omitempty"`
// Parts are the pieces of the content, in the order the model reads them.
Parts []*Part `json:"parts,omitempty"`
}
Content is a multipart message for an agent: an ordered list of parts, such as text, an image, or a PDF. It follows the shape of Google ADK's genai.Content.
Pass it to the agent's RunWithContent:
content := interfaces.NewContentFromParts([]*interfaces.Part{
interfaces.NewPartFromBytes(png, "image/png"),
interfaces.NewPartFromText("What is in this picture?"),
}, interfaces.MessageRoleUser)
answer, err := myAgent.RunWithContent(ctx, content)
func NewContentFromParts ¶ added in v0.2.84
func NewContentFromParts(parts []*Part, role MessageRole) *Content
NewContentFromParts returns a content with the given parts.
func NewContentFromText ¶ added in v0.2.84
func NewContentFromText(text string, role MessageRole) *Content
NewContentFromText returns a content with one text part.
type ConversationMemory ¶ added in v0.1.7
type ConversationMemory interface {
Memory
// GetAllConversations returns all conversation IDs for current org
GetAllConversations(ctx context.Context) ([]string, error)
// GetConversationMessages gets all messages for a specific conversation in current org
GetConversationMessages(ctx context.Context, conversationID string) ([]Message, error)
// GetMemoryStatistics returns basic memory statistics for current org
GetMemoryStatistics(ctx context.Context) (totalConversations, totalMessages int, err error)
}
ConversationMemory extends Memory interface with conversation-level operations
func AsConversationMemory ¶ added in v0.2.71
func AsConversationMemory(m Memory) (ConversationMemory, bool)
AsConversationMemory reports whether m, or any Memory it decorates, supports conversation-level operations.
Prefer this over a bare m.(ConversationMemory) assertion: the bare form returns false for a perfectly capable Memory that merely happens to be wrapped in tracing or another decorator.
type DataStore ¶
type DataStore interface {
// Collection returns a reference to a specific collection/table
Collection(name string) CollectionRef
// Transaction executes multiple operations in a transaction
Transaction(ctx context.Context, fn func(tx Transaction) error) error
// Close closes the database connection
Close() error
}
DataStore represents a database for storing structured data
type DeleteOption ¶
type DeleteOption func(*DeleteOptions)
DeleteOption represents an option for deleting documents
func WithTenantDelete ¶ added in v0.0.24
func WithTenantDelete(tenant string) DeleteOption
WithTenantDelete sets the tenant for native multi-tenancy delete operations
type DeleteOptions ¶
type DeleteOptions struct {
// Class is the class/collection name to delete from
Class string
// Tenant is the tenant name for native multi-tenancy
Tenant string
}
DeleteOptions contains options for deleting documents
type Document ¶
type Document struct {
// ID is the unique identifier for the document
ID string
// Content is the text content of the document
Content string
// Vector is the embedding vector for the document
// If nil, the vector store will generate it
Vector []float32
// Metadata contains additional information about the document
Metadata map[string]interface{}
}
Document represents a document to be stored in a vector store
type Embedder ¶ added in v0.0.2
type Embedder interface {
// Embed generates an embedding for the given text
Embed(ctx context.Context, text string) ([]float32, error)
// EmbedBatch generates embeddings for multiple texts
EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
// CalculateSimilarity calculates the similarity between two embeddings
CalculateSimilarity(vec1, vec2 []float32, metric string) (float32, error)
}
Embedder represents a service that can convert text into embeddings
type Entity ¶ added in v0.2.28
type Entity struct {
// ID is the unique identifier for the entity
ID string `json:"id"`
// Name is the human-readable name of the entity
Name string `json:"name"`
// Type categorizes the entity (e.g., "Person", "Organization", "Concept")
Type string `json:"type"`
// Description provides detailed information about the entity
Description string `json:"description"`
// Embedding is the vector representation of the entity
Embedding []float32 `json:"embedding,omitempty"`
// Properties contains additional key-value attributes
Properties map[string]interface{} `json:"properties,omitempty"`
// OrgID is the organization ID for multi-tenancy
OrgID string `json:"org_id,omitempty"`
// CreatedAt is the creation timestamp
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is the last update timestamp
UpdatedAt time.Time `json:"updated_at"`
}
Entity represents a node in the knowledge graph
type EntityTypeSchema ¶ added in v0.2.28
type EntityTypeSchema struct {
// Name is the type name (e.g., "Person")
Name string `json:"name"`
// Description describes the entity type
Description string `json:"description"`
// Properties defines the expected properties
Properties []PropertySchema `json:"properties,omitempty"`
}
EntityTypeSchema defines an entity type in the schema
type ExecutionSummary ¶ added in v0.1.13
type ExtractionOption ¶ added in v0.2.28
type ExtractionOption func(*ExtractionOptions)
ExtractionOption represents an option for extraction operations
func WithDedupThreshold ¶ added in v0.2.28
func WithDedupThreshold(threshold float32) ExtractionOption
WithDedupThreshold sets the embedding similarity threshold for deduplication
func WithExtractionEntityTypes ¶ added in v0.2.28
func WithExtractionEntityTypes(types ...string) ExtractionOption
WithExtractionEntityTypes limits extraction to specific entity types
func WithExtractionRelationshipTypes ¶ added in v0.2.28
func WithExtractionRelationshipTypes(types ...string) ExtractionOption
WithExtractionRelationshipTypes limits extraction to specific relationship types
func WithMaxEntities ¶ added in v0.2.28
func WithMaxEntities(max int) ExtractionOption
WithMaxEntities limits the number of extracted entities
func WithMinConfidence ¶ added in v0.2.28
func WithMinConfidence(confidence float32) ExtractionOption
WithMinConfidence sets the minimum extraction confidence
func WithSchemaGuided ¶ added in v0.2.28
func WithSchemaGuided(guided bool) ExtractionOption
WithSchemaGuided enables schema-guided extraction
type ExtractionOptions ¶ added in v0.2.28
type ExtractionOptions struct {
// SchemaGuided indicates whether to use schema-guided extraction
SchemaGuided bool
// EntityTypes limits extraction to specific entity types
EntityTypes []string
// RelationshipTypes limits extraction to specific relationship types
RelationshipTypes []string
// MinConfidence filters entities/relationships by minimum confidence
MinConfidence float32
// MaxEntities limits the number of entities to extract
MaxEntities int
// DedupThreshold is the embedding similarity threshold for deduplication
DedupThreshold float32
}
ExtractionOptions contains options for extraction operations
type ExtractionResult ¶ added in v0.2.28
type ExtractionResult struct {
// Entities are the extracted entities
Entities []Entity `json:"entities"`
// Relationships are the extracted relationships
Relationships []Relationship `json:"relationships"`
// SourceText is the original text
SourceText string `json:"source_text"`
// Confidence is the overall extraction confidence (0-1)
Confidence float32 `json:"confidence"`
}
ExtractionResult contains extracted entities and relationships from text
type FileData ¶ added in v0.2.84
type FileData struct {
MIMEType string `json:"mimeType"`
FileURI string `json:"fileUri"`
// DisplayName optionally names the data, such as a file name.
DisplayName string `json:"displayName,omitempty"`
}
FileData is a URI to data, with the data's MIME type.
type GenerateOption ¶
type GenerateOption func(options *GenerateOptions)
GenerateOption represents options for text generation
func WithDisableFinalSummary ¶ added in v0.2.41
func WithDisableFinalSummary(disable bool) GenerateOption
WithDisableFinalSummary creates a GenerateOption to disable the final summary LLM call
func WithFrequencyPenalty ¶ added in v0.0.43
func WithFrequencyPenalty(frequencyPenalty float64) GenerateOption
WithFrequencyPenalty creates a GenerateOption to set the frequency penalty
func WithMaxIterations ¶ added in v0.0.19
func WithMaxIterations(maxIterations int) GenerateOption
WithMaxIterations creates a GenerateOption to set the maximum number of tool-calling iterations
func WithMaxTokens ¶ added in v0.2.80
func WithMaxTokens(maxTokens int) GenerateOption
WithMaxTokens creates a GenerateOption to cap output tokens for one request.
A value of zero or less is ignored, leaving the provider default in place, so callers can pass a config value through without special-casing "unset".
func WithMemory ¶ added in v0.0.30
func WithMemory(memory Memory) GenerateOption
WithMemory creates a GenerateOption to set the memory for storing tool calls and results
func WithParts ¶ added in v0.2.84
func WithParts(parts ...*Part) GenerateOption
WithParts sets the current user turn as content parts. The parts replace the prompt text, so include the text as a text part.
Providers read these only when no memory is set. With memory, the current turn comes from the last user message in memory, so the parts must be stored on that message (Message.Parts) instead. The agent does this for you.
func WithPresencePenalty ¶ added in v0.0.43
func WithPresencePenalty(presencePenalty float64) GenerateOption
WithPresencePenalty creates a GenerateOption to set the presence penalty
func WithReasoning ¶ added in v0.0.34
func WithReasoning(enabled bool, budget ...int) GenerateOption
WithReasoning creates a GenerateOption to enable native reasoning tokens
func WithResponseFormat ¶ added in v0.0.43
func WithResponseFormat(format ResponseFormat) GenerateOption
WithResponseFormat creates a GenerateOption to set the response format
func WithStopSequences ¶ added in v0.0.43
func WithStopSequences(stopSequences []string) GenerateOption
WithStopSequences creates a GenerateOption to set the stop sequences
func WithStreamConfig ¶ added in v0.0.34
func WithStreamConfig(config StreamConfig) GenerateOption
WithStreamConfig creates a GenerateOption to set the streaming configuration
func WithSystemMessage ¶ added in v0.0.43
func WithSystemMessage(systemMessage string) GenerateOption
WithSystemMessage creates a GenerateOption to set the system message
func WithTemperature ¶ added in v0.0.43
func WithTemperature(temperature float64) GenerateOption
WithTemperature creates a GenerateOption to set the temperature
func WithTopP ¶ added in v0.0.43
func WithTopP(topP float64) GenerateOption
WithTopP creates a GenerateOption to set the top_p
type GenerateOptions ¶
type GenerateOptions struct {
LLMConfig *LLMConfig // LLM config for the generation
OrgID string // For multi-tenancy
SystemMessage string // System message for chat models
ResponseFormat *ResponseFormat // Optional expected response format
MaxIterations int // Maximum number of tool-calling iterations (0 = use default)
DisableFinalSummary bool // When true, skip the final "provide final response" LLM call
Memory Memory // Optional memory for storing tool calls and results
StreamConfig *StreamConfig // Optional streaming configuration
CacheConfig *CacheConfig // Optional prompt caching configuration (Anthropic only)
Parts []*Part // Current user turn as content parts, replacing the prompt; read only when Memory is nil
}
GenerateOptions contains configuration for text generation
type GeneratedImage ¶ added in v0.2.35
type GeneratedImage struct {
// Data contains the raw image bytes
Data []byte
// Base64 contains the base64-encoded image data
Base64 string
// MimeType is the MIME type of the image (e.g., "image/png", "image/jpeg")
MimeType string
// URL is the storage URL (populated after upload to storage)
URL string
// RevisedPrompt is the prompt actually used by the model (may differ from input)
RevisedPrompt string
// FinishReason indicates why generation stopped
FinishReason string
}
GeneratedImage represents a single generated image
type GetMessagesOption ¶
type GetMessagesOption func(*GetMessagesOptions)
GetMessagesOption represents an option for retrieving messages
func WithLimit ¶
func WithLimit(limit int) GetMessagesOption
WithLimit sets the maximum number of messages to retrieve
func WithQuery ¶
func WithQuery(query string) GetMessagesOption
WithQuery sets a search query for relevant messages
func WithRoles ¶
func WithRoles(roles ...string) GetMessagesOption
WithRoles filters messages by role
type GetMessagesOptions ¶
type GetMessagesOptions struct {
// Limit is the maximum number of messages to retrieve
Limit int
// Roles filters messages by role
Roles []string
// Query is a search query for relevant messages
Query string
}
GetMessagesOptions contains options for retrieving messages
type GraphContext ¶ added in v0.2.28
type GraphContext struct {
// CentralEntity is the starting point of the traversal
CentralEntity Entity `json:"central_entity"`
// Entities are all entities discovered within the traversal depth
Entities []Entity `json:"entities"`
// Relationships are all relationships discovered in the traversal
Relationships []Relationship `json:"relationships"`
// Depth is the actual traversal depth reached
Depth int `json:"depth"`
}
GraphContext represents context around a central entity from graph traversal
type GraphPath ¶ added in v0.2.28
type GraphPath struct {
// Source is the starting entity
Source Entity `json:"source"`
// Target is the destination entity
Target Entity `json:"target"`
// Entities are intermediate entities (ordered)
Entities []Entity `json:"entities"`
// Relationships are relationships connecting the entities (ordered)
Relationships []Relationship `json:"relationships"`
// Length is the number of hops
Length int `json:"length"`
}
GraphPath represents a path between two entities
type GraphRAGStore ¶ added in v0.2.28
type GraphRAGStore interface {
// Entity CRUD operations
StoreEntities(ctx context.Context, entities []Entity, options ...GraphStoreOption) error
GetEntity(ctx context.Context, id string, options ...GraphStoreOption) (*Entity, error)
UpdateEntity(ctx context.Context, entity Entity, options ...GraphStoreOption) error
DeleteEntity(ctx context.Context, id string, options ...GraphStoreOption) error
// Relationship CRUD operations
StoreRelationships(ctx context.Context, relationships []Relationship, options ...GraphStoreOption) error
GetRelationships(ctx context.Context, entityID string, direction RelationshipDirection, options ...GraphSearchOption) ([]Relationship, error)
DeleteRelationship(ctx context.Context, id string, options ...GraphStoreOption) error
// Search operations
Search(ctx context.Context, query string, limit int, options ...GraphSearchOption) ([]GraphSearchResult, error)
LocalSearch(ctx context.Context, query string, entityID string, depth int, options ...GraphSearchOption) ([]GraphSearchResult, error)
GlobalSearch(ctx context.Context, query string, communityLevel int, options ...GraphSearchOption) ([]GraphSearchResult, error)
// Graph traversal
TraverseFrom(ctx context.Context, entityID string, depth int, options ...GraphSearchOption) (*GraphContext, error)
ShortestPath(ctx context.Context, sourceID, targetID string, options ...GraphSearchOption) (*GraphPath, error)
// Entity/Relationship extraction (requires LLM)
ExtractFromText(ctx context.Context, text string, llm LLM, options ...ExtractionOption) (*ExtractionResult, error)
// Schema management
ApplySchema(ctx context.Context, schema GraphSchema) error
DiscoverSchema(ctx context.Context) (*GraphSchema, error)
// Multi-tenancy
SetTenant(tenant string)
GetTenant() string
// Lifecycle
Close() error
}
GraphRAGStore defines the interface for graph-based retrieval-augmented generation
type GraphSchema ¶ added in v0.2.28
type GraphSchema struct {
// EntityTypes are the allowed entity type definitions
EntityTypes []EntityTypeSchema `json:"entity_types"`
// RelationshipTypes are the allowed relationship type definitions
RelationshipTypes []RelationshipTypeSchema `json:"relationship_types"`
}
GraphSchema defines the structure of the knowledge graph
type GraphSearchMode ¶ added in v0.2.28
type GraphSearchMode string
GraphSearchMode specifies the type of search to perform
const ( // SearchModeVector uses vector similarity search SearchModeVector GraphSearchMode = "vector" // SearchModeKeyword uses keyword/BM25 search SearchModeKeyword GraphSearchMode = "keyword" // SearchModeHybrid combines vector and keyword search SearchModeHybrid GraphSearchMode = "hybrid" )
type GraphSearchOption ¶ added in v0.2.28
type GraphSearchOption func(*GraphSearchOptions)
GraphSearchOption represents an option for graph search operations
func WithEntityTypes ¶ added in v0.2.28
func WithEntityTypes(types ...string) GraphSearchOption
WithEntityTypes filters search by entity types
func WithIncludeRelationships ¶ added in v0.2.28
func WithIncludeRelationships(include bool) GraphSearchOption
WithIncludeRelationships includes relationships in results
func WithMaxDepth ¶ added in v0.2.28
func WithMaxDepth(depth int) GraphSearchOption
WithMaxDepth sets maximum traversal depth
func WithMinGraphScore ¶ added in v0.2.28
func WithMinGraphScore(score float32) GraphSearchOption
WithMinGraphScore sets the minimum similarity score
func WithRelationshipTypes ¶ added in v0.2.28
func WithRelationshipTypes(types ...string) GraphSearchOption
WithRelationshipTypes filters search by relationship types
func WithSearchMode ¶ added in v0.2.28
func WithSearchMode(mode GraphSearchMode) GraphSearchOption
WithSearchMode sets the search mode
func WithSearchTenant ¶ added in v0.2.28
func WithSearchTenant(tenant string) GraphSearchOption
WithSearchTenant sets the tenant for search operations
type GraphSearchOptions ¶ added in v0.2.28
type GraphSearchOptions struct {
// MinScore is the minimum similarity score (0-1)
MinScore float32
// EntityTypes filters by entity types
EntityTypes []string
// RelationshipTypes filters by relationship types
RelationshipTypes []string
// MaxDepth limits traversal depth (default: 2)
MaxDepth int
// IncludeRelationships includes relationships in search results
IncludeRelationships bool
// Tenant is the tenant name for native multi-tenancy
Tenant string
// SearchMode specifies the search mode
SearchMode GraphSearchMode
}
GraphSearchOptions contains options for searching graph data
type GraphSearchResult ¶ added in v0.2.28
type GraphSearchResult struct {
// Entity is the found entity
Entity Entity `json:"entity"`
// Score is the relevance score (0-1, higher is more relevant)
Score float32 `json:"score"`
// Context contains related entities from graph traversal
Context []Entity `json:"context,omitempty"`
// Path represents the relationship path to this entity (for local search)
Path []Relationship `json:"path,omitempty"`
// CommunityID is the community identifier (for global search)
CommunityID string `json:"community_id,omitempty"`
}
GraphSearchResult represents a search result from the knowledge graph
type GraphStoreOption ¶ added in v0.2.28
type GraphStoreOption func(*GraphStoreOptions)
GraphStoreOption represents an option for graph store operations
func WithGenerateEmbeddings ¶ added in v0.2.28
func WithGenerateEmbeddings(generate bool) GraphStoreOption
WithGenerateEmbeddings sets whether to generate embeddings
func WithGraphBatchSize ¶ added in v0.2.28
func WithGraphBatchSize(size int) GraphStoreOption
WithGraphBatchSize sets the batch size for store operations
func WithGraphTenant ¶ added in v0.2.28
func WithGraphTenant(tenant string) GraphStoreOption
WithGraphTenant sets the tenant for graph operations
type GraphStoreOptions ¶ added in v0.2.28
type GraphStoreOptions struct {
// BatchSize is the number of items to store in each batch
BatchSize int
// GenerateEmbeddings indicates whether to generate embeddings
GenerateEmbeddings bool
// Tenant is the tenant name for native multi-tenancy
Tenant string
}
GraphStoreOptions contains options for storing graph data
type Guardrails ¶
type Guardrails interface {
// ProcessInput processes user input before sending to the LLM
ProcessInput(ctx context.Context, input string) (string, error)
// ProcessOutput processes LLM output before returning to the user
ProcessOutput(ctx context.Context, output string) (string, error)
}
Guardrails represents a system for ensuring safe and appropriate responses
type ImageData ¶ added in v0.2.35
type ImageData struct {
// Data contains raw image bytes
Data []byte
// Base64 contains base64-encoded image data
Base64 string
// MimeType is the MIME type (e.g., "image/jpeg", "image/png")
MimeType string
// URL is a URL to fetch the image from
URL string
}
ImageData represents input image data for image-to-image generation
type ImageEditOptions ¶ added in v0.2.36
type ImageEditOptions struct {
// AspectRatio controls the output image dimensions
// Supported values: "1:1", "2:3", "3:2", "16:9", "21:9"
AspectRatio string
// ImageSize controls the output image resolution
// Supported values: "1K", "2K", "4K"
ImageSize string
}
ImageEditOptions configures a single turn in the image editing session
func DefaultImageEditOptions ¶ added in v0.2.36
func DefaultImageEditOptions() *ImageEditOptions
DefaultImageEditOptions returns default options for image editing
type ImageEditResponse ¶ added in v0.2.36
type ImageEditResponse struct {
// Text contains the text response from the model (if any)
Text string
// Images contains generated/edited images (if any)
Images []GeneratedImage
// Usage contains token/cost information if available
Usage *ImageUsage
// Metadata contains provider-specific information
Metadata map[string]interface{}
}
ImageEditResponse represents the result of an image editing turn
type ImageEditSession ¶ added in v0.2.36
type ImageEditSession interface {
// SendMessage sends a text message and returns the response (text and/or image)
SendMessage(ctx context.Context, message string, options *ImageEditOptions) (*ImageEditResponse, error)
// SendMessageWithImage sends a message with an image reference for editing
SendMessageWithImage(ctx context.Context, message string, image *ImageData, options *ImageEditOptions) (*ImageEditResponse, error)
// GetHistory returns the conversation history for this session
GetHistory() []ImageEditTurn
// Close closes the session and releases resources
Close() error
}
ImageEditSession represents a multi-turn image editing session that maintains conversation context for iterative image creation and modification.
type ImageEditSessionOptions ¶ added in v0.2.36
type ImageEditSessionOptions struct {
// Model specifies the model to use (e.g., "gemini-3-pro-image-preview")
// If empty, the provider's default image editing model will be used
Model string
// SystemInstruction provides optional system-level guidance for the session
SystemInstruction string
// Tools lists optional tools to enable (e.g., "google_search")
Tools []string
}
ImageEditSessionOptions configures a new image editing session
type ImageEditTurn ¶ added in v0.2.36
type ImageEditTurn struct {
// Role is either "user" or "model"
Role string
// Message is the text content of this turn
Message string
// Images contains any images in this turn
Images []*ImageData
}
ImageEditTurn represents a single turn in the image editing conversation
type ImageGenerationOption ¶ added in v0.2.35
type ImageGenerationOption func(*ImageGenerationOptions)
ImageGenerationOption represents options for image generation
func WithAspectRatio ¶ added in v0.2.35
func WithAspectRatio(ratio string) ImageGenerationOption
WithAspectRatio sets the aspect ratio
func WithNumberOfImages ¶ added in v0.2.35
func WithNumberOfImages(n int) ImageGenerationOption
WithNumberOfImages sets how many images to generate
func WithOutputFormat ¶ added in v0.2.35
func WithOutputFormat(format string) ImageGenerationOption
WithOutputFormat sets the output image format
func WithSafetyFilter ¶ added in v0.2.35
func WithSafetyFilter(level string) ImageGenerationOption
WithSafetyFilter sets the safety filter level
type ImageGenerationOptions ¶ added in v0.2.35
type ImageGenerationOptions struct {
// NumberOfImages specifies how many images to generate (default: 1)
NumberOfImages int
// AspectRatio controls the image dimensions (e.g., "1:1", "16:9", "9:16", "4:3", "3:4")
AspectRatio string
// OutputFormat specifies the desired output format ("png", "jpeg")
OutputFormat string
// SafetyFilterLevel controls content filtering ("none", "low", "medium", "high")
SafetyFilterLevel string
}
ImageGenerationOptions configures image generation behavior
func DefaultImageGenerationOptions ¶ added in v0.2.35
func DefaultImageGenerationOptions() *ImageGenerationOptions
DefaultImageGenerationOptions returns the default options for image generation
type ImageGenerationRequest ¶ added in v0.2.35
type ImageGenerationRequest struct {
// Prompt is the text description of the image to generate (required)
Prompt string
// ReferenceImage is an optional input image for image-to-image generation
ReferenceImage *ImageData
// Options contains generation configuration
Options *ImageGenerationOptions
}
ImageGenerationRequest represents a request to generate an image
type ImageGenerationResponse ¶ added in v0.2.35
type ImageGenerationResponse struct {
// Images contains the generated images
Images []GeneratedImage
// Usage contains token/cost information if available
Usage *ImageUsage
// Metadata contains provider-specific information
Metadata map[string]interface{}
}
ImageGenerationResponse represents the result of image generation
type ImageGenerator ¶ added in v0.2.35
type ImageGenerator interface {
// GenerateImage generates one or more images from a text prompt
GenerateImage(ctx context.Context, request ImageGenerationRequest) (*ImageGenerationResponse, error)
// SupportsImageGeneration returns true if this LLM supports image generation
SupportsImageGeneration() bool
// SupportedImageFormats returns the output formats supported (e.g., "png", "jpeg")
SupportedImageFormats() []string
}
ImageGenerator represents an LLM that can generate images
type ImageReference ¶ added in v0.2.35
type ImageReference struct {
// URL is the storage URL of the generated image
URL string
// MimeType is the image MIME type
MimeType string
// Prompt is the original prompt used to generate the image
Prompt string
// CreatedAt is the timestamp when the image was generated
CreatedAt time.Time
}
ImageReference represents a reference to a generated image stored in memory
type ImageUsage ¶ added in v0.2.35
type ImageUsage struct {
// InputTokens used for the prompt
InputTokens int
// OutputTokens used for generation
OutputTokens int
// ImagesGenerated is the number of images produced
ImagesGenerated int
}
ImageUsage represents usage/cost information for image generation
type InternalTool ¶ added in v0.0.53
type InternalTool interface {
// Internal returns true if this tool's usage should be hidden from users
// This can be used to filter tool calls in OnToolCall or other display contexts
Internal() bool
}
InternalTool is an optional interface that tools can implement to indicate they should be hidden from users
type JSONSchema ¶ added in v0.0.4
type JSONSchema map[string]interface{}
func (JSONSchema) MarshalJSON ¶ added in v0.0.4
func (s JSONSchema) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface
type LLM ¶
type LLM interface {
// Generate generates text based on the provided prompt
Generate(ctx context.Context, prompt string, options ...GenerateOption) (string, error)
// GenerateWithTools generates text and can use tools
GenerateWithTools(ctx context.Context, prompt string, tools []Tool, options ...GenerateOption) (string, error)
// GenerateDetailed generates text and returns detailed response information including token usage
GenerateDetailed(ctx context.Context, prompt string, options ...GenerateOption) (*LLMResponse, error)
// GenerateWithToolsDetailed generates text with tools and returns detailed response information including token usage
GenerateWithToolsDetailed(ctx context.Context, prompt string, tools []Tool, options ...GenerateOption) (*LLMResponse, error)
// Name returns the name of the LLM provider
Name() string
// SupportsStreaming returns true if this LLM supports streaming
SupportsStreaming() bool
}
LLM represents a large language model provider
type LLMConfig ¶ added in v0.0.11
type LLMConfig struct {
Temperature float64 // Temperature for the generation
TopP float64 // Top P for the generation
FrequencyPenalty float64 // Frequency penalty for the generation
PresencePenalty float64 // Presence penalty for the generation
StopSequences []string // Stop sequences for the generation
Reasoning string // Reasoning mode (minimal, low, medium, high) to control reasoning effort
EnableReasoning bool // Enable native reasoning tokens (Anthropic thinking/OpenAI o1)
ReasoningBudget int // Optional token budget for reasoning (Anthropic only), minimum 1024
// MaxTokens caps the output tokens a single generation may produce.
//
// Zero means "provider default", which keeps each provider's prior
// behaviour rather than imposing a cross-provider number: Anthropic
// defaults to 2048 and the OpenAI-compatible providers omit the field so
// the model's own default applies.
MaxTokens int
}
type LLMResponse ¶ added in v0.1.13
type LLMResponse struct {
// Content is the generated text response
Content string
// Usage contains token usage information (nil if not available)
Usage *TokenUsage
// Model indicates which model was used for generation
Model string
// StopReason indicates why the generation stopped (optional)
StopReason string
// Metadata contains provider-specific additional information
Metadata map[string]interface{}
}
LLMResponse represents the detailed response from an LLM generation request
type MCPContent ¶ added in v0.1.14
type MCPContent struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"` // base64 encoded for images/audio
MimeType string `json:"mimeType,omitempty"`
}
MCPContent represents different types of content
type MCPMessage ¶ added in v0.1.14
type MCPMessage struct {
Role string `json:"role"`
Content MCPContent `json:"content"`
Name string `json:"name,omitempty"`
}
MCPMessage represents a message in the conversation
type MCPModelHint ¶ added in v0.1.14
type MCPModelHint struct {
Name string `json:"name"`
}
MCPModelHint represents a model hint
type MCPModelPreferences ¶ added in v0.1.14
type MCPModelPreferences struct {
// Model hints (optional suggestions)
Hints []MCPModelHint `json:"hints,omitempty"`
// Priority values (0.0 to 1.0)
CostPriority float64 `json:"costPriority,omitempty"`
SpeedPriority float64 `json:"speedPriority,omitempty"`
IntelligencePriority float64 `json:"intelligencePriority,omitempty"`
}
MCPModelPreferences represents preferences for model selection
type MCPPrompt ¶ added in v0.1.14
type MCPPrompt struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Arguments []MCPPromptArgument `json:"arguments,omitempty"`
Schema map[string]interface{} `json:"schema,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
MCPPrompt represents a prompt template available on an MCP server
type MCPPromptArgument ¶ added in v0.1.14
type MCPPromptArgument struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Type string `json:"type,omitempty"`
Default interface{} `json:"default,omitempty"`
}
MCPPromptArgument represents an argument for a prompt template
type MCPPromptCapabilities ¶ added in v0.1.14
type MCPPromptCapabilities struct {
ListChanged bool `json:"listChanged,omitempty"`
}
MCPPromptCapabilities represents prompt-related capabilities
type MCPPromptMessage ¶ added in v0.1.14
type MCPPromptMessage struct {
Role string `json:"role"`
Content string `json:"content"`
Name string `json:"name,omitempty"`
Meta map[string]interface{} `json:"meta,omitempty"`
}
MCPPromptMessage represents a message in a prompt result
type MCPPromptResult ¶ added in v0.1.14
type MCPPromptResult struct {
Prompt string `json:"prompt"`
Messages []MCPPromptMessage `json:"messages,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
MCPPromptResult represents the result of getting a prompt with variables
type MCPResource ¶ added in v0.1.14
type MCPResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
MCPResource represents a resource available on an MCP server
type MCPResourceCapabilities ¶ added in v0.1.14
type MCPResourceCapabilities struct {
Subscribe bool `json:"subscribe,omitempty"`
ListChanged bool `json:"listChanged,omitempty"`
}
MCPResourceCapabilities represents resource-related capabilities
type MCPResourceContent ¶ added in v0.1.14
type MCPResourceContent struct {
URI string `json:"uri"`
MimeType string `json:"mimeType"`
Text string `json:"text,omitempty"`
Blob []byte `json:"blob,omitempty"`
Reader io.Reader `json:"-"` // For streaming content
Metadata map[string]string `json:"metadata,omitempty"`
}
MCPResourceContent represents the content of a resource
type MCPResourceType ¶ added in v0.1.14
type MCPResourceType string
MCPResourceType represents the type of MCP resource
const ( MCPResourceTypeText MCPResourceType = "text" MCPResourceTypeBinary MCPResourceType = "binary" MCPResourceTypeJSON MCPResourceType = "json" )
type MCPResourceUpdate ¶ added in v0.1.14
type MCPResourceUpdate struct {
URI string `json:"uri"`
Type MCPResourceUpdateType `json:"type"`
Content *MCPResourceContent `json:"content,omitempty"`
Timestamp time.Time `json:"timestamp"`
Error error `json:"error,omitempty"`
}
MCPResourceUpdate represents an update to a watched resource
type MCPResourceUpdateType ¶ added in v0.1.14
type MCPResourceUpdateType string
MCPResourceUpdateType represents the type of resource update
const ( MCPResourceUpdateTypeChanged MCPResourceUpdateType = "changed" MCPResourceUpdateTypeDeleted MCPResourceUpdateType = "deleted" MCPResourceUpdateTypeError MCPResourceUpdateType = "error" )
type MCPSamplingRequest ¶ added in v0.1.14
type MCPSamplingRequest struct {
Messages []MCPMessage `json:"messages"`
ModelPreferences *MCPModelPreferences `json:"modelPreferences,omitempty"`
SystemPrompt string `json:"systemPrompt,omitempty"`
IncludeContext string `json:"includeContext,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"maxTokens,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
MCPSamplingRequest represents a request for LLM sampling
type MCPSamplingResponse ¶ added in v0.1.14
type MCPSamplingResponse struct {
Role string `json:"role"`
Content MCPContent `json:"content"`
Model string `json:"model"`
StopReason string `json:"stopReason,omitempty"`
Usage *MCPTokenUsage `json:"usage,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
MCPSamplingResponse represents the response from LLM sampling
type MCPServer ¶ added in v0.0.13
type MCPServer interface {
// Initialize initializes the connection to the MCP server
Initialize(ctx context.Context) error
// ListTools lists the tools available on the MCP server
ListTools(ctx context.Context) ([]MCPTool, error)
// CallTool calls a tool on the MCP server
CallTool(ctx context.Context, name string, args interface{}) (*MCPToolResponse, error)
// ListResources lists the resources available on the MCP server
ListResources(ctx context.Context) ([]MCPResource, error)
// GetResource retrieves a specific resource by URI
GetResource(ctx context.Context, uri string) (*MCPResourceContent, error)
// WatchResource watches for changes to a resource (if supported)
WatchResource(ctx context.Context, uri string) (<-chan MCPResourceUpdate, error)
// ListPrompts lists the prompts available on the MCP server
ListPrompts(ctx context.Context) ([]MCPPrompt, error)
// GetPrompt retrieves a specific prompt with variables
GetPrompt(ctx context.Context, name string, variables map[string]interface{}) (*MCPPromptResult, error)
// Sampling Methods (if supported by client)
// CreateMessage requests the client to generate a completion using its LLM
CreateMessage(ctx context.Context, request *MCPSamplingRequest) (*MCPSamplingResponse, error)
// Metadata discovery methods
// GetServerInfo returns the server metadata discovered during initialization
GetServerInfo() (*MCPServerInfo, error)
// GetCapabilities returns the server capabilities discovered during initialization
GetCapabilities() (*MCPServerCapabilities, error)
// Close closes the connection to the MCP server
Close() error
}
MCPServer represents a connection to an MCP server
type MCPServerCapabilities ¶ added in v0.1.14
type MCPServerCapabilities struct {
Tools *MCPToolCapabilities `json:"tools,omitempty"`
Resources *MCPResourceCapabilities `json:"resources,omitempty"`
Prompts *MCPPromptCapabilities `json:"prompts,omitempty"`
}
MCPServerCapabilities represents server capabilities discovered during initialization
type MCPServerInfo ¶ added in v0.1.14
type MCPServerInfo struct {
Name string `json:"name"` // Required: server identifier
Title string `json:"title,omitempty"` // Optional: human-readable title
Version string `json:"version,omitempty"` // Optional: server version
}
MCPServerInfo represents server metadata discovered during initialization
type MCPTokenUsage ¶ added in v0.1.14
type MCPTokenUsage struct {
PromptTokens int `json:"promptTokens,omitempty"`
CompletionTokens int `json:"completionTokens,omitempty"`
TotalTokens int `json:"totalTokens,omitempty"`
}
MCPTokenUsage represents token usage information
type MCPTool ¶ added in v0.0.13
type MCPTool struct {
Name string `json:"name"`
Description string `json:"description"`
Schema interface{} `json:"inputSchema,omitempty"`
OutputSchema interface{} `json:"outputSchema,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
MCPTool represents a tool available on an MCP server
type MCPToolCapabilities ¶ added in v0.1.14
type MCPToolCapabilities struct {
ListChanged bool `json:"listChanged,omitempty"`
}
MCPToolCapabilities represents tool-related capabilities
type MCPToolResponse ¶ added in v0.0.13
type MCPToolResponse struct {
Content interface{} `json:"content,omitempty"`
StructuredContent interface{} `json:"structuredContent,omitempty"`
IsError bool `json:"isError,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
MCPToolResponse represents a response from a tool call
type Memory ¶
type Memory interface {
// AddMessage adds a message to memory
AddMessage(ctx context.Context, message Message) error
// GetMessages retrieves messages from memory
GetMessages(ctx context.Context, options ...GetMessagesOption) ([]Message, error)
// Clear clears the memory
Clear(ctx context.Context) error
}
Memory represents a memory store for agent conversations
func UnwrapMemory ¶ added in v0.2.71
UnwrapMemory walks a chain of MemoryUnwrapper decorators and returns the innermost Memory. It returns m unchanged when m is nil or wraps nothing.
type MemoryUnwrapper ¶ added in v0.2.71
type MemoryUnwrapper interface {
// Unwrap returns the Memory this value decorates.
Unwrap() Memory
}
MemoryUnwrapper is implemented by Memory decorators that wrap another Memory.
Memory is a three-method interface, and richer behaviour (ConversationMemory, AdminConversationMemory) is discovered by type assertion. A decorator that implements only the three core methods therefore hides every optional capability of the value it wraps, and the assertion fails silently: callers get an empty result rather than an error. Implementing Unwrap lets the AsConversationMemory / AsAdminConversationMemory helpers see through the decorator chain.
type Message ¶
type Message struct {
// Role is the role of the message sender
Role MessageRole
// Content is the content of the message
Content string
// Metadata contains additional information about the message
Metadata map[string]interface{}
// ToolCallID is used for tool messages to reference the tool call
ToolCallID string
// ToolCalls contains tool call information for assistant messages
ToolCalls []ToolCall
// Parts is the message as content parts, set when a user message carries
// media such as images. Content then holds the text parts, joined.
Parts []*Part `json:",omitempty"`
}
Message represents a message in a conversation
type MessageRole ¶ added in v0.0.58
type MessageRole string
MessageRole represents the role of a message sender
const ( // MessageRoleUser represents a user message MessageRoleUser MessageRole = "user" // MessageRoleAssistant represents an assistant message MessageRoleAssistant MessageRole = "assistant" // MessageRoleSystem represents a system message MessageRoleSystem MessageRole = "system" // MessageRoleTool represents a tool response message MessageRoleTool MessageRole = "tool" )
type MultiTurnImageEditor ¶ added in v0.2.36
type MultiTurnImageEditor interface {
// CreateImageEditSession creates a new multi-turn image editing session
CreateImageEditSession(ctx context.Context, options *ImageEditSessionOptions) (ImageEditSession, error)
// SupportsMultiTurnImageEditing returns true if this provider supports multi-turn editing
SupportsMultiTurnImageEditing() bool
}
MultiTurnImageEditor is an interface for LLM providers that support multi-turn conversational image editing sessions.
type ParameterSpec ¶
type ParameterSpec struct {
// Type is the data type of the parameter (string, number, boolean, etc.) or union of types e.g. ["array", "null"]
Type any
// Description describes what the parameter is for
Description string
// Required indicates if the parameter is required
Required bool
// Default is the default value for the parameter
Default interface{}
// Enum is a list of possible values for the parameter
Enum []interface{}
// Items is the type of the items in the parameter
Items *ParameterSpec
}
ParameterSpec defines the specification for a tool parameter
type Part ¶ added in v0.2.84
type Part struct {
// Text is plain text.
Text string `json:"text,omitempty"`
// InlineData is data sent with the request.
InlineData *Blob `json:"inlineData,omitempty"`
// FileData is data the provider fetches from a URI.
FileData *FileData `json:"fileData,omitempty"`
}
Part is one piece of a Content. Exactly one field is set.
The MIME type of inline or file data says what the data is, for example "image/png" or "application/pdf", so new kinds of media need no new fields.
func NewPartFromBytes ¶ added in v0.2.84
NewPartFromBytes returns a part that sends data inline, for example an image read from disk.
func NewPartFromText ¶ added in v0.2.84
NewPartFromText returns a text part.
func NewPartFromURI ¶ added in v0.2.84
NewPartFromURI returns a part that points at data by URI, for example an image URL.
func RequestMedia ¶ added in v0.2.84
func RequestMedia(ctx context.Context, options *GenerateOptions) ([]*Part, error)
RequestMedia returns every part of a request that is not text, in conversation order. With memory set, those are the parts of user messages in memory. Without memory, they are the parts set with WithParts.
func (*Part) HasMIMEType ¶ added in v0.2.84
HasMIMEType reports whether the part's MIME type is one of types.
func (*Part) IsImage ¶ added in v0.2.84
IsImage reports whether the part is inline or file data with an image MIME type.
func (*Part) IsPDF ¶ added in v0.2.84
IsPDF reports whether the part is inline or file data with the PDF MIME type.
type PropertySchema ¶ added in v0.2.28
type PropertySchema struct {
// Name is the property name
Name string `json:"name"`
// Type is the data type: "string", "number", "boolean", "datetime"
Type string `json:"type"`
// Required indicates whether the property is required
Required bool `json:"required"`
// Description describes the property
Description string `json:"description"`
// Default is the default value (optional)
Default interface{} `json:"default,omitempty"`
}
PropertySchema defines a property in the schema
type QueryOption ¶
type QueryOption func(*QueryOptions)
QueryOption represents an option for querying documents
func QueryWithLimit ¶
func QueryWithLimit(limit int) QueryOption
QueryWithLimit sets the maximum number of documents to return
func QueryWithOffset ¶
func QueryWithOffset(offset int) QueryOption
QueryWithOffset sets the number of documents to skip
func QueryWithOrderBy ¶
func QueryWithOrderBy(field string, direction string) QueryOption
QueryWithOrderBy sets the field to order by and the direction
type QueryOptions ¶
type QueryOptions struct {
// Limit is the maximum number of documents to return
Limit int
// Offset is the number of documents to skip
Offset int
// OrderBy specifies the field to order by
OrderBy string
// OrderDirection specifies the order direction (asc or desc)
OrderDirection string
}
QueryOptions contains options for querying documents
type Relationship ¶ added in v0.2.28
type Relationship struct {
// ID is the unique identifier for the relationship
ID string `json:"id"`
// SourceID is the ID of the source entity
SourceID string `json:"source_id"`
// TargetID is the ID of the target entity
TargetID string `json:"target_id"`
// Type describes the relationship (e.g., "WORKS_ON", "MANAGES", "LOCATED_IN")
Type string `json:"type"`
// Description provides context about the relationship
Description string `json:"description"`
// Strength indicates the relationship strength (0.0 to 1.0, default 1.0)
Strength float32 `json:"strength"`
// Properties contains additional attributes
Properties map[string]interface{} `json:"properties,omitempty"`
// OrgID is the organization ID for multi-tenancy
OrgID string `json:"org_id,omitempty"`
// CreatedAt is the creation timestamp
CreatedAt time.Time `json:"created_at"`
}
Relationship represents an edge connecting two entities
type RelationshipDirection ¶ added in v0.2.28
type RelationshipDirection string
RelationshipDirection specifies the direction for relationship queries
const ( // DirectionOutgoing returns relationships where the entity is the source DirectionOutgoing RelationshipDirection = "outgoing" // DirectionIncoming returns relationships where the entity is the target DirectionIncoming RelationshipDirection = "incoming" // DirectionBoth returns relationships in both directions DirectionBoth RelationshipDirection = "both" )
type RelationshipTypeSchema ¶ added in v0.2.28
type RelationshipTypeSchema struct {
// Name is the relationship type name (e.g., "WORKS_ON")
Name string `json:"name"`
// Description describes the relationship type
Description string `json:"description"`
// SourceTypes are the allowed source entity types
SourceTypes []string `json:"source_types,omitempty"`
// TargetTypes are the allowed target entity types
TargetTypes []string `json:"target_types,omitempty"`
// Properties defines the expected properties
Properties []PropertySchema `json:"properties,omitempty"`
}
RelationshipTypeSchema defines a relationship type in the schema
type ResponseFormat ¶ added in v0.0.4
type ResponseFormat struct {
Type ResponseFormatType
Name string // The name of the struct/object to be returned
Schema JSONSchema // JSON schema representation of the struct
}
ResponseFormat defines the format of the response from the LLM
type ResponseFormatType ¶ added in v0.0.4
type ResponseFormatType string
const ( ResponseFormatJSON ResponseFormatType = "json_object" ResponseFormatText ResponseFormatType = "text" )
type RetryPolicy ¶ added in v0.0.2
type RetryPolicy struct {
// MaxRetries is the maximum number of retries
MaxRetries int
// InitialBackoff is the initial backoff duration
InitialBackoff time.Duration
// MaxBackoff is the maximum backoff duration
MaxBackoff time.Duration
// BackoffMultiplier is the multiplier for backoff duration after each retry
BackoffMultiplier float64
}
RetryPolicy defines how tasks should be retried
type SearchOption ¶
type SearchOption func(*SearchOptions)
SearchOption represents an option for searching documents
func WithEmbedding ¶
func WithEmbedding(useEmbedding bool) SearchOption
WithEmbedding sets whether to use embedding for the search
func WithFields ¶ added in v0.0.24
func WithFields(fields ...string) SearchOption
WithFields sets the specific fields to retrieve in search results
func WithFilters ¶
func WithFilters(filters map[string]interface{}) SearchOption
WithFilters sets metadata filters
func WithKeyword ¶
func WithKeyword(useKeyword bool) SearchOption
WithKeyword sets whether to use keyword search
func WithMinScore ¶
func WithMinScore(score float32) SearchOption
WithMinScore sets the minimum similarity score
func WithNearText ¶
func WithNearText(useNearText bool) SearchOption
WithNearText sets whether to use nearText search
func WithTenantSearch ¶ added in v0.0.24
func WithTenantSearch(tenant string) SearchOption
WithTenantSearch sets the tenant for native multi-tenancy search operations
type SearchOptions ¶
type SearchOptions struct {
// MinScore is the minimum similarity score (0-1)
MinScore float32
// Filters are metadata filters to apply to the search
Filters map[string]interface{}
// Class is the class/collection name to search in
Class string
// UseEmbedding indicates whether to use embedding for the search
UseEmbedding bool
// UseBM25 indicates whether to use BM25 search instead of vector search
UseBM25 bool
// UseNearText indicates whether to use nearText search
UseNearText bool
// UseKeyword indicates whether to use keyword search
UseKeyword bool
// Tenant is the tenant name for native multi-tenancy
Tenant string
// Fields specifies which fields to retrieve. If empty, all fields will be retrieved dynamically
Fields []string
}
SearchOptions contains options for searching documents
type SearchResult ¶
type SearchResult struct {
// Document is the found document
Document Document
// Score is the similarity score (0-1, higher is more similar)
Score float32
}
SearchResult represents a document found in a search
type Span ¶
type Span interface {
// End ends the span
End()
// AddEvent adds an event to the span
AddEvent(name string, attributes map[string]interface{})
// SetAttribute sets an attribute on the span
SetAttribute(key string, value interface{})
RecordError(err error)
}
Span represents a span in a trace
type StoreOption ¶
type StoreOption func(*StoreOptions)
StoreOption represents an option for storing documents
func WithBatchSize ¶
func WithBatchSize(size int) StoreOption
WithBatchSize sets the batch size for storing documents
func WithGenerateVectors ¶
func WithGenerateVectors(generate bool) StoreOption
WithGenerateVectors sets whether to generate vectors
func WithTenant ¶ added in v0.0.24
func WithTenant(tenant string) StoreOption
WithTenant sets the tenant for native multi-tenancy operations
type StoreOptions ¶
type StoreOptions struct {
// BatchSize is the number of documents to store in each batch
BatchSize int
// GenerateVectors indicates whether to generate vectors for documents
GenerateVectors bool
// Class is the class/collection name to store documents in
Class string
// Tenant is the tenant name for native multi-tenancy
Tenant string
}
StoreOptions contains options for storing documents
type StreamConfig ¶ added in v0.0.34
type StreamConfig struct {
// BufferSize determines the channel buffer size
BufferSize int
// IncludeThinking whether to include thinking events
IncludeThinking bool
// IncludeToolProgress whether to include tool execution progress
IncludeToolProgress bool
// IncludeIntermediateMessages whether to include intermediate messages between tool iterations
IncludeIntermediateMessages bool
}
StreamConfig contains configuration for streaming behavior
func DefaultStreamConfig ¶ added in v0.0.34
func DefaultStreamConfig() StreamConfig
DefaultStreamConfig returns default streaming configuration
type StreamEvent ¶ added in v0.0.34
type StreamEvent struct {
Type StreamEventType `json:"type"`
Content string `json:"content,omitempty"`
ToolCall *ToolCall `json:"tool_call,omitempty"`
Error error `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
StreamEvent represents a single event in a stream
type StreamEventType ¶ added in v0.0.34
type StreamEventType string
StreamEventType represents the type of streaming event
const ( // Core streaming events StreamEventMessageStart StreamEventType = "message_start" StreamEventContentDelta StreamEventType = "content_delta" StreamEventContentComplete StreamEventType = "content_complete" StreamEventMessageStop StreamEventType = "message_stop" StreamEventError StreamEventType = "error" // Tool-related events StreamEventToolUse StreamEventType = "tool_use" StreamEventToolResult StreamEventType = "tool_result" // Thinking/reasoning events StreamEventThinking StreamEventType = "thinking" )
type StreamForwarder ¶ added in v0.2.3
type StreamForwarder func(event AgentStreamEvent)
StreamForwarder is a function that forwards stream events to a parent stream This is used to enable nested streaming from sub-agents to parent agents
type StreamingAgent ¶ added in v0.0.34
type StreamingAgent interface {
// RunStream executes the agent with streaming response
RunStream(ctx context.Context, input string) (<-chan AgentStreamEvent, error)
}
StreamingAgent represents an agent with streaming capabilities
type StreamingLLM ¶ added in v0.0.34
type StreamingLLM interface {
LLM
// GenerateStream generates text with streaming response
GenerateStream(ctx context.Context, prompt string, options ...GenerateOption) (<-chan StreamEvent, error)
// GenerateWithToolsStream generates text with tools and streaming response
GenerateWithToolsStream(ctx context.Context, prompt string, tools []Tool, options ...GenerateOption) (<-chan StreamEvent, error)
}
StreamingLLM extends LLM with streaming capabilities
type TaskExecutor
deprecated
added in
v0.0.2
type TaskExecutor interface {
// ExecuteSync executes a task synchronously
ExecuteSync(ctx context.Context, taskName string, params interface{}, opts *TaskOptions) (*TaskResult, error)
// ExecuteAsync executes a task asynchronously and returns a channel for the result
ExecuteAsync(ctx context.Context, taskName string, params interface{}, opts *TaskOptions) (<-chan *TaskResult, error)
// ExecuteWorkflow initiates a temporal workflow
ExecuteWorkflow(ctx context.Context, workflowName string, params interface{}, opts *TaskOptions) (*TaskResult, error)
// ExecuteWorkflowAsync initiates a temporal workflow asynchronously
ExecuteWorkflowAsync(ctx context.Context, workflowName string, params interface{}, opts *TaskOptions) (<-chan *TaskResult, error)
// CancelTask cancels a running task
CancelTask(ctx context.Context, taskID string) error
// GetTaskStatus gets the status of a task
GetTaskStatus(ctx context.Context, taskID string) (string, error)
// ExecuteStep executes a single step in a task's plan
ExecuteStep(ctx context.Context, task interface{}, step interface{}) error
// ExecuteTask executes all steps in a task's plan
ExecuteTask(ctx context.Context, task interface{}) error
}
TaskExecutor is the interface for executing tasks.
Deprecated: this interface has no satisfying implementation anywhere in the SDK and cannot usefully be implemented as written. *task/executor.TaskExecutor, the only executor shipped, does not satisfy it (it has no CancelTask, GetTaskStatus, ExecuteWorkflow or ExecuteWorkflowAsync, and its ExecuteStep / ExecuteTask take concrete *core.Task and *core.Step rather than interface{}). As a result NewInMemoryTaskService, which accepts a TaskExecutor, cannot be constructed with anything this module provides.
The ExecuteWorkflow and ExecuteWorkflowAsync methods reference a Temporal integration that does not exist; Temporal is not a dependency of this module.
This interface will be removed in a future minor release. Depend on the concrete *task/executor.TaskExecutor, or define an interface in your own package containing only the methods you use.
type TaskOptions ¶ added in v0.0.2
type TaskOptions struct {
// Timeout specifies the maximum duration for task execution
Timeout *time.Duration
// RetryPolicy specifies the retry policy for the task
RetryPolicy *RetryPolicy
// Metadata contains additional information for the task execution
Metadata map[string]interface{}
}
TaskOptions represents options for task execution
type TaskPlanner ¶ added in v0.0.3
type TaskPlanner interface {
// CreatePlan creates a plan for a task
CreatePlan(ctx context.Context, task interface{}) (string, error)
}
TaskPlanner defines the interface for planning a task
type TaskResult ¶ added in v0.0.2
type TaskResult struct {
// Data contains the result data
Data interface{}
// Error contains any error that occurred during task execution
Error error
// Metadata contains additional information about the task execution
Metadata map[string]interface{}
}
TaskResult represents the result of a task execution
type TaskService ¶ added in v0.0.3
type TaskService interface {
// CreateTask creates a new task
CreateTask(ctx context.Context, req interface{}) (interface{}, error)
// GetTask gets a task by ID
GetTask(ctx context.Context, taskID string) (interface{}, error)
// ListTasks returns tasks filtered by the provided criteria
ListTasks(ctx context.Context, filter interface{}) ([]interface{}, error)
// ApproveTaskPlan approves or rejects a task plan
ApproveTaskPlan(ctx context.Context, taskID string, req interface{}) (interface{}, error)
// UpdateTask updates an existing task with new steps or modifications
UpdateTask(ctx context.Context, taskID string, updates interface{}) (interface{}, error)
// AddTaskLog adds a log entry to a task
AddTaskLog(ctx context.Context, taskID string, message string, level string) error
}
TaskService defines the interface for task management This is a unified interface combining task and core.Service
type TokenUsage ¶ added in v0.1.13
type TokenUsage struct {
// InputTokens is the number of tokens in the input/prompt
InputTokens int
// OutputTokens is the number of tokens in the generated response
OutputTokens int
// TotalTokens is the total number of tokens used (input + output)
TotalTokens int
// ReasoningTokens is the number of tokens used for reasoning (optional, for models that support it)
ReasoningTokens int
// CacheCreationInputTokens is the number of tokens written to cache (Anthropic only)
CacheCreationInputTokens int
// CacheReadInputTokens is the number of tokens read from cache (Anthropic only)
CacheReadInputTokens int
}
TokenUsage represents token usage information for an LLM request
type Tool ¶
type Tool interface {
// Name returns the name of the tool
Name() string
// Description returns a description of what the tool does
Description() string
// Run executes the tool with the given input
Run(ctx context.Context, input string) (string, error)
// Parameters returns the parameters that the tool accepts
Parameters() map[string]ParameterSpec
// Execute executes the tool with the given arguments
Execute(ctx context.Context, args string) (string, error)
}
Tool represents a tool that can be used by an agent
type ToolCall ¶ added in v0.0.30
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
Internal bool `json:"internal,omitempty"`
Arguments string `json:"arguments"`
ThoughtSignature []byte `json:"thought_signature,omitempty"`
}
ToolCall represents a tool call made by the assistant
type ToolCallEvent ¶ added in v0.0.34
type ToolCallEvent struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
Internal bool `json:"internal,omitempty"`
Arguments string `json:"arguments,omitempty"`
Result string `json:"result,omitempty"`
Status string `json:"status"` // "starting", "executing", "completed", "error"
}
ToolCallEvent represents a tool call in streaming context
type ToolRegistry ¶
type ToolRegistry interface {
// Register registers a tool with the registry
Register(tool Tool)
// Get returns a tool by name
Get(name string) (Tool, bool)
// List returns all registered tools
List() []Tool
}
ToolRegistry is a registry of available tools
type ToolWithDisplayName ¶ added in v0.0.53
type ToolWithDisplayName interface {
// DisplayName returns a human-friendly name for the tool
DisplayName() string
}
ToolWithDisplayName is an optional interface that tools can implement to provide a human-friendly display name
type Tracer ¶
type Tracer interface {
// StartSpan starts a new span and returns a new context containing the span
StartSpan(ctx context.Context, name string) (context.Context, Span)
// StartTraceSession starts a root trace session for a request with the given contextID
// This creates a root span that will group all subsequent operations under the same trace
StartTraceSession(ctx context.Context, contextID string) (context.Context, Span)
}
Tracer represents a tracing system for observability
type Transaction ¶
type Transaction interface {
// Collection returns a reference to a specific collection/table within the transaction
Collection(name string) CollectionRef
// Commit commits the transaction
Commit() error
// Rollback rolls back the transaction
Rollback() error
}
Transaction represents a database transaction
type VectorStore ¶
type VectorStore interface {
Store(ctx context.Context, documents []Document, options ...StoreOption) error
Get(ctx context.Context, id string, options ...StoreOption) (*Document, error)
Search(ctx context.Context, query string, limit int, options ...SearchOption) ([]SearchResult, error)
SearchByVector(ctx context.Context, vector []float32, limit int, options ...SearchOption) ([]SearchResult, error)
Delete(ctx context.Context, ids []string, options ...DeleteOption) error
// Global operations for shared data (no tenant context)
GlobalStore(ctx context.Context, documents []Document, options ...StoreOption) error
GlobalSearch(ctx context.Context, query string, limit int, options ...SearchOption) ([]SearchResult, error)
GlobalSearchByVector(ctx context.Context, vector []float32, limit int, options ...SearchOption) ([]SearchResult, error)
GlobalDelete(ctx context.Context, ids []string, options ...DeleteOption) error
// Tenant management for native multi-tenancy
CreateTenant(ctx context.Context, tenantName string) error
DeleteTenant(ctx context.Context, tenantName string) error
ListTenants(ctx context.Context) ([]string, error)
}
VectorStore interface defines operations for vector storage and retrieval
type VectorStoreConfig ¶
type VectorStoreConfig struct {
// Host is the hostname of the vector store server
Host string
// APIKey is the authentication key for the vector store
APIKey string
// Scheme is the URL scheme (http or https)
Scheme string
// ClassPrefix is the default prefix for class/collection names
ClassPrefix string
// DistanceMetric is the similarity metric to use (e.g., "cosine", "euclidean", "dot")
DistanceMetric string
}
VectorStoreConfig contains configuration for vector stores