Documentation
¶
Overview ¶
Package langdag provides a Go library for managing AI agent conversations with tree-structured storage and multi-provider LLM routing.
Index ¶
- Constants
- Variables
- type APIProtocolV1
- type AnthropicConfig
- type AzureOpenAIConfig
- type BedrockConfig
- type CapabilitySetV1
- type CapabilityState
- type CatalogDiagnosticV1
- type CatalogLoadOptions
- type CatalogLoadResult
- type CatalogRefreshOptions
- type CatalogRefreshResult
- type CatalogSource
- type CatalogV1
- type Client
- func (c *Client) Close() error
- func (c *Client) DeleteNode(ctx context.Context, id string) error
- func (c *Client) GetAncestors(ctx context.Context, id string) ([]*types.Node, error)
- func (c *Client) GetNode(ctx context.Context, id string) (*types.Node, error)
- func (c *Client) GetSubtree(ctx context.Context, id string) ([]*types.Node, error)
- func (c *Client) ListConversations(ctx context.Context) ([]*types.Node, error)
- func (c *Client) Prompt(ctx context.Context, message string, opts ...PromptOption) (*PromptResult, error)
- func (c *Client) PromptFrom(ctx context.Context, nodeID string, message string, opts ...PromptOption) (*PromptResult, error)
- func (c *Client) Provider() Provider
- func (c *Client) Storage() Storage
- type CompiledCatalogV1
- type Config
- type CredentialV1
- type DeploymentBindingV1
- type DeploymentChoice
- type DeploymentConfig
- type DeploymentV1
- type EnvFallbackV1
- type GeminiConfig
- type GrokConfig
- type ModelCatalog
- type ModelOfferingTemplateV1
- type ModelOfferingV1
- type ModelPricing
- type ModelV1
- type NativeModelIDSource
- type OllamaConfig
- type OpenAIConfig
- type OpenRouterConfig
- type PricingStatus
- type PricingV1
- type PromptOption
- func WithAPIProtocol(apiProtocolID string) PromptOption
- func WithMaxOutputGroupTokens(n int) PromptOption
- func WithMaxTokens(n int) PromptOption
- func WithMaxTurns(n int) PromptOption
- func WithModel(model string) PromptOption
- func WithSystemPrompt(prompt string) PromptOption
- func WithThink(enabled bool) PromptOption
- func WithTools(tools []types.ToolDefinition) PromptOption
- type PromptResult
- type ProvenanceV1
- type Provider
- type ProviderV1
- type RemoteModelCatalogConfig
- type ResponseCostSource
- type RetryConfig
- type RetryEvent
- type RoutingEntry
- type RoutingPolicy
- type RoutingStage
- type Storage
- type StreamChunk
- type VertexConfig
Constants ¶
const CapabilitySupported = models.CapabilitySupported
const CapabilityUnknown = models.CapabilityUnknown
const CapabilityUnsupported = models.CapabilityUnsupported
const CatalogSourceCache = models.CatalogSourceCache
const CatalogSourceEmbedded = models.CatalogSourceEmbedded
const CatalogSourceRemote = models.CatalogSourceRemote
const CatalogV1JSONSchema = models.CatalogV1JSONSchema
const CatalogV1SchemaVersion = models.CatalogV1SchemaVersion
const DefaultRemoteCatalogURL = models.DefaultRemoteCatalogURL
const NativeModelIDCatalogKnown = models.NativeModelIDCatalogKnown
const NativeModelIDCatalogOrUser = models.NativeModelIDCatalogOrUser
const NativeModelIDDiscovered = models.NativeModelIDDiscovered
const NativeModelIDUserConfigured = models.NativeModelIDUserConfigured
const PricingFree = models.PricingFree
const PricingKnown = models.PricingKnown
const PricingPartial = models.PricingPartial
const PricingUnknown = models.PricingUnknown
const ResponseCostLocalFree = models.ResponseCostLocalFree
const ResponseCostProviderAsync = models.ResponseCostProviderAsync
const ResponseCostProviderExact = models.ResponseCostProviderExact
const ResponseCostUsageCountersOnly = models.ResponseCostUsageCountersOnly
Variables ¶
var CatalogRefreshOptionsFromEnv = models.CatalogRefreshOptionsFromEnv
var CompileCatalogV1 = models.CompileCatalogV1
var ContextWithRetryCallback = internalprovider.ContextWithRetryCallback
ContextWithRetryCallback returns a child context that carries a per-call retry callback. This takes priority over the config-level OnRetry.
var DeploymentBindingsV1 = models.DeploymentBindingsV1
var ParseCatalogV1 = models.ParseCatalogV1
var ParseRemoteCatalogV1 = models.ParseRemoteCatalogV1
var ReferenceCatalogV1 = models.ReferenceCatalogV1
var SplitOfferingIDV1 = models.SplitOfferingIDV1
var ValidateCatalogV1 = models.ValidateCatalogV1
Functions ¶
This section is empty.
Types ¶
type APIProtocolV1 ¶ added in v0.9.0
type APIProtocolV1 = models.APIProtocolV1
type AnthropicConfig ¶
type AnthropicConfig struct {
BaseURL string
}
AnthropicConfig holds Anthropic-specific configuration.
type AzureOpenAIConfig ¶
AzureOpenAIConfig holds Azure OpenAI-specific configuration.
type BedrockConfig ¶
type BedrockConfig struct {
Region string
}
BedrockConfig holds AWS Bedrock configuration.
type CapabilitySetV1 ¶ added in v0.9.0
type CapabilitySetV1 = models.CapabilitySetV1
type CapabilityState ¶ added in v0.9.0
type CapabilityState = models.CapabilityState
type CatalogDiagnosticV1 ¶ added in v0.9.0
type CatalogDiagnosticV1 = models.CatalogDiagnosticV1
type CatalogLoadOptions ¶ added in v0.9.0
type CatalogLoadOptions = models.CatalogLoadOptions
type CatalogLoadResult ¶ added in v0.9.0
type CatalogLoadResult = models.CatalogLoadResult
func LoadModelCatalogWithOptions ¶ added in v0.9.0
func LoadModelCatalogWithOptions(opts CatalogLoadOptions) (*CatalogLoadResult, error)
LoadModelCatalogWithOptions loads a usable model catalog immediately, preferring a valid cache and falling back to embedded catalog data with diagnostics.
func LoadRuntimeModelCatalog ¶ added in v0.9.0
func LoadRuntimeModelCatalog() (*CatalogLoadResult, error)
LoadRuntimeModelCatalog loads the model catalog used by prompt/runtime routing from the embedded catalog generated from the published model-catalog branch.
func LoadRuntimeModelCatalogWithOptions ¶ added in v0.9.0
func LoadRuntimeModelCatalogWithOptions(opts CatalogLoadOptions) (*CatalogLoadResult, error)
LoadRuntimeModelCatalogWithOptions loads the prompt/runtime catalog with explicit load options. If opts.CachePath is empty, the embedded catalog is used and no user cache path is read implicitly.
type CatalogRefreshOptions ¶ added in v0.9.0
type CatalogRefreshOptions = models.CatalogRefreshOptions
type CatalogRefreshResult ¶ added in v0.9.0
type CatalogRefreshResult = models.CatalogRefreshResult
func LoadRemoteModelCatalog ¶ added in v0.9.0
func LoadRemoteModelCatalog(ctx context.Context, opts CatalogRefreshOptions) (*CatalogRefreshResult, error)
LoadRemoteModelCatalog fetches the published remote model catalog and validates it without reading or writing any local cache file.
func RefreshModelCatalogCache ¶ added in v0.9.0
func RefreshModelCatalogCache(ctx context.Context, opts CatalogRefreshOptions) (*CatalogRefreshResult, error)
RefreshModelCatalogCache fetches the published remote catalog artifact. If opts.CachePath is non-empty, the fetched catalog replaces that cache. Invalid, stale, or partial remote data does not replace an existing cache.
type CatalogSource ¶ added in v0.9.0
type CatalogSource = models.CatalogSource
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main langdag client for managing AI conversations.
A Client is safe for concurrent use by multiple goroutines. The underlying storage (SQLite with WAL mode and busy_timeout) and providers (stateless HTTP clients) are themselves concurrent-safe, and each call to Prompt or PromptFrom returns an independent PromptResult with its own streaming channel.
func NewWithDeps ¶
NewWithDeps creates a Client from pre-built dependencies. Useful for testing or custom integrations where the caller has already constructed a Storage and Provider.
func (*Client) DeleteNode ¶
DeleteNode deletes a node and all its descendants.
func (*Client) GetAncestors ¶
GetAncestors returns all ancestors of a node (the conversation history leading to it).
func (*Client) GetSubtree ¶
GetSubtree returns a node and all its descendants.
func (*Client) ListConversations ¶
ListConversations returns all root conversation nodes.
func (*Client) Prompt ¶
func (c *Client) Prompt(ctx context.Context, message string, opts ...PromptOption) (*PromptResult, error)
Prompt starts a new conversation with the given message. Returns a PromptResult with the streaming response.
func (*Client) PromptFrom ¶
func (c *Client) PromptFrom(ctx context.Context, nodeID string, message string, opts ...PromptOption) (*PromptResult, error)
PromptFrom continues a conversation from an existing node.
type CompiledCatalogV1 ¶ added in v0.9.0
type CompiledCatalogV1 = models.CompiledCatalogV1
type Config ¶
type Config struct {
// StoragePath is the path to the SQLite database file.
// Defaults to "$HOME/.config/langdag/langdag.db"
StoragePath string
// Provider is the default LLM provider to use.
// Valid values: "anthropic", "openai", "gemini", "grok", "openrouter", "ollama",
// "anthropic-vertex", "anthropic-bedrock", "openai-azure", "gemini-vertex"
// "gemma" is accepted as an alias for "gemini".
// Defaults to "anthropic"
Provider string
// APIKeys maps provider names to their API keys.
// Keys: "anthropic", "openai", "gemini"
APIKeys map[string]string
// AnthropicConfig holds Anthropic-specific config (optional base URL override).
AnthropicConfig *AnthropicConfig
// OpenAIConfig holds OpenAI-specific config.
OpenAIConfig *OpenAIConfig
// GeminiConfig holds Gemini-specific config.
GeminiConfig *GeminiConfig
// GrokConfig holds Grok (xAI)-specific config.
GrokConfig *GrokConfig
// OpenRouterConfig holds OpenRouter-specific config.
OpenRouterConfig *OpenRouterConfig
// AzureOpenAIConfig holds Azure OpenAI-specific config.
AzureOpenAIConfig *AzureOpenAIConfig
// VertexConfig holds Google Vertex AI config.
VertexConfig *VertexConfig
// BedrockConfig holds AWS Bedrock config.
BedrockConfig *BedrockConfig
// OllamaConfig holds Ollama-specific config (local LLM server).
OllamaConfig *OllamaConfig
// ModelCatalog is the deployment-aware catalog used for canonical model
// resolution. Defaults to the embedded catalog generated from the published
// model-catalog branch when nil. Mutually exclusive with RemoteModelCatalog.
ModelCatalog *ModelCatalog
// RemoteModelCatalog, when non-nil, makes New fetch the published catalog
// instead of using the embedded catalog. Fetch failures are returned from
// New; no local cache file is read or written. Mutually exclusive with
// ModelCatalog.
RemoteModelCatalog *RemoteModelCatalogConfig
// Deployments configures routeable deployment credentials and deployment-
// scoped model mappings. Legacy provider-specific fields above remain
// readable and are merged into this shape.
Deployments map[string]DeploymentConfig
// RoutingPolicy configures canonical-model deployment routing. Exact model
// routes override matching provider routes. Non-matching models use
// automatic eligible deployment resolution unless Default is explicitly set.
RoutingPolicy *RoutingPolicy
// Routing configures multi-provider routing (optional).
// Deprecated: use RoutingPolicy with deployment IDs.
Routing []RoutingEntry
// FallbackOrder specifies provider fallback order (optional).
// Deprecated: use RoutingPolicy with deployment IDs.
FallbackOrder []string
// RetryConfig configures retry behavior.
RetryConfig *RetryConfig
}
Config holds all configuration for the langdag client.
type CredentialV1 ¶ added in v0.9.0
type CredentialV1 = models.CredentialV1
type DeploymentBindingV1 ¶ added in v0.9.0
type DeploymentBindingV1 = models.DeploymentBindingV1
type DeploymentChoice ¶ added in v0.9.0
type DeploymentChoice = internalprovider.DeploymentChoice
type DeploymentConfig ¶ added in v0.9.0
type DeploymentConfig struct {
APIKey string
BaseURL string
Endpoint string
APIVersion string
ProjectID string
Region string
ModelMappings map[string]string
}
DeploymentConfig holds deployment-scoped credentials and native model mappings. Azure OpenAI uses ModelMappings to translate canonical model IDs to the caller's Azure deployment names.
type DeploymentV1 ¶ added in v0.9.0
type DeploymentV1 = models.DeploymentV1
type EnvFallbackV1 ¶ added in v0.9.0
type EnvFallbackV1 = models.EnvFallbackV1
type GeminiConfig ¶
type GeminiConfig struct {
BaseURL string
}
GeminiConfig holds Gemini-specific configuration.
type GrokConfig ¶ added in v0.2.0
type GrokConfig struct {
BaseURL string
}
GrokConfig holds Grok (xAI)-specific configuration.
type ModelCatalog ¶ added in v0.3.0
ModelCatalog contains deployment-aware model, offering, pricing, and capability information.
func DefaultModelCatalog ¶ added in v0.3.0
func DefaultModelCatalog() (*ModelCatalog, error)
DefaultModelCatalog returns the model catalog embedded with the library. It contains model names, pricing (per 1M tokens), context window sizes, and max output tokens for all supported providers.
func FetchModelCatalog ¶ added in v0.3.0
func FetchModelCatalog(ctx context.Context, cachePath string) (*ModelCatalog, error)
FetchModelCatalog fetches the latest model catalog from official provider documentation pages (OpenAI, Anthropic, Google, xAI). This does not require any API keys.
If cachePath is non-empty, the fetched catalog is saved to that path so it can be loaded with LoadModelCatalog in future sessions.
func LoadModelCatalog ¶ added in v0.3.0
func LoadModelCatalog(cachePath string) (*ModelCatalog, error)
LoadModelCatalog loads the model catalog from a cache file, falling back to the embedded default if the file does not exist or is invalid JSON.
type ModelOfferingTemplateV1 ¶ added in v0.9.0
type ModelOfferingTemplateV1 = models.ModelOfferingTemplateV1
type ModelOfferingV1 ¶ added in v0.9.0
type ModelOfferingV1 = models.ModelOfferingV1
type ModelPricing ¶ added in v0.3.0
type ModelPricing = models.ModelPricing
ModelPricing contains pricing and capability information for a model.
type NativeModelIDSource ¶ added in v0.9.0
type NativeModelIDSource = models.NativeModelIDSource
type OllamaConfig ¶ added in v0.6.1
type OllamaConfig struct {
// BaseURL is the Ollama server address (e.g., "http://localhost:11434" or "http://100.93.184.1:11434")
BaseURL string
}
OllamaConfig holds Ollama-specific configuration. Ollama is a local LLM server that provides an OpenAI-compatible API.
type OpenAIConfig ¶
type OpenAIConfig struct {
BaseURL string
}
OpenAIConfig holds OpenAI-specific configuration.
type OpenRouterConfig ¶ added in v0.9.0
type OpenRouterConfig struct {
BaseURL string
}
OpenRouterConfig holds OpenRouter-specific configuration.
type PricingStatus ¶ added in v0.9.0
type PricingStatus = models.PricingStatus
type PromptOption ¶
type PromptOption func(*promptOptions)
PromptOption configures a prompt request.
func WithAPIProtocol ¶ added in v0.9.0
func WithAPIProtocol(apiProtocolID string) PromptOption
WithAPIProtocol selects a provider API surface for providers that expose multiple protocols for the same deployment, for example "openai-responses" or "openai-chat-completions".
func WithMaxOutputGroupTokens ¶ added in v0.7.0
func WithMaxOutputGroupTokens(n int) PromptOption
WithMaxOutputGroupTokens sets the maximum total output tokens across all continuation calls in an output group. When a response hits max_tokens and is continued, langdag tracks cumulative output tokens; if they exceed this budget the continuation stops. A value of 0 (the default) means 4× the per-call max_tokens.
func WithMaxTokens ¶
func WithMaxTokens(n int) PromptOption
WithMaxTokens sets the max tokens for the response.
func WithMaxTurns ¶ added in v0.3.0
func WithMaxTurns(n int) PromptOption
WithMaxTurns sets the maximum number of LLM round-trips for a single Prompt/PromptFrom call. Since langdag does not have a built-in tool-use loop, the value is exposed on the PromptResult so the caller can decrement and check it in their own multi-turn loop. A value of 0 (the default) means unlimited.
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) PromptOption
WithSystemPrompt sets the system prompt.
func WithThink ¶ added in v0.6.4
func WithThink(enabled bool) PromptOption
WithThink controls whether the model should use extended thinking. true = enable thinking, false = disable thinking. Omitting this option leaves the decision to the provider/model default.
func WithTools ¶
func WithTools(tools []types.ToolDefinition) PromptOption
WithTools sets the tool definitions for the prompt. When tools are provided, the LLM may respond with tool_use content blocks.
type PromptResult ¶
type PromptResult struct {
// NodeID is the ID of the saved assistant node (set when streaming completes,
// or immediately for non-streaming use when the stream is consumed).
NodeID string
// Content is the full response text (empty until streaming completes).
Content string
// Stream is the streaming channel. Range over it to receive chunks.
// It is never nil; even for simple use cases, consumers should drain it.
Stream <-chan StreamChunk
// MaxTurns is the maximum number of LLM round-trips the caller should
// allow for this conversation. 0 means unlimited. Since langdag does not
// have a built-in tool-use loop, the caller can use this value to enforce
// a turn budget in their own multi-turn loop.
MaxTurns int
// contains filtered or unexported fields
}
PromptResult holds the result of a prompt call.
The NodeID and Content fields are written by a background goroutine as the stream is consumed. Reading them directly before the stream is fully drained is a data race. Use the GetNodeID and GetContent accessor methods for concurrent-safe access at any time, or read the fields only after the Stream channel has been fully drained (closed).
func (*PromptResult) GetContent ¶ added in v0.3.0
func (r *PromptResult) GetContent() string
GetContent returns the full response content in a concurrent-safe manner. The value is only meaningful after the stream has been fully drained.
func (*PromptResult) GetNodeID ¶ added in v0.3.0
func (r *PromptResult) GetNodeID() string
GetNodeID returns the node ID in a concurrent-safe manner. The value is only meaningful after the stream has delivered a Done chunk.
type ProvenanceV1 ¶ added in v0.9.0
type ProvenanceV1 = models.ProvenanceV1
type Provider ¶
type Provider = internalprovider.Provider
Provider is the interface for LLM providers. It is re-exported here so that external consumers can use the return value of Client.Provider() without importing an internal package.
func WithRetry ¶ added in v0.8.2
func WithRetry(p Provider, cfg RetryConfig) Provider
WithRetry wraps a Provider with exponential backoff retry logic. Only transient errors (5xx, rate limits, timeouts) are retried.
type ProviderV1 ¶ added in v0.9.0
type ProviderV1 = models.ProviderV1
type RemoteModelCatalogConfig ¶ added in v0.9.0
type RemoteModelCatalogConfig struct {
Endpoint string
Timeout time.Duration
HTTPClient *http.Client
}
RemoteModelCatalogConfig configures an explicit runtime fetch of the published model catalog. Leave Endpoint empty to use DefaultRemoteCatalogURL.
type ResponseCostSource ¶ added in v0.9.0
type ResponseCostSource = models.ResponseCostSource
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int
BaseDelay time.Duration
MaxDelay time.Duration
// OnRetry is called before each retry wait. It may be nil.
OnRetry func(RetryEvent)
}
RetryConfig configures retry behavior for LLM provider calls.
type RetryEvent ¶ added in v0.8.2
type RetryEvent = internalprovider.RetryEvent
RetryEvent holds information about a retry attempt.
type RoutingEntry ¶
type RoutingEntry struct {
Provider string
Weight int
Retry *RetryConfig
}
RoutingEntry configures a single provider entry in the routing table. Deprecated: use RoutingPolicy with deployment IDs.
type RoutingPolicy ¶ added in v0.9.0
type RoutingPolicy = internalprovider.RoutingPolicy
type RoutingStage ¶ added in v0.9.0
type RoutingStage = internalprovider.RoutingStage
type Storage ¶
type Storage = internalstorage.Storage
Storage is the interface for persisting conversation nodes. It is re-exported here so that external consumers can use the return value of Client.Storage() without importing an internal package.
type StreamChunk ¶
type StreamChunk struct {
// Content is the incremental text content for this chunk.
Content string
// ContentBlock is set for content_done events (e.g. tool_use blocks).
ContentBlock *types.ContentBlock
// Done indicates the stream has completed.
Done bool
// Error holds any error that occurred during streaming.
Error error
// NodeID is set when Done=true and the assistant node has been saved to storage.
NodeID string
// StopReason is the reason the LLM stopped generating (e.g. "end_turn", "tool_use").
// Set when Done=true.
StopReason string
Usage *types.Usage
ModelResolution *types.ModelResolutionMetadata
NormalizedUsage *types.NormalizedUsage
PricingSnapshot *types.PricingSnapshot
ProviderCost *types.ProviderCost
}
StreamChunk is a piece of a streaming response.
type VertexConfig ¶
VertexConfig holds Google Vertex AI configuration.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
langdag
command
Package main provides the entry point for the langdag CLI.
|
Package main provides the entry point for the langdag CLI. |
|
internal
|
|
|
api
Package api provides an HTTP API server for langdag.
|
Package api provides an HTTP API server for langdag. |
|
cli
Package cli provides the command-line interface for langdag.
|
Package cli provides the command-line interface for langdag. |
|
config
Package config handles configuration loading for langdag.
|
Package config handles configuration loading for langdag. |
|
conversation
Package conversation provides conversation management logic.
|
Package conversation provides conversation management logic. |
|
migrate/langgraph
Package langgraph provides types and tools for importing LangGraph data into langdag.
|
Package langgraph provides types and tools for importing LangGraph data into langdag. |
|
models
Package models provides a catalog of LLM model pricing and capabilities.
|
Package models provides a catalog of LLM model pricing and capabilities. |
|
provider
Package provider defines the provider interface for LLM providers.
|
Package provider defines the provider interface for LLM providers. |
|
provider/anthropic
Package anthropic provides Anthropic-protocol implementations of the provider interface.
|
Package anthropic provides Anthropic-protocol implementations of the provider interface. |
|
provider/gemini
Package gemini provides Google Gemini provider implementations.
|
Package gemini provides Google Gemini provider implementations. |
|
provider/mock
Package mock provides a mock implementation of the provider interface for testing.
|
Package mock provides a mock implementation of the provider interface for testing. |
|
provider/openai
Package openai provides OpenAI-compatible provider implementations.
|
Package openai provides OpenAI-compatible provider implementations. |
|
storage
Package storage defines the storage interface for langdag.
|
Package storage defines the storage interface for langdag. |
|
storage/sqlite
Package sqlite provides a SQLite implementation of the storage interface.
|
Package sqlite provides a SQLite implementation of the storage interface. |
|
tools
|
|
|
catalogcmp
command
|
|
|
Package types defines shared types used across the langdag codebase.
|
Package types defines shared types used across the langdag codebase. |