dexcost
Go

API Reference

Complete reference for every public symbol in the dexcost Go SDK, grouped by function.

Initialization

dexcost.Init()

func Init(cfg Config) error

Initialize the global SDK. Must be called before StartTask, EndTask, RecordCost, or any Wrap* function. Safe to call multiple times — only the first call takes effect.

Returns an error if the API key format is invalid, the buffer directory cannot be created, or the pricing engine fails to load.

ParameterTypeDescription
cfgConfigSDK configuration. See Configuration.

dexcost.Close()

func Close()

Stop the background sync worker, finalize idle sessions, restore http.DefaultTransport if global HTTP tracking was enabled, and release all resources. Call via defer at application shutdown.

dexcost.Flush()

func Flush()

Force an immediate synchronous push of all buffered events to the Control Layer. No-op in local-only mode or when the SDK is not initialized. Push errors are written to the standard logger.

dexcost.Tracker()

func Tracker() *core.Tracker

Return the global *core.Tracker for advanced usage. Panics if Init has not been called.

dexcost.ValidateAPIKey()

func ValidateAPIKey(key string) (string, error)

Validate API key format. Returns "live", "test", or "" for an empty key. Returns ErrInvalidAPIKey when the key does not start with dx_live_ or dx_test_.

dexcost.SetContext()

func SetContext(ctx context.Context, customerID, projectID string) context.Context

Attach customer and project attribution to ctx. Returns a derived context. Attribution flows to HTTP adapters and wrapper clients when no explicit task is present.

dexcost.SetContextWithMetadata()

func SetContextWithMetadata(ctx context.Context, customerID, projectID, agent string, metadata map[string]interface{}) context.Context

Attach customer attribution plus an agent name and arbitrary metadata to ctx.

dexcost.GetContext()

func GetContext(ctx context.Context) *core.ContextData

Return the *core.ContextData stored in ctx, or nil.

dexcost.ClearContext()

func ClearContext(ctx context.Context) context.Context

Return a context with all dexcost attribution removed.


Tasks

dexcost.StartTask()

func StartTask(ctx context.Context, taskType string, opts ...TaskOption) (context.Context, *TrackedTask)

Begin tracking a new task. Returns a derived context with the task attached and a *TrackedTask for recording costs. The parent task (if any) is linked automatically from the incoming context via parent_task_id.

ParameterTypeDescription
ctxcontext.ContextParent context. Any dexcost task or attribution already in ctx is used for parent linking and attribution inheritance.
taskTypestringIdentifier for the kind of task (e.g. "resolve_ticket").
opts...TaskOptionOptional functional options — see TaskOption values below.

Panics if Init has not been called.

dexcost.EndTask()

func EndTask(ctx context.Context, status TaskStatus) error

End the task attached to ctx. Convenience wrapper for core.GetCurrentTrackedTask(ctx).End(status). Returns errNoActiveTask if no task is found.

TrackedTask.End()

func (tt *TrackedTask) End(status TaskStatus) error

Close the task, aggregate all event costs into the task totals, and persist. Returns core.ErrTaskAlreadyEnded if called more than once.

ParameterTypeDescription
statusTaskStatusOne of dexcost.StatusPending, dexcost.StatusRunning, dexcost.StatusSuccess, dexcost.StatusFailed.

dexcost.GetCurrentTask()

func GetCurrentTask(ctx context.Context) *core.Task

Return the *core.Task currently active in ctx, or nil.

dexcost.SetCurrentTask()

func SetCurrentTask(ctx context.Context, task *core.Task) context.Context

Attach a *core.Task to ctx and return the derived context.

dexcost.LinkTrace()

func LinkTrace(ctx context.Context, provider, traceID string) error

Attach an external trace link to the active task in ctx. Returns errNoActiveTask if no task is found. The top-level convenience mirrors TrackedTask.LinkTrace.

TrackedTask.LinkTrace()

func (tt *TrackedTask) LinkTrace(provider, traceID string)

Attach an external trace link stored in tt.Task.Metadata["_trace_links"].

