Skip to content

feat(py): add OpenAICompatible for any OpenAI-compatible server, matching JS and Go - #258

Merged
huangjeff5 merged 1 commit into
mainfrom
feat/py-openai-compatible-plugin
Dec 1, 2026
Merged

huangjeff5 merged 1 commit into
mainfrom
feat/py-openai-compatible-plugin

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Stack (merge in order): #257 (Anthropic(backend=GoogleCloud())) → #258 (OpenAICompatible) → #259 (OpenAICompatible(backend=GoogleCloud())) → #260 (deprecate genkit-vertexai)

OpenAICompatible(name=..., base_url=..., api_key=...) connects any OpenAI-compatible server (OpenRouter, Together, Groq, vLLM, LiteLLM, local servers) under a caller-chosen namespace. This matches JS's openAICompatible({ name, baseURL, apiKey }) and Go's compat_oai.OpenAICompatible{Provider, BaseURL, APIKey}.

Previously, OpenAI(base_url=...) was the only way to hit these servers, and its OpenAI-specific assumptions broke non-OpenAI endpoints:

  • the Dev UI listed 42 OpenAI models that don't exist on the target server;
  • OpenAI.gpt('openai/gpt-4o') stripped both prefixes and sent gpt-4o to OpenRouter;
  • OpenAI-specific filters dropped valid models (e.g., google/gemini-2.5-pro matched the -pro filter);
  • servers without /models broke Dev UI model listing;
  • only one server could be registered per app because everything shared the openai/ namespace.
from genkit import Genkit
from genkit_openai import OpenAI, OpenAICompatible

# 1. Name the server; its models register as openrouter/<id>
openrouter = OpenAICompatible(name='openrouter', base_url='https://openrouter.ai/api/v1', api_key=key)

# 2. Run it beside OpenAI's own API
ai = Genkit(plugins=[OpenAI(), openrouter])

# 3. Model IDs are forwarded verbatim
res = await ai.generate(model=openrouter.model('openai/gpt-4o'), prompt='Name a bakery.')
print(res.text)
# => Rise & Shine Bakehouse

# 4. A local server that needs no key; OPENAI_API_KEY is never read
local = OpenAICompatible(name='local', base_url='http://localhost:8000/v1')

Changes

  • New OpenAICompatible plugin: Requires name and base_url, registering models and embedders under <name>/<id>.
    • name rejects /, :, whitespace, and control characters; base_url rejects empty or blank strings.
    • Model IDs are sent verbatim with no prefix stripping or name-based kind inference; ai.generate resolves chat models and ai.embed resolves embedders.
    • Multiple OpenAICompatible instances can run alongside each other and OpenAI().
    • instance.model(name, config=...) returns a typed OpenAIConfig ref (e.g. openrouter.model('meta-llama/...')) and never strips <name>/ (so provider-prefixed IDs like openrouter/auto stay intact).
  • Model capabilities (_COMPATIBLE_SUPPORTS): Declares multiturn, media, tools, tool_choice, system_role, output=['json', 'text'], and constrained=None so Dev UI capability checks work without assuming native JSON Schema support.
  • Dynamic /models listing: init() registers nothing. Dev UI listing queries /models, deduplicates IDs in server order, classifies IDs containing embed (case-insensitive) as embedders and the rest as chat models, and logs a warning returning [] (without caching the failure) on missing /models, HTTP errors, or malformed HTTP 200 payloads.
  • Auth and credential isolation: api_key accepts a string, an async callable (awaited before each request for expiring tokens), or None (sends a placeholder for keyless local servers; invalid types raise TypeError).
    • Never reads ambient OPENAI_API_KEY (including client_options={'api_key': None}), OPENAI_ORG_ID, or OPENAI_PROJECT_ID.
    • Per-request context.secrets overrides the plugin key and strips OpenAI-Organization/OpenAI-Project headers on tenant calls; refused with FAILED_PRECONDITION if Authorization is pinned in default_headers.
  • Shared embedding path: Extracted embedding logic into a shared embed_texts helper used by both OpenAI and OpenAICompatible (preserving Mistral's output_dimension handling on Mistral hosts).
  • Dependency bump: Raised openai floor from >=1.99.2 to >=1.106.0, the first version whose api_key accepts an async callable.
  • README: Adds an "Any OpenAI-compatible server" section and narrows OpenAI(base_url=...) docs to proxies/gateways in front of OpenAI.

Decisions

  • Separate OpenAICompatible class instead of overloading OpenAI: OpenAI carries OpenAI's static catalog, name-based routing to image/TTS/STT endpoints, and OpenAI-specific filters. Adding passthrough mode there would require branching around base_url throughout the plugin. A dedicated class keeps the passthrough path clean and aligns with JS and Go.
  • Required name and base_url for generic servers: Requiring name avoids openai/ namespace collisions and openai/openai/... ambiguity; requiring base_url prevents accidentally routing to OpenAI's API. Neither field falls back to environment variables. (In feat(py): serve Model Garden's OpenAI-compatible models via OpenAICompatible(backend=GoogleCloud()) #259, backend=GoogleCloud() supplies its own endpoint and defaults name to 'modelgarden', so both become optional when a backend is passed.)
  • Chat and embeddings only: Image, TTS, and STT endpoints have OpenAI-specific request shapes that most compatible servers don't implement.

Verification

  • Unit tests: packages/genkit-openai + tests/version_bounds_guard_test.py — 1,098 passed.
  • Static & repo checks: ruff, ty, pyrefly (0 errors), scripts/check_consistency.py, uv lock --check, and addlicense -check all pass (pyright runs in CI).

Breaking changes

None to the API. Installs now need openai>=1.106.0. OpenAI(base_url=...) behaves the same; only its docs changed.

Follow-up

#259 (OpenAICompatible(backend=GoogleCloud(...))) and #260 (deprecate genkit-vertexai) stack on top of this PR.

@pavelgj pavelgj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@huangjeff5
huangjeff5 force-pushed the feat/py-openai-compatible-plugin branch from 1049d38 to 4ccad82 Compare December 1, 2026 21:20
Base automatically changed from feat/py-anthropic-google-cloud to main December 1, 2026 21:37
…hing JS and Go

OpenAICompatible(name=..., base_url=..., api_key=...) registers a server's
models and embedders as <name>/<id> and sends <id> as written. No built-in
catalog or OpenAI-only filters; the Dev UI lists /models and survives a server
without it. api_key takes a string, an async function, or None (never reads
OPENAI_API_KEY). OpenAI and OpenAICompatible share one embed helper. The
openai floor moves to 1.106.0, the first release with async api_key.
@huangjeff5
huangjeff5 force-pushed the feat/py-openai-compatible-plugin branch from 4ccad82 to b65f990 Compare December 1, 2026 21:37
@huangjeff5
huangjeff5 enabled stacked auto-merge (squash) December 1, 2026 21:52
@huangjeff5
huangjeff5 merged commit 9dba01f into main Dec 1, 2026
21 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-openai-compatible-plugin branch December 1, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants