crossmodel

package
v1.833.375 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Cross-model API compatibility suite (#138)

One request shape, sent to every major model family over both wire formats the gateway serves — OpenAI-compatible POST /v1/chat/completions and Anthropic-compatible POST /v1/messages — with the response contract asserted on each answer:

Scenario What it asserts
openai_sync chat.completion shape, choices[0].message, a mapped finish_reason, usage token counts
openai_stream SSE layout: data: {…} chunks of chat.completion.chunk, delta.content, one terminal finish_reason, closing data: [DONE]
openai_tools tools + tool_choice: finish_reason: tool_calls, tool_calls[].{id,type,function.name}, function.arguments parses as JSON
openai_tools_parallel parallel_tool_calls: true yields two distinct calls in one turn
openai_tool_followup multi-turn role: "tool" result round-trips and the answer comes back
openai_stream_tools delta.tool_calls fragments carry an index and reassemble into complete, parseable calls
openai_json_object / openai_json_schema response_format returns parseable JSON carrying the required keys
anthropic_sync / anthropic_stream type: message, text content blocks, a mapped stop_reason, usage.input_tokens/output_tokens; the documented event sequence message_start → content_block_start → content_block_delta(text_delta) → content_block_stop → message_delta → message_stop
error envelopes {error:{message,type,param,code}} on /v1/chat/completions, {type:"error",error:{type,message}} on /v1/messages, for 401 / 4xx-invalid-input / 404-unknown-model

The matrix rows (Matrix in matrix.go) are the families named in #138. Ids are pinned from the live catalog so TestCatalog_Live — which costs no credits, since GET /v1/models is public — fails the moment a row drifts or a capability flag changes.

Running it

go test ./qa/crossmodel -count=1                    # contract checks: no network, no key
HANZO_QA_LIVE=1 go test ./qa/crossmodel -run Live   # public live lane: catalog + error envelopes, no key
HANZO_API_KEY=hzo_xxx HANZO_QA_REPORT=/tmp/matrix.json \
  go test ./qa/crossmodel -run Live -timeout 30m -v # the full matrix; writes matrix.json + matrix.md

HANZO_API_URL retargets the gateway (default https://api.hanzo.ai, staging works too); HANZO_API_KEY is the only credential needed. hanzo/zen is a free catalog model, so a full keyed run can be kept off the bill.

A CI lane looks like this (the standing gate in hanzo.yml compiles and vets, which already covers this package; the live lane is what needs a secret):

  crossmodel:
    name: Cross-model API compatibility (#138)
    runs-on: [hanzo-build-linux-amd64]
    if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
    steps:
      - uses: actions/checkout@v4
        with: {fetch-depth: 1}
      - uses: actions/setup-go@v5
        with: {go-version-file: go.mod}
      - run: HANZO_QA_LIVE=1 go test ./qa/crossmodel -run Live -count=1   # key-free public checks
      - env:
          HANZO_API_KEY: ${{ secrets.HANZO_QA_KEY }}
          HANZO_QA_REPORT: matrix.json
        run: go test ./qa/crossmodel -run Live -timeout 40m -v
      - uses: actions/upload-artifact@v4
        with: {name: compatibility-matrix, path: matrix.*}

Findings on api.hanzo.ai (2026-11-09, key-free run)

Reproduce with the HANZO_QA_LIVE=1 line above; every item below is asserted by TestPublicErrorEnvelopes_Live / TestCatalog_Live.

  1. 401 on /v1/chat/completions is not an OpenAI error envelope. Body is the console envelope {"status":"error","msg":"authentication required: …","data":null,"data2":null}. The official SDKs read error.message, so a first unauthenticated call dies on an undefined field instead of the actionable message. Status code (401) is correct.
  2. 401 on /v1/messages is not an Anthropic error envelope either — same console body, while Anthropic clients key off top-level type:"error" plus error.type.
  3. An unknown route 404s as text/plain; charset=utf-8, body not found — no JSON, so no client can parse it at all.
  4. Catalog capability flags are omitted when false (supports_tools, supports_vision, supports_reasoning appear only on the entries where they are true), while free and premium are always serialized. A matrix consumer cannot tell "false" from "unknown".
  5. Kai has no chat surface at all: hanzo/kai is cataloged as endpoint: /v1/decisions, outputs: ["decision"], so the identical chat payload #138 asks for cannot reach it. The matrix marks every Kai cell skip with that reason rather than pretending parity. Zen (hanzo/zen) and Enso (enso-flash) do answer /v1/chat/completions but are not flagged supports_tools, so their tool cells skip too — 511 models listed, 354 of them tool-capable.

Where the envelope fix belongs: once a request reaches a controller, both shapes are already right (controllers/anthropic_api.go anthropicErrorBody, and routers/filter_balance.go for model_not_found). The gap is the filter layer in front of it — denyUnauthorized in routers/base.go, called from routers/authz_filter.go, answers every /v1/* credential failure with the console envelope. One branch that picks the envelope by request path closes findings 1 and 2; finding 3 is the router's no-match handler.

Documentation

Overview

Package crossmodel is the cross-model API compatibility suite for #138: one request shape, sent to every major model family over both the OpenAI-compatible /v1/chat/completions and the Anthropic-compatible /v1/messages surface, with the SSE chunk layout, tool-call serialization, structured output and error-envelope contracts asserted on each response.

The live suite is env-gated (HANZO_API_KEY) so it skips in a gate that has no credential, and its contract checks run against an httptest server so CI still proves the checks themselves work. See qa/crossmodel/README.md.

Index

Constants

View Source
const (
	BaseURLEnv = "HANZO_API_URL"
	KeyEnv     = "HANZO_API_KEY"
	// ReportEnv names a path to write the matrix report to (JSON; the .md twin is
	// written beside it). Unset means no artifact.
	ReportEnv = "HANZO_QA_REPORT"
	// LivePublicEnv opts the key-free public-surface checks into real network calls.
	// They are off by default so a gate without egress stays green.
	LivePublicEnv = "HANZO_QA_LIVE"
)

BaseURLEnv and KeyEnv are the two inputs the live suite needs.

View Source
const AnthropicVersion = "2023-06-01"

AnthropicVersion is sent on /v1/messages. The gateway defaults it when absent, but a compatibility suite should not rely on a default it did not ask for.

View Source
const DefaultBase = "https://api.hanzo.ai"

DefaultBase is the production gateway. HANZO_API_URL may name the URL with or without the /v1 suffix (the docs print it without).

View Source
const PlainPrompt = "Name one primary color. Answer in one short sentence."

PlainPrompt is the one question every family answers on every sync/stream cell.

View Source
const RequestTimeout = 150 * time.Second

RequestTimeout bounds one model round trip. Reasoning families stream for a while before they answer, so this is generous by design; the whole suite still fails fast because every scenario runs with its own context.

Variables

View Source
var JSONKeys = []string{"name", "age", "tags"}

JSONKeys are the fields a structured-output answer must carry.

View Source
var Matrix = []Family{
	{Name: "Zen", Model: "hanzo/zen", Chat: true},
	{Name: "Enso", Model: "enso-flash", Chat: true},
	{Name: "Kai", Model: "hanzo/kai"},
	{Name: "Claude", Model: "anthropic/claude-haiku-4.5", Chat: true, Tools: true},
	{Name: "GPT", Model: "openai/gpt-4o-mini", Chat: true, Tools: true},
	{Name: "Gemini", Model: "google/gemini-2.5-flash-lite", Chat: true, Tools: true},
	{Name: "Qwen", Model: "qwen/qwen-plus", Chat: true, Tools: true},
	{Name: "DeepSeek", Model: "deepseek/deepseek-v4-flash", Chat: true, Tools: true},
	{Name: "Llama", Model: "meta-llama/llama-3.3-70b-instruct", Chat: true, Tools: true},
}

Matrix pins one representative per family named in #138. The ids are taken from the live catalog (2026-11), so a rename surfaces as a 404 model_not_found in the suite rather than drifting silently out of coverage.

Kai is listed with Chat=false on purpose: the catalog routes it to /v1/decisions, so an identical chat payload cannot reach it at all. That is a matrix finding, not a test bug — see README.md.

View Source
var Scenarios = []Scenario{
	{Name: "openai_sync", NeedsChat: true, Run: openAISync},
	{Name: "openai_stream", NeedsChat: true, Run: openAIStream},
	{Name: "openai_tools", NeedsChat: true, NeedsTools: true, Run: openAITools},
	{Name: "openai_tools_parallel", NeedsChat: true, NeedsTools: true, Run: openAIParallelTools},
	{Name: "openai_tool_followup", NeedsChat: true, NeedsTools: true, Run: openAIToolFollowUp},
	{Name: "openai_json_object", NeedsChat: true, Run: openAIJSONObject},
	{Name: "openai_json_schema", NeedsChat: true, Run: openAIJSONSchema},
	{Name: "openai_stream_tools", NeedsChat: true, NeedsTools: true, Run: openAIStreamTools},
	{Name: "anthropic_sync", NeedsChat: true, Run: anthropicSync},
	{Name: "anthropic_stream", NeedsChat: true, Run: anthropicStream},
}

Scenarios is the coverage set named in #138: sync, streaming SSE layout, tool calls (single, parallel, and the multi-turn role:"tool" follow-up), structured output in both json_object and json_schema form, on both API shapes.

Functions

func BaseURL

func BaseURL() string

BaseURL resolves the gateway root, ending in /v1.

func CheckAnthropicErrorEnvelope

func CheckAnthropicErrorEnvelope(raw []byte) []string

CheckAnthropicErrorEnvelope asserts the Anthropic error contract: {type:"error", error:{type,message}} with a documented error type.

func CheckAnthropicMessage

func CheckAnthropicMessage(raw []byte) []string

CheckAnthropicMessage asserts the sync /v1/messages contract.

func CheckAnthropicStream

func CheckAnthropicStream(frames []Frame) []string

CheckAnthropicStream asserts the Anthropic SSE contract: the documented event sequence arrives in order, every payload names its own event type, at least one text_delta carries text, and message_stop closes the stream.

func CheckJSONObjectContent

func CheckJSONObjectContent(raw []byte, requiredKeys ...string) []string

CheckJSONObjectContent asserts that the assistant message is parseable JSON: the response_format json_object / json_schema contract. requiredKeys are only checked when given (the json_schema case).

func CheckOpenAIChatCompletion

func CheckOpenAIChatCompletion(raw []byte) []string

CheckOpenAIChatCompletion asserts the sync /v1/chat/completions contract.

func CheckOpenAIErrorEnvelope

func CheckOpenAIErrorEnvelope(raw []byte) []string

CheckOpenAIErrorEnvelope asserts the OpenAI error contract: {error:{message,type, param,code}}. It also names the gateway's own {status,msg,data,data2} envelope when that is what came back, because every SDK parsing this endpoint reads error.message and nothing else.

func CheckOpenAIStream

func CheckOpenAIStream(frames []Frame) []string

CheckOpenAIStream asserts the OpenAI SSE contract over the frames that arrived: every payload is a chat.completion.chunk, at least one carries delta.content, the last data payload before the sentinel carries a valid finish_reason, and the stream ends with exactly `data: [DONE]`.

func CheckOpenAIStreamToolCalls

func CheckOpenAIStreamToolCalls(frames []Frame) []string

CheckOpenAIStreamToolCalls reassembles delta.tool_calls fragments the way a client must, and asserts the stream serializes complete, parseable calls. This is where a provider that splits arguments across chunks without an index, or emits truncated JSON, gets caught.

func CheckOpenAIToolCalls

func CheckOpenAIToolCalls(raw []byte, wantNames []string, minCalls int) []string

CheckOpenAIToolCalls asserts the sync tool-call contract: finish_reason tool_calls, and wantCount calls each with an id, type function, a name from the requested set, and arguments that serialize to a JSON object.

func WriteReport

func WriteReport(path string, cells []Cell) error

WriteReport drops the matrix as JSON at path and a markdown twin beside it, so a CI run can publish both without post-processing.

Types

type Cell

type Cell struct {
	Family   string   `json:"family"`
	Model    string   `json:"model"`
	Scenario string   `json:"scenario"`
	Status   int      `json:"status"`
	Result   string   `json:"result"` // pass | fail | skip
	Problems []string `json:"problems,omitempty"`
	Detail   string   `json:"detail,omitempty"`
}

Cell is one family x scenario outcome of the matrix.

type Client

type Client struct {
	Base string // gateway root ending in /v1
	Key  string // Bearer credential; empty means send no Authorization at all
	HTTP *http.Client
}

Client speaks both wire formats of the gateway: it posts an OpenAI-shaped body to /v1/chat/completions and an Anthropic-shaped one to /v1/messages, and reads either a JSON answer or an SSE stream. It is deliberately tiny — the suite's job is the response contract, not a full SDK.

func NewClient

func NewClient() *Client

NewClient builds a client from the environment (see BaseURL and KeyEnv).

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, body any) (*Reply, error)

Chat posts an OpenAI-shaped payload to /v1/chat/completions.

func (*Client) ChatStream

func (c *Client) ChatStream(ctx context.Context, body any) (*Reply, error)

ChatStream posts a streaming OpenAI payload with "stream": true already set by the caller.

func (*Client) Messages

func (c *Client) Messages(ctx context.Context, body any) (*Reply, error)

Messages posts an Anthropic-shaped payload to /v1/messages.

func (*Client) MessagesStream

func (c *Client) MessagesStream(ctx context.Context, body any) (*Reply, error)

MessagesStream posts a streaming Anthropic payload with "stream": true set by the caller.

func (*Client) Models

func (c *Client) Models(ctx context.Context) (*Reply, error)

Models reads the public catalog, which is the source of the capability flags the matrix skips on.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body any, hdr map[string]string) (*Reply, error)

Post sends body to base+path and returns the whole JSON answer.

func (*Client) PostStream

func (c *Client) PostStream(ctx context.Context, path string, body any, hdr map[string]string) (*Reply, error)

PostStream sends a streaming request and returns every SSE frame in order. A response that is not an event stream (an error envelope, say) comes back with its Body set and no frames, which is itself a finding the caller reports.

type Family

type Family struct {
	Name  string // report label
	Model string // id exactly as GET /v1/models lists it
	Chat  bool   // false = nothing is served on /v1/chat/completions for this id
	Tools bool   // catalog says supports_tools
}

Family is one row of the compatibility matrix: a model family #138 names, and what the gateway actually serves for it.

type Frame

type Frame struct {
	Event string
	Data  string
}

Frame is one SSE data payload, paired with the event name that preceded it when the producer sent one (Anthropic does, OpenAI does not).

type Reply

type Reply struct {
	Status      int
	ContentType string
	Body        []byte
	Frames      []Frame
}

Reply is one HTTP exchange. Body carries the whole payload for a JSON answer; Frames carries the SSE payloads in wire order for a stream, including the terminal `data: [DONE]` sentinel so its presence can be asserted.

type Scenario

type Scenario struct {
	// Name is the matrix column: openai_* rides /v1/chat/completions, anthropic_*
	// rides /v1/messages with the same question behind a different body shape.
	Name string
	// NeedsChat and NeedsTools gate the cell on what the catalog says the family
	// serves, so an unsupported capability reads as "skip" rather than "fail".
	NeedsChat  bool
	NeedsTools bool

	Run func(ctx context.Context, c *Client, f Family) (status int, detail string, problems []string)
}

Scenario is one identical request, sent to every family that can take it, on the wire format named in its id. Run returns the HTTP status it saw, a one-line detail for the report, and the contract violations — empty means the cell passes.

Jump to

Keyboard shortcuts

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