func (tt *TrackedTask) GetTraceLinks() []map[string]string

Return all linked traces as a slice of {"provider": ..., "trace_id": ...} maps.

TaskOption values

TaskOption is func(*taskConfig). The following constructors are available at the dexcost package level:

ConstructorDescription
WithCustomer(id string)Set customer_id on the task.
WithProject(id string)Set project_id on the task.
WithMetadata(m map[string]interface{})Attach arbitrary metadata to the task.
WithExperiment(id string)Set experiment_id on the task.
WithVariant(v string)Set the variant label on the task.

Recording costs

dexcost.RecordCost()

func RecordCost(ctx context.Context, service string, operation string, costUSD decimal.Decimal, opts ...EventOption) error

Record a non-LLM cost against the active task in ctx. Returns errNoActiveTask if no task is attached to ctx.

ParameterTypeDescription
ctxcontext.ContextContext holding the active task.
servicestringService name (e.g. "pinecone").
operationstringOperation label (e.g. "query"). Pass "" to omit.
costUSDdecimal.DecimalCost in USD.
opts...EventOptionOptional EventOption overrides.

TrackedTask.RecordCost()

func (tt *TrackedTask) RecordCost(service string, costUSD decimal.Decimal, opts ...EventOption) error

Record a non-LLM cost directly on this task. Returns core.ErrTaskAlreadyEnded if the task has already been ended.

ParameterTypeDescription
servicestringService name.
costUSDdecimal.DecimalCost in USD.
opts...EventOptionOptional EventOption overrides — see EventOption values below.

TrackedTask.RecordUsage()

func (tt *TrackedTask) RecordUsage(service string, units int) error

Look up service in the rate registry, multiply by units, and record an external_cost event. When no rate is registered the event is recorded with cost_usd=0 and cost_confidence="unknown".

ParameterTypeDescription
servicestringService name matching a registered rate.
unitsintNumber of units consumed.

TrackedTask.RecordLLMCall()

func (tt *TrackedTask) RecordLLMCall(provider, model string, inputTokens, outputTokens int, opts ...LLMCallOption) error

Record an llm_call event. When no explicit cost is supplied via WithCost, cost is auto-computed by the pricing engine from the bundled LiteLLM pricing data.

ParameterTypeDescription
providerstringProvider name (e.g. "openai").
modelstringModel identifier (e.g. "gpt-4o").
inputTokensintNumber of input tokens.
outputTokensintNumber of output tokens.
opts...LLMCallOptionOptional LLMCallOption values — see below.

TrackedTask.MarkRetry()

func (tt *TrackedTask) MarkRetry(reason string, opts ...RetryOption) error

Create a retry_marker event that increments the task's retry_count and retry_cost_usd.

ParameterTypeDescription
reasonstringWhy the retry occurred (e.g. "rate_limit", "timeout").
opts...RetryOptionOptional RetryOption values — see below.

TrackedTask.MarkNotRetry()

func (tt *TrackedTask) MarkNotRetry(eventID uuid.UUID) error

Clear the retry flag on a retry-marked event. Pass uuid.Nil to un-flag the most recent retry event for this task. No-op if no matching retry event is found.

dexcost.RecordLiteLLM()

func RecordLiteLLM(ctx context.Context, response map[string]interface{}) (Event, error)

Record an llm_call event from a LiteLLM-style response map against the active task in ctx. The map must contain "model" (string) and "usage" (map with "prompt_tokens" and "completion_tokens"). Returns errNoActiveTask if no task is active.

EventOption values

EventOption is satisfied by any type that implements applyEventConfig(*eventConfig). The following option constructors are available:

ConstructorDescription
WithEventType(t EventType)Override the event type (default EventTypeExternalCost).
WithOperation(op string)Set the operation name stored in event.Details["operation"].
WithCostConfidence(cc CostConfidence)Override the cost confidence. Also satisfies LLMCallOption.
WithPricingSource(ps PricingSource)Override the pricing source. Also satisfies LLMCallOption.
WithPricingVersion(pv string)Set the pricing version string. Also satisfies LLMCallOption.
WithDetails(d map[string]interface{})Merge arbitrary key-value pairs into event.Details. Also satisfies LLMCallOption.

LLMCallOption values

ConstructorDescription
WithCost(cost decimal.Decimal)Explicit cost in USD; skips auto-pricing.
WithCachedTokens(n int)Prompt-cache read token count (discounted rate).
WithCacheCreationTokens(n int)Anthropic prompt-cache write token count (charged at cache creation rate).
WithLatency(ms int)Response latency in milliseconds.
WithErrorType(t string)Transient error class (e.g. "rate_limit", "timeout") stored in Details["error_type"] for heuristic retry detection.

RetryOption values

ConstructorDescription
WithRetryCost(cost decimal.Decimal)Explicit cost incurred by the retry.
WithRetryOf(id uuid.UUID)UUID of the original event this retry supersedes.

Instrumentation

dexcost.WrapOpenAI()

func WrapOpenAI(inner interface{}) *clients.TrackedOpenAI

Create a TrackedOpenAI wrapper around an OpenAI-compatible client. The wrapper records one llm_call event per CreateChatCompletion call. Panics if Init has not been called.

dexcost.WrapAnthropic()

func WrapAnthropic(inner interface{}) *clients.TrackedAnthropic

Create a TrackedAnthropic wrapper. Records one llm_call event per message creation call. Panics if Init has not been called.

dexcost.WrapGemini()

func WrapGemini(inner interface{}) *clients.TrackedGemini

Create a TrackedGemini wrapper. Records one llm_call event per generation call. Panics if Init has not been called.

dexcost.WrapBedrock()

func WrapBedrock(inner interface{}) *clients.TrackedBedrock

Create a TrackedBedrock wrapper around an AWS Bedrock client. Records one llm_call event per invocation. Panics if Init has not been called.

dexcost.WrapCohere()

func WrapCohere(inner interface{}) *clients.TrackedCohere

Create a TrackedCohere wrapper. Records one llm_call event per generation call. Panics if Init has not been called.

dexcost.WrapGroq()

func WrapGroq(inner interface{}) *clients.TrackedGroq

Create a TrackedGroq wrapper. Records one llm_call event per completion call. Panics if Init has not been called.

adapters.TrackHTTP()

func TrackHTTP(client *http.Client) *http.Client

Return a new *http.Client whose Transport is wrapped with trackingTransport. The original client is not mutated.

adapters.EnableGlobalHTTPTracking() / DisableGlobalHTTPTracking()

func EnableGlobalHTTPTracking()
func DisableGlobalHTTPTracking()

Wrap / restore http.DefaultTransport for process-wide HTTP cost capture. Both functions are idempotent. dexcost.Close() calls DisableGlobalHTTPTracking automatically.

adapters.RegisterDomainRate()

func RegisterDomainRate(domain string, costUSD decimal.Decimal, per string)

Register a per-request cost for domain (host[:port]). User-registered rates take precedence over the service catalog.

adapters.StartBrowserSession() / TrackBrowser()

func StartBrowserSession(ctx context.Context, pageURL string, ratePerMinute decimal.Decimal) *BrowserSession
func TrackBrowser(ctx context.Context, pageURL string, ratePerMinute decimal.Decimal, fn func() error) error

Track wall-clock time for a browser automation session and record a compute_cost event on End(). Pass decimal.Zero for ratePerMinute to use adapters.DefaultBrowserRatePerMinute ($0.01/min). TrackBrowser always calls End(), even if fn panics or returns an error.

middleware.GinMiddleware()

func GinMiddleware(tracker *core.Tracker, taskType string, opts ...core.TaskOption) gin.HandlerFunc

Gin middleware that starts a dexcost task per request and ends it with StatusSuccess for responses below 500 or StatusFailed for 5xx responses and panics.

middleware.EchoMiddleware()

func EchoMiddleware(tracker *core.Tracker, taskType string, opts ...core.TaskOption) echo.MiddlewareFunc

