Documentation
¶
Index ¶
- Constants
- Variables
- func BuildMultimodalContent(textContent string, imageInputs []string) (interface{}, error)
- func CheckImageFormat(ref string, data []byte) error
- func GatewayKeyFor(rawURL string) string
- func GatewayKeyForRemote(remoteURL string) string
- func GatewayKeyFromEnv() string
- func IsPrivateVertexHost(host string) bool
- func IsVertexEndpointURL(rawURL string) bool
- func NormalizeSchemaSamples(schemaContent string) string
- func NormalizeVertexEndpointURL(rawURL string) string
- func ProbabilityEntropy(probs map[string]float64) float64
- func ServerKeyFromEnv() string
- func StripKeysOnCrossOriginRedirect(req *http.Request, via []*http.Request) error
- type ChatChoice
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatMessage
- type ChoiceLogprobs
- type Client
- func (c *Client) Complete(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, *RequestStats, error)
- func (c *Client) Decide(ctx context.Context, schemaContent, userStateContent string, images ...string) (*StructuredDecisionResponse, *RequestStats, error)
- func (c *Client) WithAuthToken(token string) *Client
- type ContentPart
- type Diagnostics
- type HTTPError
- type ImageURLPart
- type ProposedOption
- type QuestionAnswer
- type QuestionDiagnostic
- type RequestStats
- type SamplePolicy
- type SampleStats
- type StructuredDecisionResponse
- type TaxonomyExpansionSuggestion
- type Temperature
- type ThoughtDiagnostic
- type TimingStats
- type TokenLogprob
- type TopLogprobItem
- type Usage
Constants ¶
const GatewayKeyHeader = "X-DGem-Api-Key"
GatewayKeyHeader carries a caller's API key for a `dgem serve` gateway started with --api-keys.
const GatewayURLEnv = "DGEM_GATEWAY_URL"
GatewayURLEnv names the environment variable holding the URL of the gateway that DGEM_GATEWAY_KEY belongs to. Clients send the key only to requests with that URL's scheme, host and port.
const PrivateVertexHostSuffix = ".prediction.p.vertexai.goog"
PrivateVertexHostSuffix is the host suffix of a Vertex private (Private Service Connect) endpoint, e.g. <ID>-<REGION>-<PROJECT_NUMBER>.prediction.p.vertexai.goog. It resolves only inside the VPC (private DNS); port 443 serves a self-signed certificate, so callers inside the VPC may use plain http on port 80.
const ServerKeyHeader = "X-DGem-Key"
ServerKeyHeader is the header carrying the serving image's service-to-service secret.
Variables ¶
var ErrImageFetch = errors.New("image URL")
ErrImageFetch marks an image URL that couldn't be fetched or isn't an image (the caller's input).
var ErrUnsupportedImageFormat = errors.New("unsupported image format")
ErrUnsupportedImageFormat marks an image the serving image can't decode. vLLM loads images with PIL, which reads raster formats (PNG, JPEG, WebP, GIF) but not SVG: an SVG came back as HTTP 502 "cannot identify image file" (#117).
var ImageHTTPClient = func(timeout time.Duration) *http.Client { return &http.Client{Timeout: timeout} }
ImageHTTPClient returns the HTTP client used to fetch image URLs. The default is a plain client (the CLI fetches from the caller's own network). Network servers (`dgem serve`, `dgem systemone serve`) replace it with a client that only connects to public addresses, since there the URL comes from a request.
var SendGatewayKey = true
SendGatewayKey controls whether clients send DGEM_GATEWAY_KEY as GatewayKeyHeader. The gateway itself turns it off, so its calls to the serving image never carry a caller key.
Functions ¶
func BuildMultimodalContent ¶
BuildMultimodalContent formats user message content with optional image parts. If images are provided, it encodes local files to base64 data URIs and places image parts BEFORE the text content, conforming to DiffusionGemma best practices.
func CheckImageFormat ¶
CheckImageFormat rejects image references the serving image can't decode: local .svg files (or files whose content is SVG) and data:image/svg+xml URIs. http(s) URLs aren't fetched here, so they pass. data maybe nil; when given (a local file's bytes) its content is sniffed too.
func GatewayKeyFor ¶
GatewayKeyFor returns the gateway API key to send with a request to rawURL: GatewayKeyFromEnv when rawURL has the scheme, host and port of DGEM_GATEWAY_URL, "" otherwise. Without DGEM_GATEWAY_URL the key is never sent, so a key meant for one gateway doesn't reach Vertex AI, Cloud Run or any other URL the CLI is pointed at.
func GatewayKeyForRemote ¶
GatewayKeyForRemote is GatewayKeyFor for a URL the user named as their gateway (`dgem mcp --remote`): without DGEM_GATEWAY_URL, that URL is the gateway.
func GatewayKeyFromEnv ¶
func GatewayKeyFromEnv() string
GatewayKeyFromEnv returns the API key a caller sends to a gateway: DGEM_GATEWAY_KEY (first entry of a list). Whether a request gets it is decided by GatewayKeyFor or GatewayKeyForRemote.
func IsPrivateVertexHost ¶
IsPrivateVertexHost reports whether host (no scheme or port) is a Vertex private (PSC) endpoint host.
func IsVertexEndpointURL ¶
IsVertexEndpointURL returns true if rawURL targets a Google Cloud Vertex AI Online Prediction Endpoint (either a Dedicated Endpoint *.prediction.vertexai.goog with /invoke/* custom routes or *.aiplatform.googleapis.com).
func NormalizeSchemaSamples ¶
NormalizeSchemaSamples turns a digit-string "samples" value (template variables such as `-v samples=4` render as strings) into a JSON number. Servers built on the upstream structured server reject "4" with `samples must be a positive count or "auto"`. Any other content is returned unchanged.
func NormalizeVertexEndpointURL ¶
NormalizeVertexEndpointURL normalizes a Vertex AI Endpoint URL:
- For Dedicated Endpoints using arbitrary custom routes (invokeRoutePrefix="/*"), routes to .../invoke/v1/chat/completions (which Vertex forwards as /v1/chat/completions to structured_server.py).
- For standard regional endpoints (aiplatform.googleapis.com without /invoke), routes to :rawPredict.
- A URL that already ends in :rawPredict (regional, or a private/PSC dedicated endpoint) is kept unchanged.
func ProbabilityEntropy ¶
ProbabilityEntropy returns the Shannon entropy H = -sum p ln p (nats) of a label distribution, renormalized so a distribution that doesn't sum exactly to 1 still gives H in [0, ln K].
func ServerKeyFromEnv ¶
func ServerKeyFromEnv() string
ServerKeyFromEnv returns the key a caller sends: DGEM_SERVER_KEY, or its first entry when it holds a comma-separated rotation list (servers accept every listed key; callers send one).
func StripKeysOnCrossOriginRedirect ¶
StripKeysOnCrossOriginRedirect is the CheckRedirect policy of clients that send dgem keys. It follows up to 10 redirects, as the default policy does. Once a redirect leaves the origin of the first request, it removes GatewayKeyHeader and ServerKeyHeader from that request and every later one, including a redirect back to the first origin. Go's client drops Authorization and cookies on redirects to another domain, but copies other headers from the first request to every redirect target.
Types ¶
type ChatChoice ¶
type ChatChoice struct {
Index int `json:"index"`
Message ChatMessage `json:"message"`
FinishReason string `json:"finish_reason"`
Logprobs *ChoiceLogprobs `json:"logprobs,omitempty"`
}
ChatChoice contains the assistant message and optional token logprobs.
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
Model string `json:"model,omitempty"`
Messages []ChatMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
Stream bool `json:"stream,omitempty"`
Logprobs bool `json:"logprobs,omitempty"`
TopLogprobs int `json:"top_logprobs,omitempty"`
}
ChatCompletionRequest is the OpenAI-compatible payload format.
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatChoice `json:"choices"`
Usage Usage `json:"usage"`
}
ChatCompletionResponse is the standard OpenAI-compatible response.
type ChatMessage ¶
type ChatMessage struct {
Role string `json:"role"`
Content interface{} `json:"content"`
}
ChatMessage represents a single chat turn.
func (ChatMessage) RawContent ¶
func (m ChatMessage) RawContent() string
RawContent returns the content as a string regardless of whether it was deserialized as string or map.
type ChoiceLogprobs ¶
type ChoiceLogprobs struct {
Content []TokenLogprob `json:"content"`
}
ChoiceLogprobs holds OpenAI/vLLM token-level log-probabilities.
type Client ¶
type Client struct {
BaseURL string
HTTPClient *http.Client
Model string
AuthToken string
// MaxRetries is the number of retries for HTTP 429/503 responses (0 = no retry). Retries use
// exponential backoff with jitter and are reported in RequestStats.Retries.
MaxRetries int
// ServerKey is sent as X-DGem-Key, the serving image's service-to-service secret (DGEM_SERVER_KEY on the
// server). Empty sends no header. NewClient fills it from the DGEM_SERVER_KEY environment variable.
ServerKey string
}
Client communicates with the local or remote diffgemma server.
func (*Client) Complete ¶
func (c *Client) Complete(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, *RequestStats, error)
Complete executes an OpenAI-compatible chat completion (or Vertex AI /invoke/v1/chat/completions or :rawPredict request).
func (*Client) Decide ¶
func (c *Client) Decide(ctx context.Context, schemaContent, userStateContent string, images ...string) (*StructuredDecisionResponse, *RequestStats, error)
Decide executes a discrete diffusion slot readout decision query with optional multimodal images.
func (*Client) WithAuthToken ¶
WithAuthToken sets the Authorization Bearer / IAM token.
type ContentPart ¶
type ContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL *ImageURLPart `json:"image_url,omitempty"`
}
ContentPart represents an element in a multimodal content array.
type Diagnostics ¶
type Diagnostics struct {
Hole string `json:"hole,omitempty"`
Steps int `json:"steps"`
Layout string `json:"layout,omitempty"` // prompt layout the server used (serving v0.2.0+)
Thought *ThoughtDiagnostic `json:"thought,omitempty"`
Timing TimingStats `json:"timing"`
Samples SampleStats `json:"samples"`
Questions map[string]QuestionDiagnostic `json:"questions"`
}
Diagnostics contains server-side timing, sampling, thought channel, and slot entropy data.
type HTTPError ¶
type HTTPError struct {
StatusCode int
Body string
Retries int
// Hint, when set, tells the user how to fix the request (for example a gateway key that wasn't sent).
Hint string
}
HTTPError is returned for non-2xx responses so callers can record the status code.
type ImageURLPart ¶
type ImageURLPart struct {
URL string `json:"url"`
}
ImageURLPart holds an image URL or base64 data URI.
type ProposedOption ¶
ProposedOption represents a ready-to-paste {"name", "description"} choice option for a .json.tmpl policy.
type QuestionAnswer ¶
type QuestionAnswer struct {
Type string `json:"type"`
Label string `json:"label"`
Confidence float64 `json:"confidence"`
Logprob float64 `json:"logprob,omitempty"`
Entropy float64 `json:"entropy,omitempty"`
Stderr float64 `json:"stderr"`
Agreement float64 `json:"agreement"`
Probabilities map[string]float64 `json:"probabilities"`
// Type-specific values:
Choice string `json:"choice,omitempty"` // For choice type
Score float64 `json:"score,omitempty"` // For score type
Level string `json:"level,omitempty"` // For score type
Noul float64 `json:"noul,omitempty"` // For boolean/noul type (probability of true/yes)
// Optional prior-fusion and co-denoised evidence telemetry:
PriorLogits map[string]float64 `json:"prior_logits,omitempty"`
PriorFused bool `json:"prior_fused,omitempty"`
RawEntropy float64 `json:"raw_entropy,omitempty"`
Evidence string `json:"evidence,omitempty"`
}
QuestionAnswer holds the evaluated result for a single question.
func (QuestionAnswer) DisplayType ¶
func (qa QuestionAnswer) DisplayType() string
DisplayType returns a human-friendly type name, replacing "noul" with "boolean".
func (QuestionAnswer) DisplayValue ¶
func (qa QuestionAnswer) DisplayValue() string
DisplayValue returns the primary value (e.g. "yes", "engineering", "2 (frustrated)").
type QuestionDiagnostic ¶
type QuestionDiagnostic struct {
ArgmaxIsLabel bool `json:"argmax_is_label"`
ArgmaxToken string `json:"argmax_token"`
Entropy float64 `json:"entropy"`
LabelMass float64 `json:"label_mass"`
Logprobs map[string]float64 `json:"logprobs,omitempty"`
}
QuestionDiagnostic holds raw token entropy, pre-softmax option logprobs, and probability mass.
func (*QuestionDiagnostic) UnmarshalJSON ¶
func (qd *QuestionDiagnostic) UnmarshalJSON(data []byte) error
type RequestStats ¶
type RequestStats struct {
Model string
Endpoint string
WallTime time.Duration
PrefillMs float64
DenoiseMs float64
PromptTokens int
ReusedTokens int
OutputTokens int
TotalTokens int
DenoiseSteps int
SamplesN int
Extended bool
Retries int
Diagnostics *Diagnostics
}
RequestStats summarizes the full lifecycle of a query for CLI display.
type SamplePolicy ¶
type SamplePolicy struct {
Extended bool `json:"extended"`
FirstReadMaxEntropy float64 `json:"first_read_max_entropy"`
Max int `json:"max"`
Mode string `json:"mode"`
PinnedSlots int `json:"pinned_slots"`
Threshold float64 `json:"threshold"`
}
SamplePolicy reveals whether the auto-sampling threshold was triggered.
func (*SamplePolicy) UnmarshalJSON ¶
func (sp *SamplePolicy) UnmarshalJSON(data []byte) error
type SampleStats ¶
type SampleStats struct {
N int `json:"n"`
Policy SamplePolicy `json:"policy"`
}
SampleStats details the multi-read sampling policy.
func (*SampleStats) UnmarshalJSON ¶
func (ss *SampleStats) UnmarshalJSON(data []byte) error
type StructuredDecisionResponse ¶
type StructuredDecisionResponse struct {
Answers map[string]QuestionAnswer `json:"answers"`
Diagnostics Diagnostics `json:"diagnostics"`
SuggestedExpansions []TaxonomyExpansionSuggestion `json:"suggested_expansions,omitempty"`
}
StructuredDecisionResponse represents the parsed structured-decision content.
func ParseStructuredContent ¶
func ParseStructuredContent(content string) (*StructuredDecisionResponse, error)
ParseStructuredContent attempts to unmarshal the raw assistant text as a StructuredDecisionResponse.
func ParseStructuredContentWithLogprobs ¶
func ParseStructuredContentWithLogprobs(content string, logprobs *ChoiceLogprobs) (*StructuredDecisionResponse, error)
ParseStructuredContentWithLogprobs unmarshals the assistant text and enriches slot confidence, top-k candidate probabilities, and Shannon entropy using OpenAI/vLLM token logprobs when present.
func (*StructuredDecisionResponse) ApplyTemperature ¶
func (r *StructuredDecisionResponse) ApplyTemperature(t Temperature)
ApplyTemperature rescales each answer's probabilities by p_k^(1/T) (renormalised) and recomputes confidence, entropy, the yes probability (noul) and the expected score, reading lossless pre-softmax log-probabilities from Diagnostics.Questions[id].Logprobs when present so answers saturated near 1.0 in float64 retain exact precision. The argmax answer does not change.
type TaxonomyExpansionSuggestion ¶
type TaxonomyExpansionSuggestion struct {
QuestionID string `json:"question_id"`
TriggerReason string `json:"trigger_reason"`
Stage1Choice string `json:"stage1_choice"`
Stage1Confidence float64 `json:"stage1_confidence"`
Stage1Entropy float64 `json:"stage1_entropy"`
TopCandidates map[string]float64 `json:"top_candidates,omitempty"`
InjectedCatchAll bool `json:"injected_catch_all"`
SuggestedOption ProposedOption `json:"suggested_option"`
RawThought string `json:"raw_thought,omitempty"`
TemplatePatchHint string `json:"template_patch_hint,omitempty"`
}
TaxonomyExpansionSuggestion records an unclassified/high-entropy slot detection and DiffusionGemma's proposed new class.
type Temperature ¶
Temperature is a post-hoc temperature for a policy's answers: one value for every question, or one per question type ("noul", "choice", "score"; an absent type keeps T = 1). JSON accepts a number or an object, e.g. "temperature": 1.4 or "temperature": {"noul": 3.0, "choice": 1.3}. A single served default doesn't transfer across domains, so fit it on a labelled sample of your own decisions (docs/confidence/calibrate-your-policy.md).
func ParseSchemaTemperature ¶
func ParseSchemaTemperature(schemaJSON string) (Temperature, error)
ParseSchemaTemperature reads a policy's "temperature" key from a rendered schema (absent: zero value).
func (Temperature) For ¶
func (t Temperature) For(answerType string) float64
For returns the temperature for a question type (1 when unset).
func (Temperature) IsSet ¶
func (t Temperature) IsSet() bool
IsSet reports whether any temperature other than 1 is configured.
func (Temperature) MarshalJSON ¶
func (t Temperature) MarshalJSON() ([]byte, error)
MarshalJSON writes the number form when only All is set.
func (*Temperature) UnmarshalJSON ¶
func (t *Temperature) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts a number or a {type: T} object.
func (Temperature) Validate ¶
func (t Temperature) Validate() error
Validate checks every value is in (0, 20].
type ThoughtDiagnostic ¶
type ThoughtDiagnostic struct {
Text string `json:"text"`
Tokens int `json:"tokens"`
Ms float64 `json:"ms"`
Budget int `json:"budget,omitempty"`
}
ThoughtDiagnostic captures DiffusionGemma's optional pre-canvas thought channel output ("think": N).
type TimingStats ¶
type TimingStats struct {
TotalMs float64 `json:"total_ms"`
Reads int `json:"reads"`
DenoiseMs float64 `json:"denoise_ms"`
PrefillMs float64 `json:"prefill_ms"`
PromptTokens int `json:"prompt_tokens"`
ReusedTokens int `json:"reused_tokens"`
Rounds int `json:"rounds"`
Samples int `json:"samples"`
StepsRun int `json:"steps_run"`
}
TimingStats details execution breakdown across local Metal and vLLM remote endpoints.
type TokenLogprob ¶
type TokenLogprob struct {
Token string `json:"token"`
Logprob float64 `json:"logprob"`
TopLogprobs []TopLogprobItem `json:"top_logprobs,omitempty"`
}
TokenLogprob represents the log-probability and top-k alternatives for a single output token.
type TopLogprobItem ¶
TopLogprobItem represents a single candidate token and its logprob at a given position.