Echo v4 middleware with the same lifecycle as GinMiddleware. The task ends with StatusFailed when the handler returns a non-nil error or the response status is ≥ 500.

middleware.HTTPMiddleware()

func HTTPMiddleware(tracker *core.Tracker, taskType string, opts ...core.TaskOption) func(http.Handler) http.Handler

Standard net/http middleware wrapper. middleware.HTTPMiddlewareFunc is a convenience variant for http.HandlerFunc.

integrations.NewDexcostCallbackHandler()

func NewDexcostCallbackHandler(buffer core.Buffer, engine *pricing.Engine) *DexcostCallbackHandler

Create a langchaingo callback handler that records llm_call events on HandleLLMEnd and HandleLLMGenerateContentEnd. All other callbacks.Handler methods are no-ops. Use handler.WithModel("model-name") to set a default model fallback.

clients.RecordMCPResponse()

func RecordMCPResponse(buffer core.Buffer, rates *pricing.RateRegistry, taskID uuid.UUID, info MCPCallInfo) (core.Event, error)

Record an external_cost event for an MCP tool call. Cost is resolved via the rate registry ("mcp:<tool_name>" key), then the MCPToolMap catalog mapping, then falls back to zero with confidence="unknown".

ParameterTypeDescription
buffercore.BufferStorage backend (from dexcost.Tracker().Buffer()).
rates*pricing.RateRegistryRate registry (from dexcost.Tracker().Rates()).
taskIDuuid.UUIDTask to attribute the event to.
infoMCPCallInfoTool name, server identifier, latency, and error flag.

Pricing & rates

pricing.Engine

Calculates LLM costs from model name and token counts. Loaded from the embedded model_cost_map.json at Init time.

pricing.NewEngine()

func NewEngine() (*Engine, error)

Load the embedded pricing data and return a new Engine.

Engine.GetCost()

func (e *Engine) GetCost(model string, inputTokens, outputTokens, cachedTokens, cacheCreationTokens int) CostResult

Compute the cost for an LLM call. Model resolution: exact match → provider-prefix strip → date-suffix fallback. Returns CostResult with CostConfidence="unknown" when the model is not found.

ParameterTypeDescription
modelstringModel identifier (e.g. "gpt-4o", "openai/gpt-4o").
inputTokensintTotal input tokens.
outputTokensintOutput tokens.
cachedTokensintPrompt-cache read tokens (charged at the discounted cache-read rate).
cacheCreationTokensintAnthropic prompt-cache write tokens (charged at the cache-creation rate).

Engine.SetCustomPricing()

func (e *Engine) SetCustomPricing(model string, inputPer1k, outputPer1k decimal.Decimal)

Override bundled pricing for model with custom per-1k-token rates. Custom pricing takes precedence over the bundled data.

Engine.PricingVersion()

func (e *Engine) PricingVersion() string

Return the 12-character SHA-256 hex prefix of the loaded pricing data. Changes when pricing data is refreshed.

Engine.RefreshFromServer()

func (e *Engine) RefreshFromServer(endpoint string) error

Fetch the latest pricing data from <endpoint>/v1/api/pricing-data/latest, parse it, and atomically replace the engine's model map. Existing data is unchanged on error.

Engine.StartBackgroundRefresh() / StopBackgroundRefresh()

func (e *Engine) StartBackgroundRefresh(endpoint string, interval time.Duration)
func (e *Engine) StopBackgroundRefresh()

Start/stop a goroutine that calls RefreshFromServer on every interval tick. StartBackgroundRefresh performs an initial refresh before the first tick. Idempotent.

pricing.RateRegistry

Stores per-service cost rates for non-LLM services.

pricing.NewRateRegistry()

func NewRateRegistry() *RateRegistry

Return an empty RateRegistry.

RateRegistry.Register()

func (r *RateRegistry) Register(service, per string, costUSD decimal.Decimal)

Add or update a rate for service.

RateRegistry.Get()

func (r *RateRegistry) Get(service string) *RateEntry

Return the *RateEntry for service, or nil if not found.

RateRegistry.GetAll()

func (r *RateRegistry) GetAll() map[string]RateEntry

Return a copy of all registered rates.

RateRegistry.LoadYAML()

func (r *RateRegistry) LoadYAML(path string) error

Load rates from a YAML file. Canonical format: entries nested under a top-level rates: key with per and cost_usd sub-keys. A legacy flat mapping is also accepted.

RateRegistry.ExportYAML()

func (r *RateRegistry) ExportYAML(path string) error

Export all registered rates to a YAML file in the canonical format.

RateRegistry.PricingVersion()

func (r *RateRegistry) PricingVersion() string

Return a deterministic 12-character SHA-256 hex hash of all registered rates. Changes on any Register or LoadYAML call.

pricing.ServiceCatalog

Manages the bundled 163-service pricing catalog.

pricing.NewServiceCatalog()

func NewServiceCatalog() (*ServiceCatalog, error)

Load the embedded service_prices.json and return a new ServiceCatalog.

ServiceCatalog.Lookup()

func (c *ServiceCatalog) Lookup(rawURL string) *ServiceEntry

Return the *ServiceEntry whose domains match the hostname in rawURL, or nil.

ServiceCatalog.ExtractCost()

func (c *ServiceCatalog) ExtractCost(entry *ServiceEntry, headers map[string]string, body map[string]interface{}) *CostExtractionResult

Extract cost from an HTTP response for a matched catalog entry. Returns nil when no pricing rule applies.

ServiceCatalog.RefreshFromURL()

func (c *ServiceCatalog) RefreshFromURL(url string) error

Download an updated catalog JSON from url and merge it into the existing entries.

ServiceCatalog.CatalogVersion()

func (c *ServiceCatalog) CatalogVersion() string

Return the catalog's version string.


Types

Config

type Config struct {
    APIKey                  string
    Storage                 string
    BatchSize               int
    FlushIntervalSeconds    float64
    BufferDir               string
    RedactFields            []string
    HashCustomerID          bool
    Environment             string
    TrackHTTP               bool
    ServiceCatalogURL       string
    EnableRetryHeuristics   bool
    RetryHeuristicWindow    float64
    RetryHeuristicThreshold float64
}

Global SDK configuration. See Configuration for field descriptions and defaults.

Key methods on Config:

MethodReturnsDescription
StorageMode()string"cloud" when API key is set and Storage != "local", otherwise "local".
KeyType()string"live", "test", or "".
IsSandbox()booltrue when using a dx_test_ key.
IsDev()booltrue when Environment == "development".

TrackedTask

dexcost.TrackedTask is an alias for core.TrackedTask. It wraps a Task and provides all cost-recording methods.

Field / MethodDescription
TaskThe underlying core.Task struct.
RecordCost(service string, costUSD decimal.Decimal, opts ...EventOption) errorRecord an external_cost event.
RecordUsage(service string, units int) errorCompute cost from the rate registry and record.
RecordLLMCall(provider, model string, inputTokens, outputTokens int, opts ...LLMCallOption) errorRecord an llm_call event.
MarkRetry(reason string, opts ...RetryOption) errorCreate a retry_marker event.
MarkNotRetry(eventID uuid.UUID) errorClear the retry flag on an event.
LinkTrace(provider, traceID string)Attach an external trace link.
GetTraceLinks() []map[string]stringReturn all linked traces.
End(status TaskStatus) errorFinalize and persist the task.

Task

The struct persisted to SQLite for each tracked task.

FieldTypeDescription
TaskIDuuid.UUIDUnique task identifier.
TaskTypestringKind of task (e.g. "resolve_ticket").
CustomerIDstringCustomer attribution.
ProjectIDstringProject attribution.
ExperimentIDstringExperiment identifier.
VariantstringVariant label.
ParentTaskID*uuid.UUIDSet automatically for nested tasks.
StatusTaskStatusCurrent task status.
StartedAttime.TimeUTC timestamp when the task was created.
EndedAt*time.TimeUTC timestamp when the task was closed, or nil if still running.
TotalCostUSDdecimal.DecimalSum of all event costs.
LLMCostUSDdecimal.DecimalSum of llm_call event costs.
ExternalCostUSDdecimal.DecimalSum of external_cost event costs.
ComputeCostUSDdecimal.DecimalSum of compute_cost event costs.
TotalInputTokensintAggregate input tokens across all LLM calls.
TotalOutputTokensintAggregate output tokens across all LLM calls.
TotalCachedTokensintAggregate cached tokens across all LLM calls.
RetryCountintNumber of events flagged as retries.
RetryCostUSDdecimal.DecimalSum of retry event costs.
FailureCountint1 when task status is failed, otherwise 0.
Metadatamap[string]interface{}Arbitrary metadata, including "_trace_links".

Event

The struct persisted for each individual cost event within a task.

FieldTypeDescription
EventIDuuid.UUIDUnique event identifier.
TaskIDuuid.UUIDTask this event belongs to.
EventTypeEventTypeOne of EventTypeLLMCall, EventTypeExternalCost, EventTypeComputeCost, EventTypeRetryMarker.
CostUSDdecimal.DecimalCost in USD.
CostConfidenceCostConfidenceOne of CostConfidenceExact, CostConfidenceComputed, CostConfidenceEstimated, CostConfidenceUnknown.
PricingSourcePricingSourceSource of pricing data.
PricingVersionstringHash of the pricing snapshot used.
ServiceNamestringService name for non-LLM events.
ProviderstringLLM provider name for llm_call events.
ModelstringModel identifier for llm_call events.
InputTokens*intInput tokens (LLM calls).
OutputTokens*intOutput tokens (LLM calls).
CachedTokens*intCached tokens (LLM calls).
LatencyMs*intResponse latency in milliseconds.
IsRetryboolWhether this event is flagged as a retry.
RetryReasonstringWhy the retry occurred.
RetryOf*uuid.UUIDUUID of the original event this retries.
OccurredAttime.TimeUTC timestamp of the event.
Detailsmap[string]interface{}Arbitrary extra metadata.

CostResult

type CostResult struct {
    CostUSD        decimal.Decimal
    CostConfidence string
    PricingSource  string
    PricingVersion string
}

Result of a pricing.Engine.GetCost() call.

FieldDescription
CostUSDCalculated cost in USD.
CostConfidence"computed" or "unknown".
PricingSource"litellm", "custom", or "unknown".
PricingVersionHash of the pricing data used.

RateEntry

type RateEntry struct {
    Service string
    Per     string
    CostUSD decimal.Decimal
}

A single rate entry in the RateRegistry.

TaskStatus

Type alias for core.TaskStatus. Constants re-exported at the dexcost package level:

ConstantValue
dexcost.StatusPending"pending"
dexcost.StatusRunning"running"
dexcost.StatusSuccess"success"
dexcost.StatusFailed"failed"

EventType

Type alias for core.EventType. Constants re-exported at the dexcost package level:

ConstantValue
dexcost.EventTypeLLMCall"llm_call"
dexcost.EventTypeExternalCost"external_cost"
dexcost.EventTypeComputeCost"compute_cost"
dexcost.EventTypeRetryMarker"retry_marker"

CostConfidence

Type alias for core.CostConfidence. Constants re-exported at the dexcost package level:

ConstantValue
dexcost.CostConfidenceExact"exact"
dexcost.CostConfidenceComputed"computed"
dexcost.CostConfidenceEstimated"estimated"
dexcost.CostConfidenceUnknown"unknown"

PricingSource

Type alias for core.PricingSource. Constants re-exported at the dexcost package level:

ConstantValue
dexcost.PricingSourceLiteLLM"litellm"
dexcost.PricingSourceProviderResponse"provider_response"
dexcost.PricingSourceManual"manual"
dexcost.PricingSourceCustom"custom"
dexcost.PricingSourceRateRegistry"rate_registry"
dexcost.PricingSourceUnknown"unknown"

DexcostContext

Type alias for core.ContextData. Holds attribution data stored in a context.Context by SetContext.

FieldTypeDescription
CustomerIDstringCustomer attribution.
ProjectIDstringProject attribution.
AgentstringAgent name.
Metadatamap[string]interface{}Arbitrary key-value metadata.

ErrInvalidAPIKey

var ErrInvalidAPIKey = errors.New("invalid API key format")

Returned by ValidateAPIKey when the key does not start with dx_live_ or dx_test_. Also available as dexcost.InvalidAPIKeyError.

ALL_SUPPORTED_INSTRUMENTS

var ALL_SUPPORTED_INSTRUMENTS = []string{
    "openai", "anthropic", "gemini", "bedrock", "cohere", "groq", "litellm", "langchain",
}

The full list of providers and integrations the Go SDK can instrument.

Type aliases

The following type aliases re-export internal types at the top-level dexcost package for convenience:

AliasUnderlying type
dexcost.Taskcore.Task
dexcost.Eventcore.Event
dexcost.CostTrackercore.Tracker
dexcost.PricingEnginepricing.Engine
dexcost.RateRegistrypricing.RateRegistry
dexcost.RateEntrypricing.RateEntry
dexcost.ServiceCatalogpricing.ServiceCatalog
dexcost.CostResultpricing.CostResult
dexcost.SyncWorkertransport.EventPusher
dexcost.DexcostCallbackHandlerintegrations.DexcostCallbackHandler
dexcost.EventOptioncore.EventOption
dexcost.LLMCallOptioncore.LLMCallOption
dexcost.RetryOptioncore.RetryOption

On this page

Initializationdexcost.Init()dexcost.Close()dexcost.Flush()dexcost.Tracker()dexcost.ValidateAPIKey()dexcost.SetContext()dexcost.SetContextWithMetadata()dexcost.GetContext()dexcost.ClearContext()Tasksdexcost.StartTask()dexcost.EndTask()TrackedTask.End()dexcost.GetCurrentTask()dexcost.SetCurrentTask()dexcost.LinkTrace()TrackedTask.LinkTrace()TrackedTask.GetTraceLinks()TaskOption valuesRecording costsdexcost.RecordCost()TrackedTask.RecordCost()TrackedTask.RecordUsage()TrackedTask.RecordLLMCall()TrackedTask.MarkRetry()TrackedTask.MarkNotRetry()dexcost.RecordLiteLLM()EventOption valuesLLMCallOption valuesRetryOption valuesInstrumentationdexcost.WrapOpenAI()dexcost.WrapAnthropic()dexcost.WrapGemini()dexcost.WrapBedrock()dexcost.WrapCohere()dexcost.WrapGroq()adapters.TrackHTTP()adapters.EnableGlobalHTTPTracking() / DisableGlobalHTTPTracking()adapters.RegisterDomainRate()adapters.StartBrowserSession() / TrackBrowser()middleware.GinMiddleware()middleware.EchoMiddleware()middleware.HTTPMiddleware()integrations.NewDexcostCallbackHandler()clients.RecordMCPResponse()Pricing & ratespricing.Enginepricing.NewEngine()Engine.GetCost()Engine.SetCustomPricing()Engine.PricingVersion()Engine.RefreshFromServer()Engine.StartBackgroundRefresh() / StopBackgroundRefresh()pricing.RateRegistrypricing.NewRateRegistry()RateRegistry.Register()RateRegistry.Get()RateRegistry.GetAll()RateRegistry.LoadYAML()RateRegistry.ExportYAML()RateRegistry.PricingVersion()pricing.ServiceCatalogpricing.NewServiceCatalog()ServiceCatalog.Lookup()ServiceCatalog.ExtractCost()ServiceCatalog.RefreshFromURL()ServiceCatalog.CatalogVersion()TypesConfigTrackedTaskTaskEventCostResultRateEntryTaskStatusEventTypeCostConfidencePricingSourceDexcostContextErrInvalidAPIKeyALL_SUPPORTED_INSTRUMENTSType aliases