# Technical Documentation: ogx-ai/ogx

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/ogx-ai/ogx)

### Overview (`README.md`)

<h1 align="center">OGX</h1>

<p align="center">
  <a href="https://pypi.org/project/ogx/"><img src="https://img.shields.io/pypi/v/ogx?logo=pypi" alt="PyPI Version"></a>
  <a href="https://pypi.org/project/ogx/"><img src="https://img.shields.io/pypi/dm/ogx" alt="PyPI Downloads"></a>
  <a href="https://hub.docker.com/u/ogxai"><img src="https://img.shields.io/docker/pulls/ogxai/distribution-starter?logo=docker" alt="Docker Hub Pulls"></a>
  <a href="https://github.com/ogx-ai/ogx/blob/main/LICENSE"><img src="https://img.shields.io/pypi/l/ogx.svg" alt="License"></a>
  <a href="https://discord.gg/bUYRqEvK6"><img src="https://img.shields.io/discord/1257833999603335178?color=5865F2&logo=discord&logoColor=ffffff" alt="Discord"></a>
  <a href="https://github.com/ogx-ai/ogx/actions/workflows/unit-tests.yml?query=branch%3Amain"><img src="https://github.com/ogx-ai/ogx/actions/workflows/unit-tests.yml/badge.svg?branch=main" alt="Unit Tests"></a>
  <a href="https://github.com/ogx-ai/ogx/actions/workflows/integration-tests.yml?query=branch%3Amain"><img src="https://github.com/ogx-ai/ogx/actions/workflows/integration-tests.yml/badge.svg?branch=main" alt="Integration Tests"></a>
  <a href="https://ogx-ai.github.io/docs/api-openai/conformance"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fogx-ai%2Fogx%2Fmain%2Fdocs%2Fstatic%2Fopenai-coverage.json&query=%24.summary.conformance.score&suffix=%25&label=OpenResponses%20Conformance&color=brightgreen" alt="OpenResponses Conformance"></a>
  <a href="https://deepwiki.com/ogx-ai/ogx"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
</p>

<p align="center">
  <b>English</b> · <a href="README.zh.md">简体中文</a>
</p>

[**Quick Start**](https://ogx-ai.github.io/docs/getting_started/quickstart) | [**Documentation**](https://ogx-ai.github.io/docs) | [**OpenAI API Compatibility**](https://ogx-ai.github.io/docs/api-openai) | [**Discord**](https://discord.gg/E8M7xraH8)

> [!IMPORTANT]
> **Llama Stack is now OGX.** The name changed, and so did the mission — model-agnostic, multi-SDK, production-grade. [Read the full announcement →](https://ogx-ai.github.io/blog/from-llama-stack-to-ogx)

**Open-source agentic API server for building AI applications. OpenAI-compatible. Any model, any infrastructure.**

<p align="center">
  <img src="docs/static/img/architecture-animated.svg" alt="OGX Architecture" width="100%">
</p>

OGX is a drop-in replacement for the OpenAI API that you can run anywhere — your laptop, your datacenter, or the cloud. Use any OpenAI-compatible client or agentic framework. Swap between Llama, GPT, Gemini, Mistral, or any model without changing your application code.

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="fake")
response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Hello"}],
)
```

## What you get

- **Chat Completions & Embeddings** — standard `/v1/chat/completions`, `/v1/completions`, and `/v1/embeddings` endpoints, compatible with any OpenAI client
- **Responses API** — server-side agentic orchestration with tool calling, MCP server integration, and built-in file search (RAG) in a single API call ([learn more](https://ogx-ai.github.io/docs/api-openai))
- **Vector Stores & Files** — `/v1/vector_stores` and `/v1/files` for managed document storage and search
- **Batches** — `/v1/batches` for offline batch processing
- **Skills** — `/v1alpha/skills` for managing versioned skill bundles (zip archives with SKILL.md manifests) that agents can invoke
- **[Open Responses](https://www.openresponses.org/) conformant** — the Responses API implementation passes the Open Responses conformance test suite
- **Multi-SDK support** — use the [Anthropic SDK](https://docs.anthropic.com/en/api/messages) (`/v1/messages`) or [Google GenAI SDK](https://ai.google.dev/gemini-api/docs/interactions) (`/v1alpha/interactions`) natively alongside the OpenAI API

## Use any model, use any infrastructure

OGX has a pluggable provider architecture. Develop locally with Ollama, deploy to production with vLLM, or connect to a managed service — the API stays the same.

See the [provider documentation](https://ogx-ai.github.io/docs/providers) for the full list.

## Get started

Install and run a OGX server:

```bash
# One-line install
curl -LsSf https://github.com/ogx-ai/ogx/raw/main/scripts/install.sh | bash

# Or install via uv
uv pip install ogx

# Start the server (auto-detects providers from the environment)
uv run ogx go
```

Then connect with any OpenAI, Anthropic, or Google GenAI client — [Python](https://github.com/openai/openai-python), [TypeScript](https://github.com/openai/openai-node), [curl](https://platform.openai.com/docs/api-reference), or any framework that speaks these APIs.

See the [Quick Start guide](https://ogx-ai.github.io/docs/getting_started/quickstart) for detailed setup.

## Resources

- [Documentation](https://ogx-ai.github.io/docs) — full reference
- [OpenAI API Compatibility](https://ogx-ai.github.io/docs/api-openai) — endpoint coverage and provider matrix
- [Contributing](CONTRIBUTING.md) — how to contribute

**Client SDKs:**

OGX provides official client SDKs for Python and TypeScript:

|  Language |  SDK | Package |
| :----: | :----: | :----: |
| Python |  [ogx-client-python](https://github.com/ogx-ai/ogx-client-python) | [](https://pypi.org/project/ogx_client/) |
| TypeScript   | [ogx-client-typescript](https://github.com/ogx-ai/ogx-client-typescript) | [](https://npmjs.org/package/ogx-client) |

## Community

We hold regular community calls every Thursday at 09:00 AM PST — see the [Community Event on Discord](https://discord.gg/bUYRqEvK6) for details.

[](https://www.star-history.com/#ogx-ai/ogx&Date)

Thanks to all our amazing contributors!

<a href="https://github.com/ogx-ai/ogx/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=ogx-ai/ogx" alt="OGX contributors" />
</a>

---

### Overview (`docs/README.md`)

# OGX Documentation

Here's a collection of comprehensive guides, examples, and resources for building AI applications with OGX. For the complete documentation, visit our [Github page](https://ogx-ai.github.io/docs/getting_started/quickstart).

## Render locally

From the ogx `docs/` directory, run the following commands to render the docs locally:

```bash
npm install
npm run gen-api-docs all
npm run build
npm run serve
```

You can open up the docs in your browser at <http://localhost:3000>

## File Import System

This documentation uses `remark-code-import` to import files directly from the repository, eliminating copy-paste maintenance. Files are automatically embedded during build time.

### Importing Code Files

To import Python code (or any code files) with syntax highlighting, use this syntax in `.mdx` files:

```markdown
```python file=./demo_script.py title="demo_script.py"
```

```text

This automatically imports the file content and displays it as a formatted code block with Python syntax highlighting.

**Note:** Paths are relative to the current `.mdx` file location, not the repository root.

### Importing Markdown Files as Content

For importing and rendering markdown files (like CONTRIBUTING.md), use the raw-loader approach:

```jsx
import Contributing from '!!raw-loader!../../../CONTRIBUTING.md';
import ReactMarkdown from 'react-markdown';

<ReactMarkdown>{Contributing}</ReactMarkdown>
```

**Requirements:**

- Install dependencies: `npm install --save-dev raw-loader react-markdown`

**Path Resolution:**

- For `remark-code-import`: Paths are relative to the current `.mdx` file location
- For `raw-loader`: Paths are relative to the current `.mdx` file location
- Use `../` to navigate up directories as needed

## Content

Try out OGX's capabilities through our detailed Jupyter notebooks:

- [Zero-to-Hero Guide](./zero_to_hero_guide) - Step-by-step guide for getting started with OGX
- [Migrating from Agent objects to Responses](./notebooks/responses-api-agent-migration.ipynb) - A guide to migrating from legacy OGX Agent APIs to the OpenAI-compatible Responses API

---

### Overview (`paper/README.md`)

# OGX Technical Whitepaper (LaTeX)

This directory holds `ogx.tex` (and its build artifacts `ogx.bbl`, `ogx.pdf`,
`references.bib`), a standalone, diagram-heavy technical whitepaper. **It is a
separate document from the JOSS submission**, not an alternate build of it.

- **JOSS manuscript:** [`paper.md`](https://github.com/ogx-ai/ogx/blob/5f0d8b975da04364c1687b3cf3215d25da505201/paper.md)
  and [`paper.bib`](https://github.com/ogx-ai/ogx/blob/5f0d8b975da04364c1687b3cf3215d25da505201/paper.bib)
  at commit `5f0d8b975da04364c1687b3cf3215d25da505201`, including the
  corrected portability and moderation claims, release-scoped provider
  counts, API stability wording, and bibliography corrections. These links
  identify the manuscript independently of the
  software release tag.
- **This whitepaper:** `ogx.tex`, built against `references.bib` and `ogx.bbl`
  in this directory. It shares subject matter with `paper.md` but is
  maintained independently, is not kept in lockstep with it, and is not part
  of the JOSS submission.

Both documents currently share the same title, which has caused confusion
about which one the JOSS proof corresponds to. If you're looking for the JOSS
manuscript, use the pinned links above.

## Source references

The software version for this revision, operator source reference, and revised
manuscript are identified independently:

| Component | Revision | Reference |
| --- | --- | --- |
| OGX software | `v1.0.3` | commit `5393c94b2d23a3069b3708f9ca81ad350d2deb21` |
| OGX Kubernetes Operator | `v0.10.0` | commit `7fa16532e1434bf74493ca305b1e21030914ae57` |
| Manuscript (`paper.md` / `paper.bib`) | -- | commit `5f0d8b975da04364c1687b3cf3215d25da505201` |

The operator reference is an existing tagged source snapshot. Its
[`OGXServer` API](https://github.com/ogx-ai/ogx-k8s-operator/blob/7fa16532e1434bf74493ca305b1e21030914ae57/api/v1beta1/ogxserver_types.go)
and [deployment documentation](https://github.com/ogx-ai/ogx-k8s-operator/blob/7fa16532e1434bf74493ca305b1e21030914ae57/README.md)
describe the custom resource, network policies, ConfigMap image overrides,
Kubernetes/OpenShift deployment, and multi-architecture builds discussed in
the manuscript. This citation identifies source for those features; it does
not establish the operator version used by historical deployments.

## Release scope and registry counts

The manuscript describes the cited OGX `v1.0.3` source snapshot. The
[14 September review](https://github.com/openjournals/joss-reviews/issues/11234#issuecomment-5668826998)
inspected a newer main revision. Both sets of counts can be reproduced from
their registry files:

| Source snapshot | Inference provider types | Vector I/O provider types | Distinct vector backends |
| --- | --- | --- | --- |
| `v1.0.3` (`5393c94b`) | [23](https://github.com/ogx-ai/ogx/blob/5393c94b2d23a3069b3708f9ca81ad350d2deb21/src/ogx/providers/registry/inference.py) | [13](https://github.com/ogx-ai/ogx/blob/5393c94b2d23a3069b3708f9ca81ad350d2deb21/src/ogx/providers/registry/vector_io.py) | 10 |
| Reviewed main (`27c9a81`) | [25](https://github.com/ogx-ai/ogx/blob/27c9a810758f3b97b8775462be00fa9d4e9766f0/src/ogx/providers/registry/inference.py) | [14](https://github.com/ogx-ai/ogx/blob/27c9a810758f3b97b8775462be00fa9d4e9766f0/src/ogx/providers/registry/vector_io.py) | 11 |

Provider types count distinct registered `provider_type` strings. Vector
backends count distinct names after removing the `inline::` or `remote::`
prefix. In `v1.0.3`, these names are `chromadb`, `elasticsearch`, `faiss`,
`infinispan`, `milvus`, `oci`, `pgvector`, `qdrant`, `sqlite-vec`, and
`weaviate`. ChromaDB, Milvus, and Qdrant each have inline and remote variants.
The reviewed main revision adds the `neo4j` backend.

Neither snapshot has a Safety or Shields provider protocol. Both implement
optional Responses guardrails using an external moderation endpoint. The
[`v1.0.3` configuration](https://github.com/ogx-ai/ogx/blob/5393c94b2d23a3069b3708f9ca81ad350d2deb21/src/ogx/providers/inline/responses/builtin/config.py)
exposes `moderation_endpoint`; the newer main documentation also describes
`moderation_headers`.

Interactions is experimental at `/v1alpha/interactions` in the cited release.
Containers and Skills are absent from that release and are omitted from the
manuscript. Their routes in reviewed main are `/v1alpha/containers` and
`/v1alpha/skills`, respectively.

The [reference audit](reference-audit.md) records checks of the 19 entries
without DOIs and the verified bibliography corrections.

## JOSS proof

The [JOSS proof generated on 10 September 2026 at 20:51 UTC](https://github.com/openjournals/joss-papers/blob/86bf0fe916ed4c2c753cf90221f91b78a1efb143/joss.11234/10.21105.joss.11234.pdf)
contains the shortened manuscript, revised deployment wording, OGX `v1.0.3`
source citation, versioned operator citation, and corrected SGLang reference.
Its corresponding manuscript pair is pinned at
[`7ce8d77a4faa98863529f227d874b75770b6c805`](https://github.com/ogx-ai/ogx/tree/7ce8d77a4faa98863529f227d874b75770b6c805);
those files are byte-identical to the merged source at
[`016a6079594de71b58cba2e58842126fadda2ec1`](https://github.com/ogx-ai/ogx/tree/016a6079594de71b58cba2e58842126fadda2ec1)
when the proof was requested. This identifies a source snapshot, without
claiming the bot's checkout commit. The PDF SHA-256 is
`4e076a5036c6c6efd7c97536411e58f515d35f604f6de3fecdc124af458bd99e`.

The rendered proof includes the AI disclosure on page 4, immutable OGX and
operator source references on page 5, and the corrected SGLang author list
and DOI on page 6.

That proof predates the portability, moderation, provider-count, API stability,
and bibliography corrections pinned above. After merging those updates, run
`@editorialbot generate pdf` on the
[JOSS review issue](https://github.com/openjournals/joss-reviews/issues/11234)
to generate a proof with the revised manuscript, and
record the new proof link and hash alongside its manuscript source revision. If either
manuscript file changes, update both source links and the table before
regenerating the proof.

---

### Overview (`scripts/README.md`)

# scripts

Build, codegen, and CI utility scripts.

## Directory Structure

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Common Operations

### Regenerate distribution configs

```bash
uv run python scripts/distro_codegen.py
```

### Regenerate provider registry

```bash
uv run python scripts/provider_codegen.py
```

### Run tests

```bash
./scripts/unit-tests.sh
./scripts/integration-tests.sh --stack-config starter
```

Pass `--client-version latest` to generate the Python client from
`client-sdks/openapi` and install it over the PyPI pin before running
(the CI `client-version=latest` equivalent), or `--client-version published`
to verify the `uv.lock`-resolved PyPI client is installed.

### Run the docs Quickstart

The Quickstart page renders its steps from
`docs/docs/getting_started/quickstart/steps.json`, and `quickstart_smoke.py` runs the
same steps for every supported combination of backend, server mode, and use case. To
change the Quickstart, edit `steps.json` and the Python files next to it, then run:

```bash
# Every combination, and which ones the page marks unsupported
uv run --no-project python scripts/quickstart_smoke.py --list

# The Ollama combinations, from wheels built from this checkout
uv build --wheel --out-dir dist && uv build --wheel --out-dir dist src/ogx_api
uv run --no-project python scripts/quickstart_smoke.py --wheels dist --backend ollama
```

Without `--wheels`, the server comes from the latest PyPI release. The OpenAI,
Anthropic, and "All of them" combinations need `OPENAI_API_KEY` and/or
`ANTHROPIC_API_KEY` and are skipped without them. Coding-agent combinations need
the agent CLIs on `PATH`, and Ollama needs `OLLAMA_CONTEXT_LENGTH=16384` or more.
Set `QUICKSTART_OLLAMA_CMD` when Ollama runs in a container (CI uses
`docker exec ollama ollama`).

### Manage test recordings

```bash
# Clean up orphaned recordings
uv run python scripts/cleanup_recordings.py
# Diagnose recording issues
uv run python scripts/diagnose_recordings.py
# Normalize recordings
uv run python scripts/normalize_recordings.py

# Only check model-list recordings (skips CI test collection)
uv run python scripts/cleanup_recordings.py --model-lists-only
```

`cleanup_recordings.py` also prunes model-list recordings (`models-*.json`):
files whose filename hash no longer matches the current hash function are dead
(no replay lookup can find them), and model-set digests that add nothing the
kept files of the same (directory, request hash) do not cover are redundant,
since replay unions all digests of one hash. Only model IDs referenced by the
test suites (recording requests + CI stack-config registrations) are required
to survive; every kept group still covers all of them.

### Remote test recording (via GitHub Actions)

```bash
./scripts/github/schedule-record-workflow.sh --test-subdirs "inference,agents"
```

---

### Overview (`tests/README.md`)

There are two obvious types of tests:

| Type | Location | Purpose |
|------|----------|---------|
| **Unit** | [`tests/unit/`](unit/README.md) | Fast, isolated component testing |
| **Integration** | [`tests/integration/`](integration/README.md) | End-to-end workflows with record-replay |

Both have their place. For unit tests, it is important to create minimal mocks and instead rely more on "fakes". Mocks are too brittle. In either case, tests must be very fast and reliable.

### Record-replay for integration tests

Testing AI applications end-to-end creates some challenges:

- **API costs** accumulate quickly during development and CI
- **Non-deterministic responses** make tests unreliable
- **Multiple providers** require testing the same logic across different APIs

Our solution: **Record real API responses once, replay them for fast, deterministic tests.** This is better than mocking because AI APIs have complex response structures and streaming behavior. Mocks can miss edge cases that real APIs exhibit. A single test can exercise underlying APIs in multiple complex ways making it really hard to mock.

This gives you:

- Cost control - No repeated API calls during development
- Speed - Instant test execution with cached responses
- Reliability - Consistent results regardless of external service state
- Provider coverage - Same tests work across OpenAI, Anthropic, local models, etc.

### Testing Quick Start

You can run the unit tests with:

```bash
uv run --group dev pytest -sv tests/unit/
```

For running integration tests, you must provide a few things:

- A stack config. This is a pointer to a stack. You have a few ways to point to a stack:
  - **`server:<config>`** - automatically start a server with the given config (e.g., `server:starter`). This provides one-step testing by auto-starting the server if the port is available, or reusing an existing server if already running.
  - **`server:<config>:<port>`** - same as above but with a custom port (e.g., `server:starter:8322`)
  - a URL which points to a OGX distribution server
  - a distribution name (e.g., `starter`) or a path to a `config.yaml` file
  - a comma-separated list of api=provider pairs, e.g. `inference=fireworks,responses=builtin,agents=builtin`. This is most useful for testing a single API surface.

- Any API keys you need to use should be set in the environment, or can be passed in with the --env option.

You can run the integration tests in replay mode with:

```bash
# Run all tests with existing recordings
  uv run --group dev \
  pytest -sv tests/integration/ --stack-config=starter
```

### Re-recording tests

#### Local Re-recording (Manual Setup Required)

If you want to re-record tests locally, you can do so with:

```bash
OGX_TEST_INFERENCE_MODE=record \
  uv run --group dev \
  pytest -sv tests/integration/ --stack-config=starter -k "<appropriate test name>"
```

This will record new API responses and overwrite the existing recordings.

```{warning}

You must be careful when re-recording. CI workflows assume a specific setup for running the replay-mode tests. You must re-record the tests in the same way as the CI workflows. This means
- you need Ollama running and serving some specific models.
- you are using the `starter` distribution.
```

#### Remote Re-recording (Recommended)

**For easier re-recording without local setup**, use the automated recording workflow:

```bash
# Automated: just open a PR with test changes - recordings are auto-recorded!

# Manual: record for a specific PR with specific providers
gh workflow run record-integration-tests.yml -f pr_number=1234 -f providers="gpt,azure"

# Manual: record with specific subdirs or pattern
gh workflow run record-integration-tests.yml -f pr_number=1234 -f subdirs="agents,inference"
```

This workflow:

- Runs in GitHub Actions - no local Ollama setup required
- Auto-triggers on PRs that change tests or source code
- Works from forks (auto-pushes if "Allow edits from maintainers" is enabled, otherwise uploads artifacts)
- Commits recordings back to your branch

**Supported providers:** `ollama` (auto), `gpt`, `azure`, `bedrock` (manual trigger)

### Architecture Context

The test infrastructure lives in two places:

- **Test fixtures and conftest**: `tests/integration/conftest.py` sets up the `ogx_client` fixture, which is either a real HTTP client (server mode) or an in-process library client.
- **API Recorder**: `src/ogx/testing/api_recorder.py` implements the record/replay engine. It monkey-patches `OpenAI` client methods to intercept all API calls.
- **Recording storage**: `tests/integration/recordings/` contains cached API responses organized by provider and test.
- **Recording management scripts**: `scripts/cleanup_recordings.py`, `scripts/diagnose_recordings.py`, and `scripts/normalize_recordings.py` help manage recordings.

For a complete system architecture overview, see [ARCHITECTURE.md](../ARCHITECTURE.md).

### Next Steps

- [Integration Testing Guide](integration/README.md) - Detailed usage and configuration
- [Unit Testing Guide](unit/README.md) - Fast component testing

---

### Overview (`.github/workflows/README.md`)

# OGX CI

OGX uses GitHub Actions for Continuous Integration (CI). Below is a table detailing what CI the project includes and the purpose.

| Name | File | Purpose |
| ---- | ---- | ------- |
| Backward Compatibility Check | [backward-compat.yml](backward-compat.yml) | Check backward compatibility for config.yaml files |
| Build Distribution Images | [build-distributions.yml](build-distributions.yml) | Build Distribution Images |
| Check Provider Versions | [check-provider-versions.yml](check-provider-versions.yml) | Open issues when the vLLM, Ollama, llama.cpp or TEI servers we record against have newer releases |
| CI Status | [ci-status.yml](ci-status.yml) | Aggregate CI check status |
| CodeQL Workflow Security Scan | [codeql.yml](codeql.yml) | CodeQL Workflow Security Scan |
| Commit Constraint Updates | [commit-constraint-updates.yml](commit-constraint-updates.yml) | Commit Constraint Updates |
| Commit Recordings | [commit-recordings.yml](commit-recordings.yml) | Commit Recordings |
| Dependabot constraint-dependencies | [dependabot-constraints.yml](dependabot-constraints.yml) | Update constraint-dependencies for Dependabot PR |
| Documentation Build | [docs-build.yml](docs-build.yml) | Build and validate documentation |
| File Processors Tests | [file-processors-tests.yml](file-processors-tests.yml) | Run file processors integration tests |
| Installer CI | [install-script-ci.yml](install-script-ci.yml) | Test the installation script |
| Integration Auth Tests | [integration-auth-tests.yml](integration-auth-tests.yml) | Run the integration test suite with Kubernetes authentication |
| Integration Responses, Conversations, Prompts & Vector Stores Auth Tests | [integration-responses-conversations-auth-tests.yml](integration-responses-conversations-auth-tests.yml) | Run responses, conversations, and prompts auth tests with Kubernetes authentication |
| SqlStore Integration Tests | [integration-sql-store-tests.yml](integration-sql-store-tests.yml) | Run the integration test suite with SqlStore |
| Connect CLI - Agent Smoke Tests | [integration-tests-connect-cli.yml](integration-tests-connect-cli.yml) | Drive the agent CLIs (Claude Code, Codex, OpenCode) through ogx connect (mock provider backend) |
| Messages API - Claude Agent SDK Smoke Test | [integration-tests-messages-clients.yml](integration-tests-messages-clients.yml) | Drive the latest Claude Agent SDK against /v1/messages (mock provider backend) |
| Integration Tests (Replay) | [integration-tests.yml](integration-tests.yml) | Run the integration test suites from tests/integration in replay mode |
| Vector IO Integration Tests | [integration-vector-io-tests.yml](integration-vector-io-tests.yml) | Run the integration test suite with various VectorIO providers |
| OpenAPI Generator SDK Validation | [openapi-generator-validation.yml](openapi-generator-validation.yml) | Validate OpenAPI Generator SDK generation |
| OpenResponses Conformance Tests | [openresponses-conformance.yml](openresponses-conformance.yml) | Run OpenResponses conformance tests against ogx Responses API |
| Post-release automation | [post-release.yml](post-release.yml) | Post-release automation |
| Pre-commit | [pre-commit.yml](pre-commit.yml) | Run pre-commit checks |
| Prepare release | [prepare-release.yml](prepare-release.yml) | Prepare release |
| Test OGX Build | [providers-build.yml](providers-build.yml) | Test ogx build and list-deps |
| Build, test, and publish packages | [pypi.yml](pypi.yml) | Build, test, and publish packages |
| Quickstart Smoke Test | [quickstart-tests.yml](quickstart-tests.yml) | Run the docs quickstart against a fresh ogx install |
| Integration Tests (Record) | [record-integration-tests.yml](record-integration-tests.yml) | Auto-record missing test recordings for PR |
| Release Branch Scheduled CI | [release-branch-scheduled-ci.yml](release-branch-scheduled-ci.yml) | Scheduled CI checks for active release branches |
| Check semantic PR titles | [semantic-pr.yml](semantic-pr.yml) | Ensure that PR titles follow the conventional commit spec |
| Close stale issues and PRs | [stale_bot.yml](stale_bot.yml) | Run the Stale Bot action |
| Test External Providers Installed via Module | [test-external-provider-module.yml](test-external-provider-module.yml) | Test External Provider installation via Python module |
| Test External API and Providers | [test-external.yml](test-external.yml) | Test the External API and Provider mechanisms |
| Trigger Docs Deploy | [trigger-docs-deploy.yml](trigger-docs-deploy.yml) | Trigger docs site rebuild after docs change |
| Trivy Scheduled Security Scan | [trivy-scheduled.yml](trivy-scheduled.yml) | Trivy Scheduled Security Scan |
| Trivy Security Scan | [trivy-security.yml](trivy-security.yml) | Trivy Security Scan |
| UI Tests | [ui-unit-tests.yml](ui-unit-tests.yml) | Run the UI test suite |
| Unit Tests | [unit-tests.yml](unit-tests.yml) | Run the unit test suite |

---

### Overview (`benchmarking/k8s-benchmark/README.md`)

# OGX Benchmark Suite on Kubernetes

## Motivation

Performance benchmarking is critical for understanding the overhead and characteristics of the OGX abstraction layer compared to direct inference engines like vLLM.

### Why This Benchmark Suite Exists

**Performance Validation**: The OGX provides a unified API layer across multiple inference providers, but this abstraction introduces potential overhead. This benchmark suite quantifies the performance impact by comparing:

- OGX inference (with vLLM backend)
- Direct vLLM inference calls
- Both under identical Kubernetes deployment conditions

**Production Readiness Assessment**: Real-world deployments require understanding performance characteristics under load. This suite simulates concurrent user scenarios with configurable parameters (duration, concurrency, request patterns) to validate production readiness.

**Regression Detection (TODO)**: As the OGX evolves, this benchmark provides automated regression detection for performance changes. CI/CD pipelines can leverage these benchmarks to catch performance degradations before production deployments.

**Resource Planning**: By measuring throughput, latency percentiles, and resource utilization patterns, teams can make informed decisions about:

- Kubernetes resource allocation (CPU, memory, GPU)
- Auto-scaling configurations
- Cost optimization strategies

### Key Metrics Captured

The benchmark suite measures critical performance indicators:

- **Throughput**: Requests per second under sustained load
- **Latency Distribution**: P50, P95, P99 response times
- **Time to First Token (TTFT)**: Critical for streaming applications
- **Inter-Token Latency (ITL)**: Token generation speed for streaming
- **Error Rates**: Request failures and timeout analysis

This data enables data-driven architectural decisions and performance optimization efforts.

## Setup

**1. Deploy base k8s infrastructure:**

```bash
cd ../../docs/source/distributions/k8s
./apply.sh
```

**2. Deploy benchmark components:**

```bash
./apply.sh
```

**3. Verify deployment:**

```bash
kubectl get pods
# Should see: ogx-benchmark-server, vllm-server, etc.
```

## Benchmark Results

We use [GuideLLM](https://github.com/neuralmagic/guidellm) against our k8s deployment for comprehensive performance testing.

### Performance - 1 vLLM Replica

We vary the number of OGX replicas with 1 vLLM replica and compare performance below.



For full results see the `benchmarking/k8s-benchmark/results/` directory.

## Quick Start

Follow the instructions below to run benchmarks similar to the ones above.

### Comprehensive Benchmark Suite

**Run all benchmarks with different cluster configurations:**

```bash
./scripts/run-all-benchmarks.sh
```

This script will automatically:

- Scale deployments to different configurations
- Run benchmarks for each setup
- Generate output files with meaningful names that include setup information

### Individual Benchmarks

**Benchmark OGX (runs against current cluster setup):**

```bash
./scripts/run-guidellm-benchmark.sh --target stack
```

**Benchmark vLLM direct (runs against current cluster setup):**

```bash
./scripts/run-guidellm-benchmark.sh --target vllm
```

**Benchmark with custom parameters:**

```bash
./scripts/run-guidellm-benchmark.sh --target stack --max-seconds 120 --prompt-tokens 1024 --output-tokens 512
```

**Benchmark with custom output file:**

```bash
./scripts/run-guidellm-benchmark.sh --target stack --output-file results/my-custom-benchmark.txt
```

### Generating Charts

Once the benchmarks are run, you can generate performance charts from benchmark results:

```bash
uv run ./scripts/generate_charts.py
```

This loads runs in the `results/` directory and creates visualizations comparing different configurations and replica counts.

## Benchmark Workflow

The benchmark suite is organized into two main scripts with distinct responsibilities:

### 1. `run-all-benchmarks.sh` - Orchestration & Scaling

- **Purpose**: Manages different cluster configurations and orchestrates benchmark runs
- **Responsibilities**:
  - Scales Kubernetes deployments (vLLM replicas, Stack replicas, worker counts)
  - Runs benchmarks for each configuration
  - Generates meaningful output filenames with setup information
- **Use case**: Running comprehensive performance testing across multiple configurations

### 2. `run-guidellm-benchmark.sh` - Single Benchmark Execution

- **Purpose**: Executes a single benchmark against the current cluster state
- **Responsibilities**:
  - Runs GuideLLM benchmark with configurable parameters
  - Accepts custom output file paths
  - No cluster scaling - benchmarks current deployment state
- **Use case**: Testing specific configurations or custom scenarios

### Typical Workflow

1. **Comprehensive Testing**: Use `run-all-benchmarks.sh` to automatically test multiple configurations
2. **Custom Testing**: Use `run-guidellm-benchmark.sh` for specific parameter testing or manual cluster configurations
3. **Analysis**: Use `generate_charts.py` to visualize results from either approach

## Command Reference

### run-all-benchmarks.sh

Orchestrates multiple benchmark runs with different cluster configurations. This script:

- Automatically scales deployments before each benchmark
- Runs benchmarks against the configured cluster setup
- Generates meaningfully named output files

```bash
./scripts/run-all-benchmarks.sh
```

**Configuration**: Edit the `configs` array in the script to customize benchmark configurations:

```bash
# Each line: (target, stack_replicas, vllm_replicas, stack_workers)
configs=(
    "stack 1 1 1"
    "stack 1 1 2"
    "stack 1 1 4"
    "vllm 1 1 -"
)
```

**Output files**: Generated with setup information in filename:

- Stack: `guidellm-benchmark-stack-s{replicas}-sw{workers}-v{vllm_replicas}-{timestamp}.txt`
- vLLM: `guidellm-benchmark-vllm-v{vllm_replicas}-{timestamp}.txt`

### run-guidellm-benchmark.sh Options

Runs a single benchmark against the current cluster setup (no scaling).

```bash
./scripts/run-guidellm-benchmark.sh [options]

Options:
  -t, --target <stack|vllm>     Target to benchmark (default: stack)
  -s, --max-seconds <seconds>   Maximum duration in seconds (default: 60)
  -p, --prompt-tokens <tokens>  Number of prompt tokens (default: 512)
  -o, --output-tokens <tokens>  Number of output tokens (default: 256)
  -r, --rate-type <type>        Rate type (default: concurrent)
  -c, --rate                    Rate (default: 1,2,4,8,16,32,64,128)
  --output-file <path>          Output file path (default: auto-generated)
  --stack-deployment <name>     Name of the stack deployment (default: ogx-benchmark-server)
  --vllm-deployment <name>      Name of the vllm deployment (default: vllm-server)
  --stack-url <url>             URL of the stack service (default: http://ogx-benchmark-service:8323/v1/openai)
  -h, --help                    Show help message

Examples:
  ./scripts/run-guidellm-benchmark.sh --target vllm                              # Benchmark vLLM direct
  ./scripts/run-guidellm-benchmark.sh --target stack                             # Benchmark OGX (default)
  ./scripts/run-guidellm-benchmark.sh -t vllm -s 60 -p 512 -o 256               # vLLM with custom parameters
  ./scripts/run-guidellm-benchmark.sh --output-file results/my-benchmark.txt     # Specify custom output file
  ./scripts/run-guidellm-benchmark.sh --stack-deployment my-stack-server         # Use custom stack deployment name
```

## Local Testing

### Running Benchmark Locally

For local development without Kubernetes:

**1. (Optional) Start Mock OpenAI server:**

There is a simple mock OpenAI server if you don't have an inference provider available.
The `openai-mock-server.py` provides:

- **OpenAI-compatible API** for testing without real models
- **Configurable streaming delay** via `STREAM_DELAY_SECONDS` env var
- **Consistent responses** for reproducible benchmarks
- **Lightweight testing** without GPU requirements

```bash
uv run python openai-mock-server.py --port 8080
```

**2. Start Stack server:**

```bash
OGX_CONFIG=benchmarking/k8s-benchmark/stack_run_config.yaml uv run uvicorn ogx.core.server.server:create_app --port 8321 --workers 4 --factory
```

**3. Run GuideLLM benchmark:**

```bash
GUIDELLM__PREFERRED_ROUTE="chat_completions" uv run guidellm benchmark run \
  --target "http://localhost:8321/v1/openai/v1" \
  --model "meta-llama/Llama-3.2-3B-Instruct" \
  --rate-type sweep \
  --max-seconds 60 \
  --data "prompt_tokens=256,output_tokens=128" --output-path='output.html'
```

---

### Overview (`benchmarking/rag/README.md`)

# RAG Benchmark Suite

Evaluates RAG quality through OGX's OpenAI-compatible API surface
(Files → Vector Stores → Responses with `file_search`). The same code runs
against both **OpenAI SaaS** and **OGX** — swap `--base-url` to
switch backends.

## Benchmarks

| Benchmark | Type | Primary Metric | Description |
|---|---|---|---|
| **BEIR** | Retrieval-only | nDCG@10 | Standard IR benchmarks (nfcorpus, scifact, arguana, fiqa, trec-covid) |
| **MultiHOP RAG** | End-to-end RAG | EM / F1 | Multi-hop reasoning over news articles |
| **QReCC** | Conversational RAG | EM / F1 | Multi-turn conversational QA with scoped corpus per conversation |
| **Doc2Dial** | Document-grounded dialogue | EM / F1 | Goal-oriented dialogues grounded in documents |

## Prerequisites

- Python 3.11+
- An OpenAI API key (for OpenAI SaaS runs, or for OGX's `remote::openai` inference)
- For OGX runs: a running Milvus instance and a OGX server

## Quick Start

```bash
cd benchmarking/rag

# Create a virtual environment and install dependencies
uv venv && source .venv/bin/activate
uv pip install -r requirements.txt

# Copy and edit the environment file
cp .env.example .env
# Edit .env with your OPENAI_API_KEY
```

## Running Against OpenAI

```bash
python run_benchmark.py --benchmark beir --base-url https://api.openai.com/v1
python run_benchmark.py --benchmark multihop --base-url https://api.openai.com/v1
python run_benchmark.py --benchmark qrecc --base-url https://api.openai.com/v1
python run_benchmark.py --benchmark doc2dial --base-url https://api.openai.com/v1
```

## Running Against OGX

First, start OGX with the included config:

```bash
# Start Milvus (if not already running)
# Start OGX
bash start_stack.sh
```

Then run benchmarks:

```bash
python run_benchmark.py --benchmark beir --base-url http://localhost:8321/v1 --search-mode hybrid
python run_benchmark.py --benchmark multihop --base-url http://localhost:8321/v1 --search-mode hybrid
```

## Running All Benchmarks

```bash
bash run_all.sh
```

This runs all four benchmarks against both OpenAI SaaS and OGX
(vector and hybrid search modes).

## Comparing Results

After running benchmarks against multiple backends:

```bash
python compare_results.py              # Table output
python compare_results.py --format csv # CSV output
python compare_results.py --format json --output results.json
```

## Running with Open-Source Models via vLLM

The benchmark suite supports any OpenAI-compatible inference backend. To use a
self-hosted model via vLLM:

1. Register vLLM as a `remote::openai` provider in `config.yaml`
2. Point `--model` at the registered model ID
3. For reasoning models that require `enable_thinking=False`, pass `--disable-thinking`

```bash
python run_benchmark.py --benchmark doc2dial \
  --base-url http://localhost:8321/v1 \
  --model vllm/google/gemma-4-31B-it \
  --search-mode hybrid \
  --disable-thinking
```

See `results/REPORT.md` for benchmark results comparing OpenAI SaaS, OGX with
GPT-4.1, and OGX with Gemma 4 31B-IT.

## CLI Options

```text
python run_benchmark.py --help

Options:
  --benchmark       beir | multihop | qrecc | doc2dial (required)
  --dataset         BEIR dataset name (nfcorpus, scifact, arguana, fiqa, trec-covid)
  --base-url        API base URL (default: https://api.openai.com/v1)
  --search-mode     vector | hybrid | keyword (OGX only)
  --model           Model for end-to-end RAG (default: gpt-4.1)
  --max-queries     Limit number of queries (useful for testing)
  --max-conversations  Limit conversations for QReCC/Doc2Dial
  --resume          Resume from checkpoint
  --disable-thinking  Disable thinking for reasoning models (vLLM)
  --output-dir      Custom output directory
  --data-dir        Custom data directory
  --verbose         Enable debug logging
```

## Directory Layout

```text
benchmarking/rag/
├── lib/                  # Core library
│   ├── client.py         # OpenAI client factory (configurable base_url)
│   ├── ingest.py         # Corpus upload: Files API → Vector Stores API
│   ├── search.py         # Retrieval-only eval: Vector Stores Search API
│   ├── query.py          # End-to-end RAG: Responses API with file_search
│   ├── metrics.py        # pytrec_eval, HF evaluate, rouge-score
│   └── utils.py          # Checkpointing, batching, ID mapping
├── benchmarks/           # Benchmark adapters
│   ├── base.py           # Abstract BenchmarkRunner
│   ├── beir_bench.py     # BEIR (retrieval-only, nDCG@10)
│   ├── multihop_bench.py # MultiHOP RAG (end-to-end, EM/F1)
│   ├── qrecc_bench.py    # QReCC (conversational, scoped corpus)
│   └── doc2dial_bench.py # Doc2Dial (document-grounded dialogue)
├── run_benchmark.py      # CLI entry point
├── run_all.sh            # Run all benchmarks
├── compare_results.py    # Generate comparison tables
├── config.yaml           # OGX server config
├── start_stack.sh        # Launch OGX
├── requirements.txt      # Python dependencies
└── .env.example          # Environment variables template
```

## How It Works

1. **Ingestion**: Documents are uploaded via the Files API, then attached to a
   Vector Store via the Vector Stores API. Uploads are batched and checkpointed
   for resumability.

2. **Retrieval** (BEIR): Queries are run through the Vector Stores Search API.
   Results are mapped back to corpus doc IDs and evaluated with pytrec_eval.

3. **End-to-end RAG** (MultiHOP, QReCC, Doc2Dial): Queries are sent to the
   Responses API with the `file_search` tool. Answer quality is measured with
   Exact Match, token-level F1 (HuggingFace SQuAD metric), and ROUGE-L.

4. **Conversational RAG** (QReCC, Doc2Dial): Multi-turn conversations are
   threaded using `previous_response_id` to maintain context across turns.

---

### Overview (`benchmarking/vertical-scaling/README.md`)

# OGX Vertical Scaling Benchmark

A simple benchmark suite for measuring the vertical scaling performance of the OGX inference API using a mocked OpenAI-compatible backend.

## Overview

This benchmark measures how well the OGX server scales with increasing worker counts. It uses:

- **Python Mock Server** - Lightweight HTTP server returning fixed OpenAI-compatible responses
- **Locust** - Load testing tool to generate concurrent requests
- **OGX Server** - The inference API under test with `remote::openai` provider

The benchmark runs twice:

1. **Baseline**: Tests the mock server directly to establish maximum throughput
2. **Stack**: Tests the stack server to measure routing overhead

This helps identify bottlenecks in the stack routing layer and measure the impact of vertical scaling (adding more workers) on throughput and latency.

## Prerequisites

### Python (for mock server)

The mock server is a simple Python script with no dependencies beyond the standard library.

```bash
python --version
```

### Locust (Load Testing)

Verify installation:

```bash
uv run --group benchmark locust --version
```

## Quick Start

Run a benchmark with default settings (1 worker, 1 user, 60 seconds):

```bash
cd benchmarking/vertical-scaling
./run-benchmark.sh
```

This will:

1. Check port availability (8080, 8321)
2. Start Python mock server on port 8080
3. Start OGX server on port 8321 with 1 worker
4. Run baseline benchmark against mock server (60 seconds)
5. Run stack benchmark against stack server (60 seconds)
6. Generate HTML reports in `results/`
7. Clean up all services

## Usage

**Server Options:**

- `--workers NUMBER` - Number of uvicorn workers (default: 1)
- `--mock-port NUMBER` - Port for mock server (default: 8080)
- `--stack-port NUMBER` - Port for OGX server (default: 8321)

**Benchmark Options:**

- `--users NUMBER` - Concurrent users (default: 1)
- `--run-time SECONDS` - Test duration (default: 60)

## Interpreting Results

### Output Files

Results are saved to `results/` directory:

- `baseline.html` - Interactive HTML report for mock server baseline
- `baseline_stats.csv` - Baseline summary statistics
- `baseline_stats_history.csv` - Baseline time-series data
- `baseline_failures.csv` - Baseline failed requests
- `stack.html` - Interactive HTML report for stack server
- `stack_stats.csv` - Stack summary statistics
- `stack_stats_history.csv` - Stack time-series data
- `stack_failures.csv` - Stack failed requests

Additional files in the benchmark directory:

- `stack.log` - OGX server logs

Compare the baseline and stack HTML reports to see the routing overhead.

### Key Metrics

Open the HTML report to view:

1. **Requests/s (RPS)** - Throughput metric
   - Higher is better
   - Should increase with more workers (up to a point)

2. **Response Times** - Latency metrics
   - **p50 (median)** - Typical user experience
   - **p95** - 95th percentile, catches slower requests
   - **p99** - 99th percentile, catches outliers
   - Lower is better

3. **Failure Rate** - Error percentage
   - Should be 0% for healthy setup
   - High failure rate indicates overload

### Identifying Bottlenecks

**Good vertical scaling:**

- RPS increases linearly with workers (2x workers ≈ 2x RPS)
- Latency remains stable or improves
- No failures

**CPU-bound bottleneck:**

- RPS increases but plateaus at high worker counts
- Latency increases with more workers
- System CPU usage at 100%

**I/O-bound bottleneck:**

- RPS doesn't increase much with workers
- Latency increases significantly
- Network or disk I/O saturated

**GIL bottleneck (Python):**

- RPS plateaus around 2-4 workers
- Adding more workers doesn't help
- Consider using multiple processes

---

### Overview (`client-sdks/openapi/README.md`)

# OpenAPI Generator SDK

The `ogx-client` Python SDK is generated with [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). The base OpenAPI spec and resource-hierarchy config are read from `../spec` and enriched before code generation.

## Prerequisites

### Java 11+

openapi-generator-cli requires Java 11 or higher.

```bash
# macOS
brew install openjdk

# Fedora/RHEL/CentOS
sudo dnf install java-11-openjdk
# For other Linux distributions, use your package manager (apt, yum, pacman, etc.).
```

### OpenAPI Generator CLI

For more installation options, see: <https://openapi-generator.tech/docs/installation>

```bash
# macOS
brew install openapi-generator

# Linux (also possible for macOS)
npm install @openapitools/openapi-generator-cli
```

### Python Dependencies

```bash
uv pip install ruamel.yaml
```

## Usage

**From the client-sdks/openapi directory:**

```bash
cd client-sdks/openapi

make openapi    # Generate enriched OpenAPI spec from the base spec + resource config
make hierarchy  # Process spec for hierarchical SDK structure
make sdk        # Generate Python SDK (runs full pipeline)
make version    # Show version that will be used
make clean      # Remove generated files
```

The `make sdk` target runs the full pipeline and will automatically check for required dependencies (openapi-generator-cli and java) before generating.

## How it Works

```text
merge_resources.py  ->  build_hierarchy.py  ->  openapi-generator  ->  patch_hierarchy.py
```

1. **`merge_resources.py`** reads the base spec from `../spec/openapi.yml`, enriches it with resource mappings from `../spec/resources.yml`, and applies patches from `patches.yml`. This is the only step that depends on the resource-hierarchy config.
2. **`build_hierarchy.py`** extracts tag hierarchies, reduces endpoints to leaf tags, creates dummy endpoints for parent resource groups, and applies schema fixes for openapi-generator compatibility.
3. **`openapi-generator`** generates the Python SDK from the processed spec using custom Mustache templates.
4. **`patch_hierarchy.py`** patches the generated API classes to wire up parent-child relationships, enabling nested access like `client.chat.completions.create(...)`.

**Generated files (git-ignored):**

- `openapi.yml` - Enriched OpenAPI specification
- `openapi-hierarchical.yml` - Processed spec with hierarchy tags
- `api-hierarchy.yml` - Hierarchy data for post-generation patching
- `sdks/python/` - Generated Python SDK
- `.openapi-generator/` - Generator metadata

## CI/CD Automation

### Continuous Integration

The CI workflow (`.github/workflows/openapi-generator-validation.yml`) automatically validates SDK generation on every PR:

- ✅ Generates OpenAPI spec from the base spec + resource config
- ✅ Builds Python SDK (1,134 files)
- ✅ Verifies SDK installation and imports
- ✅ Runs integration tests against generated SDK
- ✅ Multi-platform testing:
  - **Ubuntu** - Always runs
  - **macOS** - Runs for main/release branch pushes, or when critical files change

**Triggered by:**

- Pull requests modifying OpenAPI generation files
- Pushes to `main` or `release-*` branches
- Manual workflow_dispatch

### Continuous Delivery

The `ogx-client` package is published through the unified PyPI/NPM release workflow (`.github/workflows/pypi.yml`) alongside other ogx packages.

**Automatic publishing (via tags):**

- Tags matching `v*` trigger the unified workflow
- The workflow builds all packages including `ogx-client`

**Manual publishing (via GitHub UI):**

- Go to Actions → "Build, test, and publish packages"
- Choose `packages: clients-only` (or `all`) and the desired `dry_run` mode

## Publishing to PyPI

The SDK is published as `ogx-client` via the unified workflow at `.github/workflows/pypi.yml`.

### Manual Publishing (via GitHub UI)

1. Go to Actions → "Build, test, and publish packages"
2. Click "Run workflow"
3. Select options:
   - **packages**: `clients-only` or `all`
   - **dry_run**: `test-pypi` (default), `build-only`, or `off` (production)

### Automatic Publishing (via Git Tags)

Push a version tag to trigger the unified workflow:

```bash
# Release → triggers unified workflow for all packages
git tag v1.0.0
git push origin v1.0.0
```

### Testing the Published Package

After publishing to TestPyPI:

```bash
pip install --index-url https://test.pypi.org/simple/ ogx-client
```

After publishing to PyPI:

```bash
pip install ogx-client
```

## Files

- `Makefile` - Build orchestration
- `merge_resources.py` - Merge the resource-hierarchy config into the OpenAPI spec
- `build_hierarchy.py` - Extract hierarchy and prepare spec for code generation
- `patch_hierarchy.py` - Post-generation patching for nested API structure
- `patches.yml` - OpenAPI spec patches for codegen compatibility
- `openapi-config.json` - Python SDK generation config
- `openapitools.json` - OpenAPI Generator CLI version config
- `templates/python/` - Custom Mustache templates and library files
  - `LICENSE.mustache` - MIT license for generated SDK
  - `CHANGELOG.mustache` - Changelog template for release notes

---

### Overview (`client-sdks/spec/README.md`)

These are the source files for the generated `ogx-client` Python SDK (see `../openapi`).

- `openapi.yml`: the OpenAPI specification for the OGX API.
- `resources.yml`: the resource-hierarchy configuration that maps resources to endpoints. The `../openapi` pipeline reads its `resources:` tree to build the client's method hierarchy.

Both files are regenerated by `scripts/run_openapi_generator.sh`:

- `openapi.yml` comes from the FastAPI-based spec generator.
- `resources.yml` is rendered from `scripts/openapi_generator/resources_config/generate_resources.py` so the resource mapping stays in lock-step with the spec.

---

### Overview (`docs/zero_to_hero_guide/README.md`)

# OGX: from Zero to Hero

OGX defines and standardizes the set of core building blocks needed to bring generative AI applications to market. These building blocks are presented in the form of interoperable APIs with a broad set of Providers providing their implementations. These building blocks are assembled into Distributions which are easy for developers to get from zero to production.

This guide will walk you through an end-to-end workflow with OGX with Ollama as the inference provider and ChromaDB as the VectorIO provider. Please note the steps for configuring your provider and distribution will vary depending on the services you use. However, the user experience will remain universal - this is the power of Llama-Stack.

If you're looking for more specific topics, we have a [Zero to Hero Guide](#next-steps) that covers everything from 'Tool Calling' to 'Agents' in detail. Feel free to skip to the end to explore the advanced topics you're interested in.

> If you'd prefer not to set up a local server, explore our notebook on [tool calling with the Together API](Tool_Calling101_Using_Together_Llama_Stack_Server.ipynb). This notebook will show you how to leverage together.ai's OGX Server API, allowing you to get started with OGX without the need for a locally built and running server.

## Table of Contents

- [OGX: from Zero to Hero](#ogx-from-zero-to-hero)
  - [Table of Contents](#table-of-contents)
  - [Setup ollama](#setup-ollama)
  - [Install Dependencies and Set Up Environment](#install-dependencies-and-set-up-environment)
  - [Build, Configure, and Run OGX](#build-configure-and-run-ogx)
  - [Test with `ogx-client` CLI](#test-with-ogx-client-cli)
  - [Test with `curl`](#test-with-curl)
  - [Test with Python](#test-with-python)
    - [1. Create Python Script (`test_ogx.py`)](#1-create-python-script-test_ogxpy)
    - [2. Create a Chat Completion Request in Python](#2-create-a-chat-completion-request-in-python)
    - [3. Run the Python Script](#3-run-the-python-script)
  - [Next Steps](#next-steps)

---

## Setup ollama

1. **Download Ollama App**:
   - Go to [https://ollama.com/download](https://ollama.com/download).
   - Follow instructions based on the OS you are on. For example, if you are on a Mac, download and unzip `Ollama-darwin.zip`.
   - Run the `Ollama` application.

2. **Download the Ollama CLI**:
   Ensure you have the `ollama` command line tool by downloading and installing it from the same website.

3. **Start ollama server**:
   Open the terminal and run:

   ```bash
   ollama serve
   ```

4. **Run the model**:
   Open the terminal and run:

   ```bash
   ollama run llama3.2:3b-instruct-fp16 --keepalive -1m
   ```

   **Note**:
     - Browse the [Ollama model library](https://ollama.com/library) for models available to run locally.
     - `keepalive -1m` is used so that ollama continues to keep the model in memory indefinitely. Otherwise, ollama frees up memory and you would have to run `ollama run` again.

---

## Install Dependencies and Set Up Environment

1. **Install uv**:
   Install [uv](https://docs.astral.sh/uv/) for managing dependencies:

   ```bash
   # macOS and Linux
   curl -LsSf https://astral.sh/uv/install.sh | sh

   # Windows
   powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
   ```

2. **Install ChromaDB**:
   Install `chromadb` using `uv`:

   ```bash
   uv pip install chromadb
   ```

3. **Run ChromaDB**:
   Start the ChromaDB server:

   ```bash
   chroma run --host localhost --port 8000 --path ./my_chroma_data
   ```

---

## Build, Configure, and Run OGX

1. **Install dependencies**:

   ```bash
   ogx stack list-deps starter | xargs -L1 uv pip install
   ```

2. **Start the distribution**:

   ```bash
   ogx run starter
   ```

3. **Set the ENV variables by exporting them to the terminal**:

   ```bash
   export OLLAMA_URL="http://localhost:11434"
   export OGX_PORT=8321
   export INFERENCE_MODEL="meta-llama/Llama-3.2-3B-Instruct"
   export MODERATION_ENDPOINT="http://localhost:11434/v1/moderations"
   ```

4. **Run the OGX**:
   Run the stack using uv:

   ```bash
   INFERENCE_MODEL=$INFERENCE_MODEL \
   MODERATION_ENDPOINT=$MODERATION_ENDPOINT \
   OLLAMA_URL=$OLLAMA_URL \
   uv run --with ogx ogx run starter \
      --port $OGX_PORT
   ```

   Note: Every time you run a new model with `ollama run`, you will need to restart the ogx. Otherwise it won't see the new model.

The server will start and listen on `http://localhost:8321`.

---

## Test with `ogx-client` CLI

After setting up the server, open a new terminal window and configure the ogx-client.

1. Configure the CLI to point to the ogx server.

   ```bash
   uv run --with ogx-client ogx-client configure --endpoint http://localhost:8321
   ```

   **Expected Output:**

   ```bash
   Done! You can now use the OGX Client CLI with endpoint http://localhost:8321
   ```

2. Test the CLI by running inference:

   ```bash
   uv run --with ogx-client ogx-client inference chat-completion --message "Write me a 2-sentence poem about the moon"
   ```

   **Expected Output:**

   ```bash
   OpenAIChatCompletion(
      id='chatcmpl-950',
      choices=[
         OpenAIChatCompletionChoice(
               finish_reason='stop',
               index=0,
               message=OpenAIChatCompletionChoiceMessageOpenAIAssistantMessageParam(
                  role='assistant',
                  content='...The moon casts silver threads through the velvet night, a silent bard of shadows, ancient and bright.',
                  name=None,
                  tool_calls=None,
                  refusal=None,
                  annotations=None,
                  audio=None,
                  function_call=None
               ),
               logprobs=None
         )
      ],
      created=1759240813,
      model='meta-llama/Llama-3.2-3B-Instruct',
      object='chat.completion',
      service_tier=None,
      system_fingerprint='fp_ollama',
      usage={
         'completion_tokens': 479,
         'prompt_tokens': 19,
         'total_tokens': 498,
         'completion_tokens_details': None,
         'prompt_tokens_details': None
      },
   )
   ```

## Test with `curl`

After setting up the server, open a new terminal window and verify it's working by sending a `POST` request using `curl`:

```bash
curl http://localhost:$OGX_PORT/v1/chat/completions
-H "Content-Type: application/json"
-d @- <<EOF
{
    "model": "$INFERENCE_MODEL",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write me a 2-sentence poem about the moon"}
    ],
      "temperature": 0.7,
      "seed": 42,
      "max_tokens": 512
   }
}
EOF
```

You can check the available models with the command `uv run --with ogx-client ogx-client models list`.

**Expected Output:**

```json
{
    ...
    "content": "... The moon glows softly in the midnight sky,\nA beacon of wonder, as it catches the eye.",
    ...
}
```

---

## Test with Python

You can also interact with the OGX server using a simple Python script. Below is an example:

### 1. Create Python Script (`test_ogx.py`)

```bash
touch test_ogx.py
```

### 2. Create a Chat Completion Request in Python

In `test_ogx.py`, write the following code:

```python
import os
from ogx_client import OgxClient

# Get the model ID from the environment variable
INFERENCE_MODEL = os.environ.get("INFERENCE_MODEL")

# Check if the environment variable is se
if INFERENCE_MODEL is None:
    raise ValueError("The environment variable 'INFERENCE_MODEL' is not set.")

# Initialize the client
client = OgxClient(base_url="http://localhost:8321")

# Create a chat completion request
response = client.chat.completions.create(
    messages=[
        {"role": "system", "content": "You are a friendly assistant."},
        {"role": "user", "content": "Write a two-sentence poem about llama."},
    ],
    model=INFERENCE_MODEL,
)

# Print the response
print(response.choices[0].message.content)
```

### 3. Run the Python Script

```bash
uv run --with ogx-client python test_ogx.py
```

**Expected Output:**

```text
The moon glows softly in the midnight sky,
A beacon of wonder, as it catches the eye.
```

With these steps, you should have a functional OGX setup capable of generating text using the specified model. For more detailed information and advanced configurations, refer to some of our documentation below.

This command initializes the model to interact with your local OGX instance.

---

## Next Steps

**Explore Other Guides**: Dive deeper into specific topics by following these guides:

- [Understanding Distribution](https://ogx-ai.github.io/latest/concepts/index.html#distributions)
- [Inference 101](00_Inference101.ipynb)
- [Local and Cloud Model Toggling 101](01_Local_Cloud_Inference101.ipynb)
- [Prompt Engineering](02_Prompt_Engineering101.ipynb)
- [Chat with Image - OGX Vision API](03_Image_Chat101.ipynb)
- [Tool Calling: How to and Details](04_Tool_Calling101.ipynb)
- [Memory API: Show Simple In-Memory Retrieval](05_Memory101.ipynb)
- [Agents API: Explain Components](07_Agents101.ipynb)

**Explore Client SDKs**: Utilize our client SDKs for various languages to integrate OGX into your applications:

- [Python SDK](https://github.com/ogx-ai/ogx-client-python)
- [Node SDK](https://github.com/ogx-ai/ogx-client-typescript)
- [Swift SDK](https://github.com/ogx-ai/llama-stack-client-swift)
- [Kotlin SDK](https://github.com/ogx-ai/llama-stack-client-kotlin)

**Advanced Configuration**: Learn how to customize your OGX distribution by referring to the [Building a OGX Distribution](https://ogx-ai.github.io/latest/distributions/building_distro.html) guide.

**Explore Example Apps**: Check out [Llama Stack Apps](https://github.com/ogx-ai/llama-stack-apps/tree/main/examples) for example applications built using OGX.

---

---

### Overview (`scripts/telemetry/README.md`)

# Observability Test for OGX

This directory contains configuration files and a setup script to deploy a full observability stack for testing OGX telemetry. It uses OpenTelemetry, Jaeger, Prometheus, and Grafana to collect traces, metrics, and visualize them.

## Architecture

```text
┌──────────────┐
│  OGX │──┐
│  Server      │  │  OTLP     ┌───────────────────┐   scrape    ┌──────────────┐
└──────────────┘  ├─────────►│  OTel Collector     │◄───────────│  Prometheus  │
┌──────────────┐  │  :4318   │  :4317 (gRPC)       │   :9464    │  :9090       │
│  OGX │──┘          │  :4318 (HTTP)       │            └──────────────┘
│  Client      │             └────────┬────────────┘                   ▲
└──────────────┘                      │ OTLP                           │
                                      ▼                           datasource
                             ┌────────────────┐                        │
                             │  Jaeger         │              ┌──────────────┐
                             │  :16686 (UI)    │◄────────────│  Grafana     │
                             └────────────────┘  datasource   │  :3000 (UI)  │
                                                              └──────────────┘
```

| Component | Purpose | Port(s) |
|---|---|---|
| **OTel Collector** | Receives OTLP telemetry, exports traces to Jaeger and metrics to Prometheus (and optionally MLflow) | 4317 (gRPC), 4318 (HTTP), 9464 (Prometheus metrics) |
| **Jaeger** | Distributed tracing UI | 16686 |
| **Prometheus** | Metrics storage and querying | 9090 |
| **Grafana** | Dashboards and visualization | 3000 |
| **MLflow** | Trace ingest via OTLP `/v1/traces` (container in this stack) | 5001 |

## Pre-requisites

- **Docker** or **Podman** installed and running
- **OGX** development environment set up
- **OpenTelemetry Python packages** (installed in step 2 below)

## Files

| File | Description |
|---|---|
| `setup_telemetry.sh` | Main script to start all telemetry services |
| `otel-collector-config.yaml` | OpenTelemetry Collector configuration (OTLP receiver, Prometheus exporter, Jaeger exporter) |
| `prometheus.yml` | Prometheus scrape configuration (scrapes OTel Collector on port 9464) |
| `grafana-datasources.yaml` | Grafana datasource provisioning (Prometheus + Jaeger) |
| `grafana-dashboards.yaml` | Grafana dashboard provisioning configuration |
| `ogx-dashboard.json` | Pre-built Grafana dashboard for OGX (token usage, operation duration, HTTP metrics) |

## Steps

### Start the telemetry stack

Run the setup script to start Jaeger, OTel Collector, Prometheus, and Grafana:

```bash
# Auto-detect container runtime (podman or docker)
./scripts/telemetry/setup_telemetry.sh

# Or specify a container runtime explicitly
./scripts/telemetry/setup_telemetry.sh --container docker
./scripts/telemetry/setup_telemetry.sh --container podman
```

This will:

- Create a `llama-telemetry` container network
- Start Jaeger, OTel Collector, Prometheus, and Grafana containers
- Provision Grafana with a pre-built OGX dashboard

> **MLflow traces**
>
> - MLflow is now started as a container in this stack (`mlflow:5001`), OTLP endpoint `/v1/traces`.
> - Collector exporter `otlphttp/mlflow` points to `http://mlflow:5001/v1/traces`, header `x-mlflow-experiment-id: "1"`. If you need auth, set `MLFLOW_OTEL_HEADERS` (e.g., `Authorization=Bearer <token>`) before running the setup script.
> - If you prefer an external MLflow, override `MLFLOW_OTEL_ENDPOINT` before running the script (e.g., `http://host.docker.internal:5001`).

### Install OpenTelemetry instrumentation For OGX Server and Client

```bash
uv pip install opentelemetry-distro opentelemetry-exporter-otlp
uv run opentelemetry-bootstrap -a requirements | uv pip install --requirement -
```

### Set environment variables and start OGX Server

```bash
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_SERVICE_NAME=ogx-server

uv run opentelemetry-instrument ogx run starter
```

> **Note:** The `opentelemetry-instrument` wrapper automatically instruments the application and sends traces/metrics to the OTel Collector.

### Set environment variables and start OGX Client

```bash
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_SERVICE_NAME=my-ogx-app

opentelemetry-instrument python ogx-client.py
```

An example `ogx-client.py`

```python
from openai import OpenAI


def main():
    client = OpenAI(
        api_key="fake",
        base_url="http://localhost:8321/v1/",
    )
    print("hello")
    response = client.chat.completions.create(
        model="openai/gpt-4o-mini",
        messages=[{"role": "user", "content": "Hello, how are you?"}],
    )
    print("Sync response: ", response.choices[0].message.content)


if __name__ == "__main__":
    main()
```

### Explore the telemetry data

Open the following UIs in your browser:

| Service | URL | Credentials |
|---|---|---|
| **Mlflow** (traces) | [http://localhost:5001](http://localhost:5001) | N/A |
| **Jaeger** (traces) | [http://localhost:16686](http://localhost:16686) | N/A |
| **Prometheus** (metrics) | [http://localhost:9090](http://localhost:9090) | N/A |
| **Grafana** (dashboards) | [http://localhost:3000](http://localhost:3000) | admin / admin |

#### Prometheus metrics to try

The following metrics are automatically generated by OpenTelemetry auto-instrumentation:

```promql
# Total input token usage by model
sum by(gen_ai_request_model) (ogx_gen_ai_client_token_usage_sum{gen_ai_token_type="input"})

# Total output token usage by model
sum by(gen_ai_request_model) (ogx_gen_ai_client_token_usage_sum{gen_ai_token_type="output"})

# P95 HTTP server latency
histogram_quantile(0.95, rate(ogx_http_server_duration_milliseconds_bucket[5m]))

# Total HTTP request count
sum(ogx_http_server_duration_milliseconds_count)
```

#### Grafana dashboard

A pre-provisioned **OGX** dashboard is available in Grafana with panels for:

- Prompt Tokens (input token usage by model)
- Completion Tokens (output token usage by model)
- P95 / P99 HTTP Server Duration
- Total HTTP Requests

### GenAI message content capture (logs vs spans)

- `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` controls whether prompts/outputs/tool-call args are captured. **Default: false** (no content captured). Set to `true` to capture.
- Captured content is emitted as **logs** (e.g., events like `gen_ai.user.message` and `gen_ai.choice`), with `trace_id`/`span_id` for correlation.
- Spans carry structured metadata (model, finish_reason, usage tokens, latency, HTTP call, etc.) but **not** the raw text content.

### Exporter examples

**Local console (debugging):**

```bash
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true \
OTEL_TRACES_EXPORTER=console \
OTEL_LOGS_EXPORTER=console \
opentelemetry-instrument python ogx-client.py
```

**Send to Collector (recommended):**

```bash
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true \
OTEL_TRACES_EXPORTER=otlp \
OTEL_LOGS_EXPORTER=otlp \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
opentelemetry-instrument python ogx-client.py
```

### Jaeger caveat (logs)

- Jaeger’s built-in OTLP typically ingests **traces only**, not logs. If you point `OTEL_LOGS_EXPORTER=otlp` at Jaeger, logs will be rejected (e.g., 404) and you will not see message content.
- To view captured content, send logs to an OTel Collector (or another backend that supports OTLP logs). For debugging, you can also use `OTEL_LOGS_EXPORTER=console` to print logs to stdout.

### Minimal Collector example (traces → Jaeger, logs → stdout)

```yaml
receivers:
  otlp:
    protocols:
      http:
      grpc:

processors:
  batch: {}

exporters:
  jaeger:
    endpoint: localhost:14250
    tls:
      insecure: true
  logging:  # view logs in collector stdout
    loglevel: info

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [jaeger]
    logs:
      receivers: [otlp]
      processors: [batch]
      exporters: [logging]
```

Use with:

```bash
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true \
OTEL_TRACES_EXPORTER=otlp \
OTEL_LOGS_EXPORTER=otlp \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
opentelemetry-instrument python ogx-client.py
```

## Cleanup

Stop and remove all telemetry containers:

```bash
# Replace "docker" with "podman" if applicable
docker stop jaeger otel-collector prometheus grafana
docker rm jaeger otel-collector prometheus grafana
docker network rm llama-telemetry
```

## Known Issues

When OpenTelemetry auto-instrumentation is enabled, both the low-level database driver instrumentor
(e.g. `asyncpg`, `sqlite3`) and the SQLAlchemy ORM instrumentor activate simultaneously. This causes
duplicate spans and inflated traces. To prevent this, disable the driver-level instrumentors:

```bash
export OTEL_PYTHON_DISABLED_INSTRUMENTATIONS="sqlite3,asyncpg"
```

## References

- [OpenTelemetry Documentation](https://opentelemetry.io/)
- [OpenTelemetry GenAI Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-metrics/)
- [Jaeger Documentation](https://www.jaegertracing.io/)
- [Prometheus Documentation](https://prometheus.io/docs/)
- [Grafana Documentation](https://grafana.com/docs/)

---

### Overview (`src/ogx/README.md`)

# ogx

Server implementation for OGX. This is the main package that provides the runtime, built-in providers, CLI, and all server-side logic.

## Directory Structure

```text
ogx/
  core/               # Server core: routing, resolution, storage, server
  providers/           # All provider implementations (inline + remote)
  distributions/       # Pre-built distribution configurations
  cli/                 # CLI commands (ogx run, build, configure, etc.)
  models/              # Model metadata and registries
  testing/             # Test infrastructure (API recorder for record/replay)
  telemetry/           # OpenTelemetry integration
  __init__.py
  env.py               # Environment variable utilities
  log.py               # Logging configuration
```

## How It Fits Together

1. **`core/`** handles server startup, provider resolution, request routing, and storage.
2. **`providers/`** contains all provider implementations. Each provider implements a protocol defined in `ogx_api`.
3. **`distributions/`** are pre-configured YAML files that wire together specific providers for common deployment scenarios.
4. **`cli/`** provides the `ogx` command-line tool for running, building, and configuring stacks.

## Key Entry Points

- `core/server/server.py` -- FastAPI application and `main()` entry point
- `core/stack.py` -- `Stack` class that initializes and wires all components
- `core/resolver.py` -- `resolve_impls()` resolves provider dependencies and instantiates them

## Package Relationship

This package (`ogx`) depends on `ogx-api` (`src/ogx_api/`) for protocol definitions and data types. See the root [ARCHITECTURE.md](../../ARCHITECTURE.md) for the full system overview.

---

### Overview (`src/ogx_api/README.md`)

# ogx-api

API and Provider specifications for OGX - a lightweight package with protocol definitions and provider specs.

## Overview

`ogx-api` is a minimal dependency package that contains:

- **API Protocol Definitions**: Type-safe protocol definitions for OGX APIs (inference, agents, responses, etc.)
- **Provider Specifications**: Provider spec definitions for building custom providers
- **Data Types**: Shared data types and models used across the OGX ecosystem
- **Type Utilities**: Strong typing utilities and schema validation

## What This Package Does NOT Include

- Server implementation (see `ogx` package)
- Provider implementations (see `ogx` package)
- CLI tools (see `ogx` package)
- Runtime orchestration (see `ogx` package)

## Use Cases

This package is designed for:

1. **Third-party Provider Developers**: Build custom providers without depending on the full OGX server
2. **Client Library Authors**: Use type definitions without server dependencies
3. **Documentation Generation**: Generate API docs from protocol definitions
4. **Type Checking**: Validate implementations against the official specs

## Installation

```bash
pip install ogx-api
```

Or with uv:

```bash
uv pip install ogx-api
```

## Dependencies

Minimal dependencies:

- `openai>=2.5.0` - For OpenAI-compatible types
- `fastapi>=0.137.2,<1.0` - For FastAPI route definitions
- `pydantic>=2.11.9` - For data validation and serialization
- `jsonschema` - For JSON schema utilities
- `opentelemetry-sdk>=1.30.0` - For telemetry
- `opentelemetry-exporter-otlp-proto-http>=1.30.0` - For OTLP export

## Versioning

This package follows semantic versioning independently from the main `ogx` package:

- **Patch versions** (0.1.x): Documentation, internal improvements
- **Minor versions** (0.x.0): New APIs, backward-compatible changes
- **Major versions** (x.0.0): Breaking changes to existing APIs

The version is determined dynamically via `setuptools-scm` at build time.

## Usage Example

```python
from ogx_api import (
    Api,
    Inference,
    InlineProviderSpec,
    OpenAIChatCompletionRequestWithExtraBody,
)


# Use protocol definitions for type checking
class MyInferenceProvider(Inference):
    async def openai_chat_completion(
        self, request: OpenAIChatCompletionRequestWithExtraBody
    ):
        # Your implementation
        pass


# Define provider specifications
my_provider_spec = InlineProviderSpec(
    api=Api.inference,
    provider_type="inline::my-provider",
    pip_packages=["my-dependencies"],
    module="my_package.providers.inference",
    config_class="my_package.providers.inference.MyConfig",
)
```

## Relationship to ogx

The main `ogx` package depends on `ogx-api` and provides:

- Full server implementation
- Built-in provider implementations
- CLI tools for running and managing stacks
- Runtime provider resolution and orchestration

## Contributing

See the main [OGX repository](https://github.com/ogx-ai/ogx) for contribution guidelines.

## License

MIT License - see LICENSE file for details.

## Links

- [Main OGX Repository](https://github.com/ogx-ai/ogx)
- [Documentation](https://ogx.ai/)
- [Client Library](https://pypi.org/project/ogx-client/)

---

### Overview (`src/ogx_ui/README.md`)

## This is WIP

We use shadcdn/ui [Shadcn UI](https://ui.shadcn.com/) for the UI components.

## Getting Started

First, install dependencies:

```bash
npm install
```

Then, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:8322](http://localhost:8322) with your browser to see the result.

## Model filtering

The Chat Playground shows all available LLM models by default. To limit the
model dropdown, set `NEXT_PUBLIC_OGX_UI_ALLOWED_MODELS` to a comma-separated
list of model IDs:

```bash
NEXT_PUBLIC_OGX_UI_ALLOWED_MODELS=openai/gpt-4.1-mini,anthropic/claude-sonnet-4-6
```

When configured, only matching models are shown in the configured order, and
the first matching model is selected by default. If the variable is unset, the
first model in the existing sorted list is selected by default.

---

### Overview (`tests/integration/README.md`)

# Integration Testing Guide

Integration tests verify complete workflows across different providers using OGX's record-replay system.

For the list of target models per provider and their CI lanes, see [TARGET_MODELS.md](TARGET_MODELS.md).

## Quick Start

```bash
# Run all integration tests with existing recordings
uv run --group dev \
  pytest -sv tests/integration/ --stack-config=starter
```

### Provider dependencies

`scripts/integration-tests.sh` checks that the provider dependencies for the
stack config are installed — the same `ogx stack list-deps <config> |
xargs -L1 uv pip install` step CI runs — and fails early with the exact
install command when any are missing. Pass `--install-deps` to install them
automatically before running the tests.

## Configuration Options

You can see all options with:

```bash
cd tests/integration

# this will show a long list of options, look for "Custom options:"
pytest --help
```

Here are the most important options:

- `--stack-config`: specify the stack config to use. You have four ways to point to a stack:
  - **`server:<config>`** - automatically start a server with the given config (e.g., `server:starter`). This provides one-step testing by auto-starting the server if the port is available, or reusing an existing server if already running.
  - **`server:<config>:<port>`** - same as above but with a custom port (e.g., `server:starter:8322`)
  - a URL which points to a OGX distribution server
  - a distribution name (e.g., `starter`) or a path to a `config.yaml` file
  - a comma-separated list of api=provider pairs, e.g. `inference=ollama,responses=builtin`. This is most useful for testing a single API surface.
- `--env`: set environment variables, e.g. --env KEY=value. this is a utility option to set environment variables required by various providers.

Model parameters can be influenced by the following options:

- `--text-model`: comma-separated list of text models.
- `--vision-model`: comma-separated list of vision models.
- `--embedding-model`: comma-separated list of embedding models.
- `--judge-model`: comma-separated list of judge models.
- `--rerank-model`: comma-separated list of rerank models.
- `--embedding-dimension`: output dimensionality of the embedding model to use for testing. Default: 768

Each of these are comma-separated lists and can be used to generate multiple parameter combinations. Note that tests will be skipped
if no model is specified.

### Suites and Setups

- `--suite`: single named suite that narrows which tests are collected.
- Available suites:
  - `base`: collects most tests (excludes responses)
  - `responses`: collects tests under `tests/integration/responses` (needs strong tool-calling models)
  - `vision`: collects only `tests/integration/inference/test_vision_inference.py`
  - `auth`: kubernetes-auth access-control tests. Its `auth` setup is `matrix_excluded`, so this suite only ever runs under the dedicated auth workflow (which stands up the k8s auth provider) and never in the standard CI matrix
  - `connect-cli`: drives the real agent CLIs (Claude Code, Codex, OpenCode) through `ogx connect <agent>` against the mock setup. The tests self-skip unless the CLIs are installed, so they only actually run under the dedicated connect-cli workflow
- `--setup`: global configuration that can be used with any suite. Setups prefill model/env defaults; explicit CLI flags always win.
  - Available setups:
    - `ollama`: Local Ollama provider with lightweight models (sets OLLAMA_URL, uses qwen3.5:0.8b)
    - `vllm`: vLLM provider running natively on the host (sets VLLM_URL, uses Qwen/Qwen3-0.6B)
    - `gpt`: OpenAI GPT models for high-quality responses (uses gpt-4o)
    - `claude`: Anthropic Claude models for high-quality responses (uses claude-3-5-sonnet)

Examples

```bash
# Run conversations tests with GPT for high-quality responses
pytest -s -v tests/integration/conversations --stack-config=server:starter --setup=gpt

# Fast responses run with a strong tool-calling model
pytest -s -v tests/integration --stack-config=server:starter --suite=responses --setup=gpt

# Fast single-file vision run with Ollama defaults
pytest -s -v tests/integration --stack-config=server:starter --suite=vision --setup=ollama

# Base suite with VLLM for performance
pytest -s -v tests/integration --stack-config=server:starter --suite=base --setup=vllm

# Override a default from setup
pytest -s -v tests/integration --stack-config=server:starter \
  --suite=responses --setup=gpt --embedding-model=text-embedding-3-small
```

## Examples

### Testing against a Server

Run all inference tests by auto-starting a server with the `starter` config:

```bash
OLLAMA_URL=http://localhost:11434 \
  pytest -s -v tests/integration/inference \
   --stack-config=server:starter \
   --text-model=ollama/qwen3.5:0.8b \
   --embedding-model=nomic-embed-text-v1.5
```

Run tests with auto-server startup on a custom port:

```bash
OLLAMA_URL=http://localhost:11434 \
  pytest -s -v tests/integration/inference/ \
   --stack-config=server:starter:8322 \
   --text-model=ollama/qwen3.5:0.8b \
   --embedding-model=nomic-embed-text-v1.5
```

### Testing with Library Client

The library client constructs the Stack "in-process" instead of using a server. This is useful during the iterative development process since you don't need to constantly start and stop servers.

You can do this by simply using `--stack-config=starter` instead of `--stack-config=server:starter`.

### Using ad-hoc distributions

Sometimes, you may want to make up a distribution on the fly. This is useful for testing a single provider or a single API or a small combination of providers. You can do so by specifying a comma-separated list of api=provider pairs to the `--stack-config` option, e.g. `inference=remote::ollama,responses=inline::builtin`.

```bash
pytest -s -v tests/integration/inference/ \
   --stack-config=inference=remote::ollama,responses=inline::builtin \
   --text-model=$TEXT_MODELS \
   --vision-model=$VISION_MODELS \
   --embedding-model=$EMBEDDING_MODELS
```

Another example: Running Vector IO tests for embedding models:

```bash
pytest -s -v tests/integration/vector_io/ \
   --stack-config=inference=inline::sentence-transformers,vector_io=inline::sqlite-vec \
   --embedding-model=nomic-embed-text-v1.5
```

## Recording Modes

The testing system supports four modes controlled by environment variables:

### REPLAY Mode (Default)

Uses cached responses instead of making API calls:

```bash
pytest tests/integration/
```

### RECORD-IF-MISSING Mode (Recommended for adding new tests)

Records only when no recording exists, otherwise replays. This is the preferred mode for iterative development:

```bash
pytest tests/integration/inference/test_new_feature.py --inference-mode=record-if-missing
```

### RECORD Mode

**Force-records all API interactions**, overwriting existing recordings. Use with caution as this will re-record everything:

```bash
pytest tests/integration/inference/test_new_feature.py --inference-mode=record
```

### LIVE Mode

Tests make real API calls (not recorded):

```bash
pytest tests/integration/ --inference-mode=live
```

By default, the recording directory is `tests/integration/recordings`. You can override this by setting the `OGX_TEST_RECORDING_DIR` environment variable.

## Managing Recordings

### SGLang Recordings

SGLang uses Qwen3-0.6B for the `sglang` setup and
`togethercomputer/Tev1-0.8B-experimental` for `sglang-systemone`. Live recording
uses the AMX backend of the pinned SGLang CPU image. An AVX-512-only
runner can pass import but hit an illegal instruction in Qwen3 Q/K norm; Tev1
also needs the AMX gated RMSNorm path. Automatic PR recording skips unsupported
runners and
reports the skip in the job summary; manually dispatched recording fails with a
message to re-run that job. No recordings are produced in either case. Re-run the
job to request another runner. Replay uses the saved responses and does not
require AMX or a running SGLang server.

### vLLM SystemOne Recordings

The `vllm` setup uses Qwen/Qwen3-0.6B, and `vllm-systemone` uses
`togethercomputer/Tev1-0.8B-experimental`, served natively (no container) by
the pinned vLLM 0.34.0 CPU wheel against vLLM's structured decisions API
(`/v1/systemone`). Both checkpoints are pinned to immutable HuggingFace
commits, and every file is sha256-verified before use. Replay uses the saved
responses and does not require a running vLLM server.

### Model-List Recordings

`models-*.json` files record provider model-list responses
(`models-{request_hash}-{model_set_digest}.json`). Replay unions the bodies of
every digest for a request hash, so stale model catalogs accumulate one digest
per recording. `scripts/cleanup_recordings.py` prunes them:

- files whose filename hash no longer matches the current hash function are
  unreachable by any replay lookup, and
- model-set digests that add no model referenced by the test suites (recording
  requests + CI stack-config registrations) are redundant, with the
  guarantee that the kept files per (directory, request hash) still cover
  every referenced model and that each group keeps at least one file.

### Viewing Recordings

```bash
# See what's recorded
sqlite3 recordings/index.sqlite "SELECT endpoint, model, timestamp FROM recordings;"

# Inspect specific response
cat recordings/responses/abc123.json | jq '.'
```

### Re-recording Tests

#### Automated Re-recording (Recommended)

When you open a PR with new or modified tests, the recording workflow automatically:

1. Detects missing test recordings
2. Records them using ollama (no API keys needed)
3. Commits the recordings back to your PR

The workflow uses two steps for security:

- Step 1: Runs tests with read-only permissions and uploads recordings as artifacts
- Step 2: Commits recordings from artifacts (only runs trusted base repo code with write permissions)

**For PR authors:**

- Just open a PR with test changes - that's it!
- Works for both same-repo and fork PRs (if "Allow edits from maintainers" is enabled)
- Recording commits trigger tests again in replay mode to validate the recordings work

**For maintainers** - recording with providers requiring API keys (gpt, azure, bedrock):

Via GitHub UI:

1. Go to **Actions** → **Integration Tests (Record)**
2. Click **Run workflow**
3. Enter PR number and providers: `gpt,azure`

Via GitHub CLI:

```bash
# Record for a specific PR with multiple providers
gh workflow run record-integration-tests.yml \
  -f pr_number=1234 \
  -f providers="gpt,azure"

# Just gpt
gh workflow run record-integration-tests.yml \
  -f pr_number=1234 \
  -f providers="gpt"

# Record specific subdirectories or patterns
gh workflow run record-integration-tests.yml \
  -f pr_number=1234 \
  -f subdirs="agents,inference"

gh workflow run record-integration-tests.yml \
  -f pr_number=1234 \
  -f pattern="test_streaming"
```

**Forcing a full re-record:** Recordings are keyed by the SHA256 of the request body, so `record-if-missing` never overwrites existing recordings. This matters when a pinned test server is bumped, since recordings captured against the old server stay stale for as long as the request body is unchanged. To force a full re-record, dispatch with `inference_mode=record`:

```bash
gh workflow run record-integration-tests.yml \
  -f pr_number=1234 -f providers="vllm" -f inference_mode=record
```

Note that `record` overwrites all existing recordings for the selected provider/suite, producing a large recording diff on the PR branch. This option is only available via `workflow_dispatch`; `pull_request`-triggered runs always use `record-if-missing`.

**Available providers:**

- `ollama` - No API keys (auto-runs on PRs)
- `llama-cpp-server` - No API keys (auto-runs on PRs)
- `vllm` - No API keys (auto-runs on PRs; installed natively from a pinned CPU wheel)
- `text-embeddings-inference` - No API keys (auto-runs on PRs)
- `gpt` - OpenAI (requires `OPENAI_API_KEY` secret)
- `azure` - Azure OpenAI (requires `AZURE_API_KEY`, `AZURE_API_BASE` secrets)
- `bedrock` - AWS Bedrock (requires `AWS_BEARER_TOKEN_BEDROCK` secret)
- `watsonx` - IBM watsonx (requires `WATSONX_API_KEY`, `WATSONX_BASE_URL`, `WATSONX_PROJECT_ID` secrets)

**Adding new providers:**

1. Add a new entry to the `provider` matrix in `.github/workflows/record-integration-tests.yml`:

   ```yaml
   - setup: your-provider
     suite: responses
   ```

2. Add the provider's API key env var in the `Run and record tests` step:

   ```yaml
   YOUR_PROVIDER_API_KEY: ${{ matrix.provider.setup == 'your-provider' && secrets.YOUR_PROVIDER_API_KEY || '' }}
   ```

3. Add the GitHub secret in repo settings

#### Local Re-recording

```bash
# Re-record specific tests
pytest -s -v --stack-config=server:starter tests/integration/inference/test_modified.py --inference-mode=record
```

Note that when re-recording tests, you must use a Stack pointing to a server (i.e., `server:starter`). This subtlety exists because the set of tests run in server are a superset of the set of tests run in the library client.

## Writing Tests

### Basic Test Pattern

```python
def test_basic_chat_completion(ogx_client, text_model_id):
    response = ogx_client.chat.completions.create(
        model=text_model_id,
        messages=[{"role": "user", "content": "Hello"}],
    )

    # Test structure, not AI output quality
    assert response.choices[0].message is not None
    assert isinstance(response.choices[0].message.content, str)
    assert len(response.choices[0].message.content) > 0
```

### Provider-Specific Tests

```python
def test_asymmetric_embeddings(ogx_client, embedding_model_id):
    if embedding_model_id not in MODELS_SUPPORTING_TASK_TYPE:
        pytest.skip(f"Model {embedding_model_id} doesn't support task types")

    query_response = ogx_client.inference.embeddings(
        model_id=embedding_model_id,
        contents=["What is machine learning?"],
        task_type="query",
    )

    assert query_response.embeddings is not None
```

## TypeScript Client Replays

TypeScript SDK tests can run alongside Python tests when testing against `server:<config>` stacks. Set `TS_CLIENT_PATH` to the path or version of `ogx-client-typescript` to enable:

```bash
# Use the latest published npm package (responses suite)
TS_CLIENT_PATH=latest scripts/integration-tests.sh --stack-config server:ci-tests --suite responses --setup gpt

# Use local checkout from ~/.cache (recommended for development)
git clone https://github.com/ogx-ai/ogx-client-typescript.git ~/.cache/ogx-client-typescript
TS_CLIENT_PATH=~/.cache/ogx-client-typescript scripts/integration-tests.sh --stack-config server:ci-tests --suite responses --setup gpt

# Run base suite with TypeScript tests
TS_CLIENT_PATH=~/.cache/ogx-client-typescript scripts/integration-tests.sh --stack-config server:ci-tests --suite base --setup ollama
```

TypeScript tests run immediately after Python tests pass, using the same replay fixtures. The mapping between Python suites/setups and TypeScript test files is defined in `tests/integration/client-typescript/suites.json`.

If `TS_CLIENT_PATH` is unset, TypeScript tests are skipped entirely.

## Directory Structure

```text
integration/
  admin/               # Admin API tests
  agents/              # Agent orchestration tests
  batches/             # Batch processing tests
  client-typescript/   # TypeScript SDK replay tests
  common/              # Shared test utilities and recording storage
  conversations/       # Conversation persistence tests
  datasets/            # Dataset management tests
  eval/                # Evaluation tests
  files/               # File management tests
  fixtures/            # Test fixtures and data
  inference/           # Inference API tests (chat completion, embeddings, vision)
  inspect/             # Inspect API tests
  post_training/       # Post-training tests
  providers/           # Provider-specific tests
  recordings/          # Cached API responses for replay mode
  responses/           # OpenAI Responses API tests
  scoring/             # Scoring tests
  telemetry/           # Telemetry tests
  test_cases/          # Shared test case definitions
  tools/               # Tool integration tests
  vector_io/           # Vector I/O tests
  conftest.py          # Main conftest (client setup, recording mode, fixtures)
  suites.py            # Suite/setup definitions
  ci_matrix.json       # CI test matrix configuration
```

## Recording System Internals

The record/replay system is implemented in `src/ogx/testing/api_recorder.py`. Key implementation details:

- **Request hashing**: Each API call is matched to a recording by hashing its parameters (method name, model, messages, etc.). This allows replay even when test execution order changes.
- **Deterministic IDs**: During replay, resource IDs (files, vector stores, etc.) are generated deterministically using counters, so tests produce the same IDs across runs.
- **Storage format**: Recordings are stored as JSON files in provider-specific directories. An SQLite index maps request hashes to response files.
- **Streaming**: Streamed responses are recorded as complete sequences of chunks, then replayed chunk-by-chunk to faithfully reproduce streaming behavior.

---

### Overview (`tests/unit/README.md`)

# OGX Unit Tests

## Unit Tests

Unit tests verify individual components and functions in isolation. They are fast, reliable, and don't require external services.

### Prerequisites

1. **Python Environment**: Ensure you have Python 3.13+ installed
2. **uv Package Manager**: Install `uv` if not already installed

You can run the unit tests by running:

```bash
./scripts/unit-tests.sh [PYTEST_ARGS]
```

Any additional arguments are passed to pytest. For example, you can specify a test directory, a specific test file, or any pytest flags (e.g., -vvv for verbosity). If no test directory is specified, it defaults to "tests/unit", e.g:

```bash
./scripts/unit-tests.sh tests/unit/registry/test_registry.py -vvv
```

If you'd like to run for a non-default version of Python (currently 3.13), pass `PYTHON_VERSION` variable as follows:

```bash
source .venv/bin/activate
PYTHON_VERSION=3.14 ./scripts/unit-tests.sh
```

### Test Configuration

- **Test Discovery**: Tests are automatically discovered in the `tests/unit/` directory
- **Async Support**: Tests use `--asyncio-mode=auto` for automatic async test handling
- **Coverage**: Tests generate coverage reports in `htmlcov/` directory
- **Python Version**: Defaults to Python 3.13, but can be overridden with `PYTHON_VERSION` environment variable

### Coverage Reports

After running tests, you can view coverage reports:

```bash
# Open HTML coverage report in browser
open htmlcov/index.html  # macOS
xdg-open htmlcov/index.html  # Linux
start htmlcov/index.html  # Windows
```

### Directory Structure

```text
unit/
  cli/                 # CLI command tests
  conversations/       # Conversation service tests
  core/                # Core server and routing tests
  distribution/        # Distribution config tests
  files/               # File handling tests
  models/              # Model metadata tests
  prompts/             # Prompt service tests
  providers/           # Provider-specific unit tests
  rag/                 # RAG pipeline tests
  registry/            # Provider registry tests
  server/              # Server endpoint tests
  tools/               # Tool runtime tests
  utils/               # Utility function tests
  conftest.py          # Shared test fixtures
  fixtures.py          # Test data factories
```

### Writing Unit Tests

Unit tests should be fast and isolated. Prefer "fakes" (lightweight in-memory implementations) over mocks. Mocks are brittle and don't catch real integration issues.

For async tests, the test suite uses `--asyncio-mode=auto`, so you can write `async def test_*` functions directly without decorators.

---

### Overview (`src/ogx/core/README.md`)

# core

Server core for OGX: routing, provider resolution, storage, and the FastAPI server.

## Directory Structure

```text
core/
  server/              # FastAPI server, auth middleware, quota middleware
  routers/             # API-specific routers (inference, vector_io, web_search)
  routing_tables/      # Resource-to-provider mapping tables
  jobs/                # Out-of-process job execution (durable queue + worker pool)
  storage/             # KVStore and SqlStore backends
  store/               # Distribution registry (persists registered resources)
  access_control/      # Access control policy enforcement
  conversations/       # Conversation service (persistence for chat threads)
  prompts/             # Prompt service (prompt template management)
  utils/               # Config resolution, context propagation, dynamic import
  resolver.py          # Provider resolution engine: validate, sort, instantiate
  distribution.py      # Provider registry loading, API enumeration
  stack.py             # Stack class: initialization, resource registration, lifecycle
  datatypes.py         # Core data types (StackConfig, Provider, RoutableObject, etc.)
  library_client.py    # In-process client (no server needed)
  build.py             # Build config handling for container images
  configure.py         # Interactive configuration wizard
```

## Request Lifecycle

1. `server.py` receives an HTTP request and dispatches to the correct handler.
2. Authentication middleware validates the token, extracts the user identity and `tenant_id`.
3. Tenancy middleware enforces the configured mode (disabled/single/multi) and stores `tenant_id` in the request scope.
4. The handler calls a **Router** (e.g., `InferenceRouter`) which consults the **RoutingTable** to find the provider for the requested resource.
5. The router delegates to the provider implementation.
6. The provider either computes locally (inline) or calls an external service (remote).
7. Storage operations go through `AuthorizedSqlStore`, which applies tenant isolation (`WHERE tenant_id = ?`) before ABAC policy checks.

## Key Classes

- `Stack` (`stack.py`) -- Orchestrates initialization: loads config, resolves providers, registers resources, starts background tasks.
- `resolve_impls()` (`resolver.py`) -- The provider resolution engine. Validates providers against the registry, sorts by dependency order, instantiates each one.
- `CommonRoutingTableImpl` (`routing_tables/common.py`) -- Base class for all routing tables. Manages the mapping from resource identifiers to provider implementations.
- `DistributionRegistry` (`store/`) -- Persistent registry of all resources (models, vector stores, tool groups, etc.) across providers.

---

### Overview (`src/ogx/distributions/README.md`)

# distributions

Pre-built distribution configurations that wire together specific providers for common deployment scenarios.

## Directory Structure

```text
distributions/
  starter/             # General-purpose distribution with many providers enabled
  ci-tests/            # Minimal distribution for CI testing
  nvidia/              # NVIDIA NIM-based distribution
  oci/                 # Oracle Cloud Infrastructure distribution
  open-benchmark/      # Benchmarking distribution
  postgres-demo/       # PostgreSQL-backed distribution demo
  watsonx/             # IBM WatsonX distribution
  __init__.py
  template.py          # Distribution template rendering engine
```

## What Is a Distribution

A distribution is a pre-built configuration that bundles specific providers for a target environment, similar to how Kubernetes has distributions like AKS, EKS, and GKE. The core API stays the same, but each distribution wires different backends. Concretely, it is a `config.yaml` file that defines which APIs to serve, which providers to use for each API, how storage is configured, and what models/resources/datasets to register at startup.

Example from `starter/config.yaml`:

```yaml
version: 2
distro_name: starter
apis: [inference, responses, vector_io, ...]
providers:
  inference:
    - provider_id: ollama
      provider_type: remote::ollama
      config:
        base_url: ${env.OLLAMA_URL:=http://localhost:11434/v1}
```

## Environment Variable Substitution

Distribution configs use `${env.VAR:=default}` syntax for environment-driven configuration. The `${env.VAR:+value}` syntax conditionally enables providers only when the variable is set.

## Template System

`template.py` provides the `DistributionTemplate` class used to generate distribution configs programmatically. Each distribution directory can contain a template definition that `scripts/distro_codegen.py` uses to regenerate `config.yaml` files.

## Usage

Run a distribution with:

```bash
ogx run starter
# or
ogx run --config path/to/config.yaml
```

## Disabling Chat Completions Persistence

By default the `inference` store reference is enabled, so chat completion
request/response payloads are persisted and the history endpoints (`list`,
`retrieve`, `messages`) are served from it. An operator can disable that
persistence for the inference API by setting `inference.enabled: false` in a run
config:

```yaml
storage:
  stores:
    inference:
      enabled: false
```

When the store is disabled, OGX does not construct an `InferenceStore` at all:
no `inference_store` table is created and no background write workers run. Chat
completions still work for both streaming and non-streaming requests; the
history endpoints report that persistence is not configured (HTTP 501) rather
than returning an empty list or a 404. Other stores (`responses`, `datasets`,
`eval`, `files`, `prompts`, `vector_io`) stay enabled, so disabling inference
persistence is independent of the rest of the storage layer. See the storage
module README for details.

---

### Overview (`src/ogx/providers/README.md`)

# providers

All provider implementations for OGX APIs.

## Directory Structure

```text
providers/
  inline/              # In-process providers (run locally)
  remote/              # Remote service adapters (call external APIs)
  registry/            # Provider spec declarations (available_providers())
  utils/               # Shared utilities (OpenAI mixin, model registry, etc.)
  __init__.py
```

## Provider Types

- **Inline providers** (`inline/`) run computations in-process. Examples: `meta-reference` inference, `sqlite-vec` vector storage.
- **Remote providers** (`remote/`) adapt external services to the OGX API. Examples: `ollama`, `openai`, `fireworks`, `vllm`, `anthropic`.

## How Providers Are Registered

Each API has a file in `registry/` (e.g., `registry/inference.py`) with an `available_providers()` function that returns a list of `ProviderSpec` objects. At startup, `core/distribution.py` calls `get_provider_registry()` to collect all specs.

## How Providers Are Instantiated

When the server starts, `core/resolver.py` reads the run config, matches provider declarations to specs from the registry, sorts by dependencies, and calls each provider module's factory function (`get_adapter_impl()` for remote, `get_provider_impl()` for inline).

## Adding a New Provider

1. Create a directory under `inline/` or `remote/` for the appropriate API.
2. Implement the API protocol from `ogx_api`.
3. Add a `ProviderSpec` entry to the corresponding file in `registry/`.
4. Run `python scripts/provider_codegen.py` to regenerate distribution configs.

See [CONTRIBUTING.md](../../../CONTRIBUTING.md) for full details.

---

### Overview (`tests/integration/openresponses/README.md`)

# OpenResponses Conformance Recordings

This directory holds inference recordings used by the
[OpenResponses conformance CI job](../../../.github/workflows/openresponses-conformance.yml)
to replay underlying OpenAI API calls without needing a live API key.

## How recordings work

The ogx server intercepts outbound inference calls (e.g., to OpenAI) and
stores each request/response pair as a JSON file named by the SHA-256 hash of the
normalized request. In CI the server runs with `OGX_TEST_INFERENCE_MODE=replay`
and looks up those files instead of making real network calls.

## Adding or updating recordings

Use the provided script — it handles everything (installing deps, starting the
server, running the tests, and reporting what was written):

```bash
OPENAI_API_KEY=<your-key> bash scripts/record-openresponses-conformance.sh
```

Then commit the results:

```bash
git add tests/integration/openresponses/recordings/
git commit -m "chore: update OpenResponses conformance recordings"
```

## Known conformance gaps

See [`CONFORMANCE_GAPS.md`](./CONFORMANCE_GAPS.md) for a full breakdown of why
tests currently fail and what needs to change in the ogx implementation.

---

### Overview (`tests/integration/recordings/README.md`)

# Test Recording System

This directory contains recorded inference API responses used for deterministic testing without requiring live API access.

For more information, see the
[docs](https://ogx-ai.github.io/docs/contributing/testing/record-replay).
This README provides more technical information.

## Structure

- `responses/` - JSON files containing request/response pairs for inference operations

## Recording Format

Each JSON file contains:

- `request` - The normalized request parameters (method, endpoint, body)
- `response` - The response body (serialized from Pydantic models)

## Normalization

To reduce noise in git diffs, the recording system automatically normalizes fields that vary between runs but don't affect test behavior:

### OpenAI-style responses

- `id` - Deterministic hash based on request: `rec-{request_hash[:12]}`
- `created` - Normalized to epoch: `0`

### Ollama-style responses

- `created_at` - Normalized to: `"1970-01-01T00:00:00.000000Z"`
- `total_duration` - Normalized to: `0`
- `load_duration` - Normalized to: `0`
- `prompt_eval_duration` - Normalized to: `0`
- `eval_duration` - Normalized to: `0`

These normalizations ensure that re-recording tests produces minimal git diffs, making it easier to review actual changes to test behavior.

## Usage

### Replay mode (default)

Responses are replayed from recordings:

```bash
OGX_TEST_INFERENCE_MODE=replay pytest tests/integration/
```

### Record-if-missing mode (recommended for adding new tests)

Records only when no recording exists, otherwise replays. Use this for iterative development:

```bash
OGX_TEST_INFERENCE_MODE=record-if-missing pytest tests/integration/
```

### Recording mode

**Force-records all API interactions**, overwriting existing recordings. Use with caution:

```bash
OGX_TEST_INFERENCE_MODE=record pytest tests/integration/
```

### Live mode

Skip recordings entirely and use live APIs:

```bash
OGX_TEST_INFERENCE_MODE=live pytest tests/integration/
```

## Re-normalizing Existing Recordings

If you need to apply normalization to existing recordings (e.g., after updating the normalization logic):

```bash
python scripts/normalize_recordings.py
```

Use `--dry-run` to preview changes without modifying files.

---

### Overview (`docs/notebooks/nvidia/beginner_e2e/README.md`)

# Beginner Fine-tuning, Inference, and Evaluation with NVIDIA NeMo Microservices and NIM

## Introduction

This notebook contains the OGX implementation for an end-to-end workflow for running inference, customizing, and evaluating LLMs using the NVIDIA provider. The NVIDIA provider leverages the NeMo Microservices platform, a collection of microservices that you can use to build AI workflows on your Kubernetes cluster on-prem or in cloud.

### About NVIDIA NeMo Microservices

The NVIDIA NeMo microservices platform provides a flexible foundation for building AI workflows such as fine-tuning, evaluation, running inference, or applying guardrails to AI models on your Kubernetes cluster on-premises or in cloud. Refer to [documentation](https://docs.nvidia.com/nemo/microservices/latest/about/index.html) for further information.

## Objectives

This end-to-end tutorial shows how to leverage the NeMo Microservices platform for customizing Llama-3.1-8B-Instruct using data from the Stanford Question Answering Dataset (SQuAD) reading comprehension dataset, consisting of questions posed on a set of Wikipedia articles, where the answer to every question is a segment of text from the corresponding passage, or the question is unanswerable.

## Prerequisites

### Deploy NeMo Microservices

Ensure the NeMo Microservices platform is up and running, including the model downloading step for `meta/llama-3.1-8b-instruct`. Please refer to the [installation guide](https://docs.nvidia.com/nemo/microservices/latest/set-up/deploy-as-platform/index.html) for instructions.

`NOTE`: The Guardrails step uses the `llama-3.1-nemoguard-8b-content-safety` model to add content safety guardrails to user input. You can either replace this with another model you've already deployed, or deploy this NIM using NeMo Deployment Management Service. This step is similar to [NIM deployment instructions](https://docs.nvidia.com/nemo/microservices/latest/get-started/tutorials/deploy-nims.html#deploy-nim-for-llama-3-1-8b-instruct) in documentation, but with the following values:

```bash
# URL to NeMo deployment management service
export NEMO_URL="http://nemo.test"

curl --location "$NEMO_URL/v1/deployment/model-deployments" \
   -H 'accept: application/json' \
   -H 'Content-Type: application/json' \
   -d '{
      "name": "llama-3.1-nemoguard-8b-content-safety",
      "namespace": "nvidia",
      "config": {
         "model": "nvidia/llama-3.1-nemoguard-8b-content-safety",
         "nim_deployment": {
            "image_name": "nvcr.io/nim/nvidia/llama-3.1-nemoguard-8b-content-safety",
            "image_tag": "1.0.0",
            "pvc_size":   "25Gi",
            "gpu": 1,
            "additional_envs": {
               "NIM_GUIDED_DECODING_BACKEND": "fast_outlines"
            }
         }
      }
   }'
```

The NIM deployment described above should take approximately 10 minutes to go live. You can continue with the remaining steps while the deployment is in progress.

### Client-Side Requirements

Ensure you have access to:

1. A Python-enabled machine capable of running Jupyter Lab.
2. Network access to the NeMo Microservices IP and ports.

## Get Started

Navigate to the [beginner E2E tutorial](./Llama_Stack_NVIDIA_E2E_Flow.ipynb) tutorial to get started.

---

### Overview (`docs/notebooks/nvidia/tool_calling/README.md`)

# Tool Calling Fine-tuning, Inference, and Evaluation with NVIDIA NeMo Microservices and NIM

## Introduction

Tool calling enables Large Language Models (LLMs) to interact with external systems, execute programs, and access real-time information unavailable in their training data. This capability allows LLMs to process natural language queries, map them to specific functions or APIs, and populate required parameters from user inputs. It's essential for building AI agents capable of tasks like checking inventory, retrieving weather data, managing workflows, and more. It imbues generally improved decision making in agents in the presence of real-time information.

### Customizing LLMs for Function Calling

To effectively perform function calling, an LLM must:

- Select the correct function(s)/tool(s) from a set of available options.
- Extract and populate the appropriate parameters for each chosen tool from a user's natural language query.
- In multi-turn (interact with users back-and-forth), and multi-step (break its response into smaller parts) use cases, the LLM may need to plan, and have the capability to chain multiple actions together.

As the number of tools and their complexity increases, customization becomes critical for maintaining accuracy and efficiency. Also, smaller models can achieve comparable performance to larger ones through parameter-efficient techniques like [Low-Rank Adaptation (LoRA)](https://arxiv.org/abs/2106.09685). LoRA is compute- and data-efficient, which involves a smaller one-time investment to train the LoRA adapter, allowing you to reap inference-time benefits with a more efficient "bespoke" model.

### About the xLAM dataset

The Salesforce [xLAM](https://huggingface.co/datasets/Salesforce/xlam-function-calling-60k) dataset contains approximately 60,000 training examples specifically designed to enhance language models' function calling capabilities. This dataset has proven particularly valuable for fine-tuning smaller language models (1B-2B parameters) through parameter-efficient techniques like LoRA. The dataset enables models to respond to user queries with executable functions, providing outputs in JSON format that can be directly processed by downstream systems.

### About NVIDIA NeMo Microservices

The NVIDIA NeMo microservices platform provides a flexible foundation for building AI workflows such as fine-tuning, evaluation, running inference, or applying guardrails to AI models on your Kubernetes cluster on-premises or in cloud. Refer to [documentation](https://docs.nvidia.com/nemo/microservices/latest/about/index.html) for further information.

## Objectives

This end-to-end tutorial shows how to leverage the NeMo Microservices platform for customizing [Llama-3.2-1B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct) using the [xLAM](https://huggingface.co/datasets/Salesforce/xlam-function-calling-60k) function-calling dataset, then evaluating its accuracy, and finally safeguarding the customized model behavior.

The following stages will be covered in this set of tutorials:

1. [Preparing Data for fine-tuning and evaluation](./1_data_preparation.ipynb)
2. [Customizing the model with LoRA fine-tuning](./2_finetuning_and_inference.ipynb)
3. [Evaluating the accuracy of the customized model](./3_model_evaluation.ipynb)
4. [Adding Guardrails to safeguard your LLM behavior](./4_adding_safety_guardrails.ipynb)

> **Note:** The LoRA fine-tuning of the Llama-3.2-1B-Instruct model takes up to 45 minutes to complete.

## Prerequisites

### Deploy NeMo Microservices

To follow this tutorial, you will need at least two NVIDIA GPUs, which will be allocated as follows:

- **Fine-tuning:** One GPU for fine-tuning the `llama-3.2-1b-instruct` model using NeMo Customizer.
- **Inference:** One GPU for deploying the `llama-3.2-1b-instruct` NIM for inference.

`NOTE`: Notebook [4_adding_safety_guardrails](./4_adding_safety_guardrails.ipynb) asks the user to use one GPU for deploying the `llama-3.1-nemoguard-8b-content-safety` NIM to add content safety guardrails to user input. This will re-use the GPU that was previously used for finetuning in notebook 2.

Refer to the [platform prerequisites and installation guide](https://docs.nvidia.com/nemo/microservices/latest/get-started/platform-prereq.html) to deploy NeMo Microservices.

### Deploy `llama-3.2-1b-instruct` NIM

This step is similar to [NIM deployment instructions](https://docs.nvidia.com/nemo/microservices/latest/get-started/tutorials/deploy-nims.html#deploy-nim-for-llama-3-1-8b-instruct) in documentation, but with the following values:

```bash
# URL to NeMo deployment management service
export NEMO_URL="http://nemo.test"

curl --location "$NEMO_URL/v1/deployment/model-deployments" \
   -H 'accept: application/json' \
   -H 'Content-Type: application/json' \
   -d '{
      "name": "llama-3.2-1b-instruct",
      "namespace": "meta",
      "config": {
         "model": "meta/llama-3.2-1b-instruct",
         "nim_deployment": {
            "distro_name": "nvcr.io/nim/meta/llama-3.2-1b-instruct",
            "image_tag": "1.8.1",
            "pvc_size":   "25Gi",
            "gpu":       1,
            "additional_envs": {
               "NIM_GUIDED_DECODING_BACKEND": "fast_outlines"
            }
         }
      }
   }'
```

The NIM deployment described above should take approximately 10 minutes to go live. You can continue with the remaining steps while the deployment is in progress.

### Managing GPU Resources for Model Deployment (If Applicable)

If you previously deployed the `meta/llama-3.1-8b-instruct` NIM during the [Beginner Tutorial](https://docs.nvidia.com/nemo/microservices/latest/get-started/platform-prereq.html), and are running on a cluster with at most two NVIDIA GPUs, you will need to delete the previous `meta/llama-3.1-8b-instruct` deployment to free up resources. This ensures sufficient GPU availability to run the `meta/llama-3.2-1b-instruct` model while keeping one GPU available for fine-tuning, and another for the content safety NIM.

```bash
export NEMO_URL="http://nemo.test"

curl -X DELETE "$NEMO_URL/v1/deployment/model-deployments/meta/llama-3.1-8b-instruct"
```

### Client-Side Requirements

Ensure you have access to:

1. A Python-enabled machine capable of running Jupyter Lab.
2. Network access to the NeMo Microservices IP and ports.

### Get access to the xLAM dataset

- Go to [xlam-function-calling-60k](https://huggingface.co/datasets/Salesforce/xlam-function-calling-60k) and request access, which should be granted instantly.
- Obtain your [Hugging Face access token](https://huggingface.co/docs/hub/en/security-tokens).

## Get Started

Navigate to the [data preparation](./1_data_preparation.ipynb) tutorial to get started.

## Other Notes

### About NVIDIA NIM

- The workflow showcased in this tutorial for tool calling fine-tuning is tailored to work with NVIDIA NIM for inference. It won't work with other inference providers (for example, vLLM, SG Lang, TGI).
- For improved inference speeds, we need to use NIM with `fast_outlines` guided decoding system. This is the default if NIM is deployed with the NeMo Microservices Helm Chart. However, if NIM is deployed separately, then users need to set the `NIM_GUIDED_DECODING_BACKEND=fast_outlines` environment variable.

### Limitations with Tool Calling

If you decide to use your own dataset or implement a different data preparation approach:

- There may be a response delay issue in tool calling due to incomplete type info. Tool calls might take over 30 seconds if descriptions for `array` types lack `items` specifications, or if descriptions for `object` types lack `properties` specifications. As a workaround, make sure to include these details (`items` for `array`, `properties` for `object`) in tool descriptions.
- Response Freezing in Tool Calling (Too Many Parameters): Tool calls will freeze the NIM if a tool description includes a function with more than 8 parameters. As a workaround, ensure functions defined in tool descriptions use 8 or fewer parameters. If this does occur, it requires the NIM to be restarted. This will be resolved in the next NIM release.

---

### Overview (`src/ogx/core/jobs/README.md`)

# Job Execution Substrate

Runs provider work in a **separate process** instead of the server's event loop, and
makes that work **durable** so it survives restarts. Providers opt in with
`execution_mode: worker` on their `InlineProviderSpec`; today only the
`file_processors` API uses it (large/slow file parsing must not block the server).

## How it fits together

```text
server process                         worker process(es)
--------------                         ------------------
FileProcessorJobProxy  --enqueue-->  ┌──────────────┐  --lease-->  real provider impl
 (JobBackedProxy)        [ jobs ]    │  JobQueue    │              (rebuilt from a
                          table  <---│  (queue.py)  │<--complete-- ProviderDescriptor)
  process_file()  <--poll result---  └──────────────┘                (worker.py)
```

- **`queue.py` — `JobQueue`**: a durable queue backed by a SQL store. The queue table
  *is* the IPC channel between the server and its workers. Leasing is an atomic guarded
  `UPDATE` so two workers never run the same job; expired leases are reclaimed (a crashed
  worker's job is retried without exceeding its attempt budget). Job control queries are
  scoped by API, provider, principal, and tenant. Composite indexes support leasing and
  cursor pagination, and periodic maintenance expires terminal rows after seven days.
- **`worker.py` — `WorkerPool` + worker loop**: spawns OS processes (spawn context, so a
  fresh interpreter and its own GIL). Each worker rebuilds the real provider impl — and its
  direct API dependencies — from a `ProviderDescriptor`, then leases → executes → reports.
  Descriptors preserve secret config values and access policies, sibling providers are wired
  after reconstruction, and the enqueue-time authenticated identity is restored for each
  invocation and terminal cleanup. The parent supervises crashed workers, restarts them with
  bounded backoff, and exposes pool failure through the stack health endpoints.
- **`proxy.py` — `JobBackedProxy`**: the API-agnostic proxy the server mounts in place of a
  worker-mode provider. It only enqueues and reads job state (`_enqueue`, `_run_blocking`,
  `_get`, `_cancel`, `_list`). APIs register a proxy factory via `register_worker_proxy`;
  the resolver looks one up by API (`WORKER_PROXY_FACTORIES`) — nothing here is per-API.
- **`file_processor_proxy.py` — `FileProcessorJobProxy`**: the thin, file-processor-specific
  adapter. It keeps `process_file` compatible with the stable `FileProcessors` provider
  protocol while exposing job lifecycle methods as an optional server-side capability. It
  stages direct uploads into Files and deletes those temporary files when jobs become terminal.
  Cleanup itself is durably claimed and leased, so another maintenance pass retries it after
  a worker crash or transient storage failure. Job listings are lightweight, owner-scoped,
  and cursor-paginated.
- **`dispatch.py`**: per-`(api, method)` (de)serialization of payloads and results. Add a
  new worker-backed method by adding one entry.
- **`models.py`**: `JobRecord` (persisted form) and `ProviderDescriptor` (how a worker
  rebuilds an impl). The public job shape is `ogx_api.common.job_types.Job`.
- **`runtime.py` / `bootstrap.py`**: process-global handle to the queue + pool, and the
  stack-side construction of them (owned by `Stack`, started after provider resolution,
  shut down on stack shutdown).

## Data plane

Job payloads never carry file bytes. Direct uploads are staged into the Files API and the
job carries only a `file_id`; the worker reads the bytes back through its own (rebuilt)
Files provider. The queue stays small and the same shared storage backs both processes.

## Notes

- The queue uses `get_system_sqlstore()` (a plain, non-authorized store) because it is
  internal infrastructure shared across processes. The job layer persists the trusted
  authenticated identity and applies explicit API/provider/principal/tenant predicates to
  every user-facing read or mutation; workers use unscoped operations only for leasing and
  terminal state transitions.
- Because workers talk to the shared DB rather than the server directly, moving workers
  off-box later is an extension of this boundary, not a rewrite.
- Auto-routed APIs cannot yet be reconstructed inside workers. Optional auto-routed
  dependencies are omitted; a Docling worker configured with `vlm_model` fails startup
  clearly instead of silently disabling VLM processing. Run that provider inline until
  worker-side inference routing is supported.

---

### Overview (`src/ogx/core/routing_tables/README.md`)

# routing_tables

Resource-to-provider mapping tables. Each routing table tracks which provider owns which resource for a given API.

## Directory Structure

```text
routing_tables/
  __init__.py            # Factory functions: get_routing_table_impl(), get_auto_router_impl()
  common.py              # CommonRoutingTableImpl base class
  models.py              # ModelsRoutingTable (models -> inference providers)
  vector_stores.py       # VectorStoresRoutingTable
  web_search.py          # WebSearchRoutingTable (web_search_providers -> web_search)
```

## How Routing Works

Each auto-routed API has a paired routing table API (see `builtin_automatically_routed_apis()` in `core/distribution.py`). For example:

- `Api.models` (routing table) is paired with `Api.inference` (router)
- When a model is registered, the routing table records which provider owns it
- When an inference request arrives, the router asks the routing table for the provider that handles the requested model

## CommonRoutingTableImpl

`CommonRoutingTableImpl` in `common.py` is the base class for all routing tables. It provides:

- Resource registration and unregistration with provider tracking
- Resource lookup by identifier with access control enforcement
- Persistence via `DistributionRegistry` (survives server restarts)
- Provider initialization: on startup, calls each provider's list method to discover pre-existing resources

## Factory Functions

`__init__.py` exports two factory functions:

- `get_routing_table_impl(api, ...)` -- Creates the appropriate routing table for the given API
- `get_auto_router_impl(api, routing_table, ...)` -- Creates the router that uses the routing table to dispatch requests

---

### Overview (`src/ogx/core/server/README.md`)

# server

FastAPI server implementation for OGX.

## Directory Structure

```text
server/
  __init__.py
  server.py                    # Main FastAPI app, route dispatch, SSE streaming, lifespan
  auth.py                      # AuthenticationMiddleware (Bearer token validation)
  auth_providers.py            # Auth provider implementations (Kubernetes, custom endpoint, local API key)
  metrics.py                   # RequestMetricsMiddleware (per-API request metrics)
  routes.py                    # Route initialization and matching from FastAPI routers
  fastapi_router_registry.py   # Auto-discovery of FastAPI routers from ogx_api packages
```

## How It Works

### Server Startup

1. `main()` in `server.py` resolves the config, creates a `StackApp` (subclass of `FastAPI`).
2. The lifespan context awaits `stack.initialize()` (provider resolution, resource registration), then registers routers.
3. The lifespan starts background tasks (e.g., periodic registry refresh).

### Route Registration

Routes are defined as native FastAPI routers. `fastapi_router_registry.py` auto-discovers router factories by scanning `ogx_api.<api>.fastapi_routes` modules for `create_router` functions. During lifespan startup, `server.py` calls `build_fastapi_router()` for each enabled API and includes the resulting router in the FastAPI app. External APIs can also register router factories via `register_external_api_routers()`.

### Middleware

- **`RequestMetricsMiddleware`** (`metrics.py`): Tracks per-API request counts and latency metrics. Runs as the outermost middleware.
- **`AuthenticationMiddleware`** (`auth.py`): Validates Bearer tokens using a configured auth provider (Kubernetes, custom endpoint, local API key). Extracts user identity, attributes, and `tenant_id` for access control. Each auth provider resolves `tenant_id` from its source (JWT claim, HTTP header, K8s claim, or custom endpoint field). The local API key provider returns attributes (`roles`, `teams`) but **does not** resolve `tenant_id` — it only supports `single` or `disabled` tenancy modes. Endpoints can opt out by setting `openapi_extra={PUBLIC_ROUTE_KEY: True}` on their route.
- **`TenancyMiddleware`** (`auth.py`): Enforces the configured tenancy mode after authentication. In `disabled` mode: passthrough. In `single` mode: overrides `tenant_id` to the configured default (works with or without auth). In `multi` mode: rejects requests with no `tenant_id` (401).
- **`RouteAuthorizationMiddleware`** (`auth.py`): Enforces route-level access policies based on user roles.
- **`ClientVersionMiddleware`** (`server.py`): Rejects requests from clients with incompatible major.minor versions.
- **`ProviderDataMiddleware`** (`server.py`): Sets up request context for provider data propagation and test context.

### Metrics Export

OTel metrics can be exported two ways, independently and simultaneously:

- **OTLP push** — set `OTEL_EXPORTER_OTLP_ENDPOINT` to push metrics to an OTel Collector.
- **Metrics scrape endpoint** — set `OGX_METRICS_ENDPOINT_ENABLED` (`1`/`true`/`yes`/`on`) to
  expose all metrics in Prometheus exposition format, suitable for scrape-based monitoring
  systems. Metrics are served by a standalone HTTP server on a dedicated port
  (`OGX_METRICS_PORT`, default `9464`; bind address `OGX_METRICS_HOST`, default `127.0.0.1`),
  separate from the main API. It binds to loopback by default; set `OGX_METRICS_HOST` (e.g.
  `0.0.0.0`) to expose it to other hosts or pods. Keeping the scrape endpoint off the API
  port means collectors need no API authentication and the metrics are not reachable by
  regular API consumers.

Telemetry is configured by `ogx.telemetry.initialize_telemetry()`, called from
`Stack.initialize()` (server and library modes). It does not run at import, so non-serving
commands (e.g. `ogx stack list-deps`) neither configure telemetry nor open a network port.
When ogx is launched under `opentelemetry-instrument`, the auto-instrumentation owns the
global `MeterProvider` and manages OTLP export; in that case the scrape reader is added to
the existing provider instead of installing a competing one, so ogx metrics still reach the
scrape endpoint.

### Response Handling

- Non-streaming responses return JSON via FastAPI's standard response handling.
- Streaming responses use Server-Sent Events (SSE) via `StreamingResponse`, with `create_sse_event()` serializing each chunk.
- Exceptions are translated to appropriate HTTP status codes by `translate_exception()`.

---

### Overview (`src/ogx/core/storage/README.md`)

# storage

Storage backends for OGX: key-value stores and SQL stores.

## Directory Structure

```text
storage/
  kvstore/             # Key-value store backends
    __init__.py
    config.py          # KVStore config classes
    kvstore.py         # KVStore factory and base implementation
    sqlite/            # SQLite KV backend (aiosqlite)
    redis/             # Redis KV backend
    postgres/          # PostgreSQL KV backend
    mongodb/           # MongoDB KV backend
  sqlstore/            # SQL store backends (SQLAlchemy-based)
    __init__.py
    sqlstore.py        # SqlStore factory and config
    sqlalchemy_sqlstore.py  # SQLAlchemy implementation
    authorized_sqlstore.py  # SqlStore with access control
  __init__.py
  datatypes.py         # Storage config types (StorageBackendType, KVStoreReference, etc.)
```

## KVStore

The `KVStore` interface provides simple key-value operations (`get`, `set`, `delete`, `keys`). Values are strings (typically JSON-serialized). Keys can be namespaced.

Backends: SQLite (default), Redis, PostgreSQL, MongoDB.

Used by: distribution registry, quota middleware, provider state persistence.

## SqlStore

The `SqlStore` interface provides typed table operations with column definitions, filtering, and pagination. Built on SQLAlchemy for portability.

Backends: SQLite (default), PostgreSQL.

Used by: inference store (chat completion logs), conversations, prompts.

### AuthorizedSqlStore

`authorized_sqlstore.py` wraps a `SqlStore` with two enforcement layers applied to every operation:

1. **Tenant isolation** -- when tenancy is enabled (`single` or `multi` mode), a `tenant_id` column is added to every table. Writes stamp the current user's `tenant_id`; all reads and mutations include a non-bypassable `WHERE tenant_id = ?` filter. In `multi` mode, missing tenant context results in default deny (empty results). Client-supplied `tenant_id` in data payloads is stripped and replaced with the authenticated value.

2. **ABAC access control** -- `owner_principal` and `access_attributes` columns support policy-based rules (e.g., `user is owner`). These operate within a tenant boundary.

The tenancy mode is set process-wide during startup via `set_default_tenancy_mode()` in `stack.py`.

### Migrations

`SqlStore` exposes primitives for in-place, idempotent table migrations (currently used to move
the conversation items table from a single-`id` primary key to a `(conversation_id, id)` composite
key): `table_exists`, `primary_key_columns`, `rename_table`, `copy_missing_rows` (an anti-join
insert that is a no-op for rows already present), and `insert_do_nothing` (an insert that skips
conflicting rows). The conversation migration runs on every boot, is flagged in a
`conversation_migrations` table so the one-time backfill happens only once, and is written to be
safe when several server workers start migrating the same database at once: each step is
idempotent, and a worker that loses a DDL race to a sibling retries and re-reads the migrated
state rather than failing its boot.

## Configuration

Storage is configured in `StackConfig.storage` via `StorageConfig`. The `stores` field contains typed references (`KVStoreReference`, `SqlStoreReference`, `InferenceStoreReference`) that point to specific backend configurations.

See `datatypes.py` for all config types and `StorageBackendType` for the enum of supported backends.

### Inference Store (enabled flag)

Setting `inference.enabled: false` on the inference store reference explicitly
disables Chat Completions persistence. Omitting the flag (or the whole
reference) keeps the store enabled for backward compatibility, and setting the
reference itself to `null` remains a configuration error.

When disabled, no `InferenceStore` is constructed, no `inference_store` table is
created, and no background write workers run. Streaming and non-streaming Chat
Completions continue to work. The history endpoints (`list`, `retrieve`, and
`messages`) report that persistence is not configured (HTTP 501).

Other stores (`responses`, `datasets`, `eval`, `files`, `prompts`, `vector_io`)
are unaffected by disabling the inference store.

---

### Overview (`src/ogx/providers/inline/README.md`)

# inline providers

In-process provider implementations that run locally within the OGX server.

## Directory Structure

```text
inline/
  responses/           # Responses API (builtin: tool calling, multi-turn conversations)
  batches/             # Batch processing for async job execution
  inference/           # Local inference (sentence-transformers, transformers)
  ios/                 # iOS on-device inference
  vector_io/           # Vector storage (sqlite-vec, faiss, chroma, milvus, qdrant)
  files/               # File storage and management
  file_processor/      # File processing (text extraction, etc.)
  skills/              # Skills API (versioned skill bundle management)
  __init__.py
```

## What Makes a Provider "Inline"

Inline providers run in the same process as the server. They are declared with `InlineProviderSpec` and their `provider_type` starts with `inline::` (e.g., `inline::meta-reference`).

Their factory function is typically named `get_provider_impl()` and returns an instance implementing the relevant protocol from `ogx_api`.

## Key Inline Providers

- **`responses/builtin`** -- Implements the OpenAI Responses API. Handles tool calling loops, multi-turn conversations, and streaming.
- **`inference/sentence_transformers`** -- Runs embedding models using the sentence-transformers library.
- **`inference/transformers`** -- Runs Llama models locally using the transformers library.
- **`vector_io/sqlite_vec`** -- SQLite-based vector storage using the sqlite-vec extension.
- **`skills/builtin`** -- Manages versioned skill bundles (zip archives with SKILL.md manifests). Stores bundles via the Files API and metadata in KVStore.
- **`web_search/placeholder`** -- Placeholder backend for the web_search API. Performs no search; invocations return a "not available" notice. Registered by `ogx go` when no web search provider is configured.

---

### Overview (`src/ogx/providers/registry/README.md`)

# registry

Provider spec declarations. Each file defines which providers are available for a given API.

## Directory Structure

```text
registry/
  __init__.py
  batches.py           # Batch processing providers
  file_processors.py   # File processor providers
  files.py             # File storage providers
  inference.py         # Inference providers (20+ remote + 2 inline)
  interactions.py      # Interaction providers
  responses.py         # Responses API providers (inline::builtin)
  skills.py            # Skills API providers (inline::builtin)
  vector_io.py         # Vector I/O providers
  web_search.py        # Web search backends
```

## How It Works

Each file exports an `available_providers()` function that returns a list of `ProviderSpec` objects (`InlineProviderSpec` or `RemoteProviderSpec`). These specs declare:

- `api` -- which API the provider implements
- `provider_type` -- unique identifier (e.g., `"remote::ollama"`)
- `module` -- Python module path containing the provider implementation
- `config_class` -- fully qualified path to the provider's Pydantic config class
- `pip_packages` -- additional pip dependencies needed at runtime
- `provider_data_validator` -- optional runtime data validator for per-request credentials

## Usage

At server startup, `core/distribution.py:get_provider_registry()` calls `available_providers()` from each file and builds a mapping of `Api -> provider_type -> ProviderSpec`. The resolver uses this mapping to validate and instantiate providers from the run config.

---

### Overview (`src/ogx/providers/remote/README.md`)

# remote providers

Remote provider adapters that connect OGX APIs to external services.

## Directory Structure

```text
remote/
  inference/           # Remote inference adapters
    anthropic/         # Anthropic Claude
    azure/             # Azure OpenAI
    bedrock/           # AWS Bedrock
    cerebras/          # Cerebras Cloud
    databricks/        # Databricks
    fireworks/         # Fireworks AI
    gemini/            # Google Gemini
    groq/              # Groq
    llama_cpp_server/  # llama.cpp server
    llama_openai_compat/ # Generic OpenAI-compatible endpoints
    nvidia/            # NVIDIA NIM
    oci/               # Oracle Cloud Infrastructure
    ollama/            # Ollama
    openai/            # OpenAI
    runpod/            # RunPod
    sambanova/         # SambaNova
    text_embeddings_inference/ # HuggingFace Text-Embeddings-Inference
    together/          # Together AI
    vertexai/          # Google Vertex AI
    vllm/              # vLLM
    watsonx/           # IBM WatsonX
  vector_io/           # Remote vector storage (chroma, elasticsearch, milvus, pgvector, qdrant, weaviate, etc.)
  files/               # Remote file storage (openai, s3)
  web_search/          # Web search backends (bing, brave, exa, nimble, searchapi, serply, tavily)
  __init__.py
```

## What Makes a Provider "Remote"

Remote providers adapt an external service to the OGX API. They are declared with `RemoteProviderSpec` and their `provider_type` starts with `remote::` (e.g., `remote::ollama`).

Their factory function is typically named `get_adapter_impl()` and returns an instance implementing the relevant protocol from `ogx_api`.

## Common Pattern

Most remote inference providers extend `OpenAIMixin` from `providers/utils/inference/openai_mixin.py`, which provides a standard implementation of OpenAI-compatible chat completion, completion, and embedding endpoints using the `AsyncOpenAI` client. The provider only needs to supply the base URL and any provider-specific configuration.

---

### Overview (`src/ogx/providers/utils/README.md`)

# utils

Shared utilities used across multiple providers.

## Directory Structure

```text
utils/
  bedrock/             # AWS Bedrock-specific utilities
  inference/           # Inference utilities (OpenAI mixin, model registry, prompt adapter)
  common/              # Common utilities shared across provider types
  datasetio/           # Dataset I/O utilities
  files/               # File handling utilities
  memory/              # Memory/vector store utilities
  responses/           # Responses API store
  scoring/             # Scoring utilities
  tools/               # Tool utilities (MCP client, TTL cache)
  vector_io/           # Vector I/O utilities
  __init__.py
```

## Key Components

### OpenAI Mixin (`inference/openai_mixin.py`)

`OpenAIMixin` is the most important shared utility. It provides a standard implementation of OpenAI-compatible endpoints (chat completion, completion, embeddings) using the `AsyncOpenAI` client. Most remote inference providers extend this mixin and only need to implement `get_base_url()` and optionally customize behavior via class attributes.

### Model Registry (`inference/model_registry.py`)

`ModelRegistryHelper` manages the mapping between OGX model identifiers and provider-specific model IDs. Providers declare their supported models as `ProviderModelEntry` objects.

### Prompt Adapter (`inference/prompt_adapter.py`)

Converts between OGX's message format and provider-specific formats. Handles image content localization, tool call formatting, and other provider-specific adaptations.

### MCP Client (`tools/mcp.py`)

Model Context Protocol client used by tool runtime providers to connect to MCP servers.

### Responses Store (`responses/responses_store.py`)

Persistent storage for OpenAI Responses API objects, used by the agents provider.

---

### Overview (`src/ogx/providers/inline/responses/README.md`)

# agents / responses (inline provider)

The `builtin` agents provider implements the OpenAI Responses API. This directory is being renamed from `agents` to `responses` (see PR #5195).

## Directory Structure

```text
agents/
  builtin/
    __init__.py        # Provider factory (get_provider_impl)
    impl.py            # Core orchestration logic
    config.py          # BuiltinResponsesImplConfig
    responses/         # OpenAI Responses API implementation
      __init__.py
      openai_responses.py   # Responses API handler
      streaming.py          # SSE streaming for responses
      tool_executor.py      # Tool call execution engine
      types.py              # Response-specific types
      utils.py              # Response utilities
  __init__.py
```

## What It Does

This provider handles:

- **Agent turns**: Multi-step inference with tool calling loops. The agent calls the inference provider, executes any requested tools, feeds results back, and repeats until the model produces a final response.
- **OpenAI Responses API**: Implements the `/v1/responses` endpoint, which provides a stateful, agentic interface compatible with OpenAI's Responses API. Supports built-in tools (web search, code interpreter, file search) and custom function tools.
- **Guardrails**: Optionally runs input and output through an external moderation endpoint for content safety.

## Dependencies

This provider depends on:

- `Api.inference` -- for LLM calls
- `Api.vector_io` -- for file search / RAG
- `Api.files` -- for file management
- `Api.web_search` (optional) -- for web search tool execution

---

### Overview (`src/ogx/providers/remote/inference/README.md`)

# remote inference adapters

Remote inference provider adapters that connect to external AI services.

## Directory Structure

```text
inference/
  anthropic/                # Anthropic Claude models
  azure/                    # Azure OpenAI Service
  bedrock/                  # AWS Bedrock
  cerebras/                 # Cerebras Cloud
  databricks/               # Databricks Model Serving
  fireworks/                # Fireworks AI
  gemini/                   # Google Gemini API
  groq/                     # Groq LPU inference
  llama_cpp_server/         # llama.cpp server/router (serves llm, embedding, and SystemOne decision models)
  llama_openai_compat/      # Generic OpenAI-compatible endpoints
  nvidia/                   # NVIDIA NIM
  oci/                      # Oracle Cloud Infrastructure GenAI
  ollama/                   # Ollama (local model serving, including SystemOne decision models)
  openai/                   # OpenAI API
  runpod/                   # RunPod cloud GPU
  sambanova/                # SambaNova
  sglang/                   # SGLang inference server (serves llm, embedding, and SystemOne decision models)
  text_embeddings_inference/ # HuggingFace Text-Embeddings-Inference (embedding models)
  tgi/                      # HuggingFace TGI and Inference API
  together/                 # Together AI
  typesafe/                 # TypeSafe SystemOne (judgment) models
  vertexai/                 # Google Vertex AI
  vllm/                     # vLLM inference server (serves llm, embedding, and SystemOne decision models)
  watsonx/                  # IBM WatsonX
  __init__.py
```

## Common Pattern

Most remote inference providers follow the same pattern:

1. **Config class** -- A Pydantic model with `base_url`, `api_key`, and provider-specific settings.
2. **Implementation class** -- Extends `OpenAIMixin` from `providers/utils/inference/openai_mixin.py`.
3. **Model registry** -- Declares supported models as `ProviderModelEntry` objects.
4. **Factory function** -- `get_adapter_impl()` instantiates the provider with config and dependencies.

`OpenAIMixin` provides standard implementations of `openai_chat_completion()`, `openai_completion()`, and `openai_embeddings()` using the `AsyncOpenAI` client. The provider typically just needs to implement `get_base_url()`.

## Provider Data

Some providers support per-request credentials via `provider_data_validator`. This allows API keys to be passed in request headers rather than server config, useful for multi-tenant deployments.

## Adding a New Inference Provider

1. Create a directory under `inference/` with `__init__.py`, `config.py`, and the implementation.
2. Extend `OpenAIMixin` if the service is OpenAI-compatible.
3. Add a `RemoteProviderSpec` entry to `providers/registry/inference.py`.
4. Define supported models using `ProviderModelEntry` in a model registry.

---

### Overview (`src/ogx/providers/utils/inference/README.md`)

# inference utilities

Shared utilities for inference providers: the OpenAI mixin, model registry, prompt adaptation, and streaming helpers.

## Directory Structure

```text
inference/
  __init__.py
  openai_mixin.py         # OpenAIMixin: standard OpenAI-compatible endpoint implementations
  openai_compat.py        # OpenAI compatibility helpers (parameter preparation, stream options)
  model_registry.py       # ModelRegistryHelper and ProviderModelEntry for model ID mapping
  prompt_adapter.py       # Message format conversion, image localization, tool formatting
  stream_utils.py         # Streaming response helpers
  inference_store.py      # InferenceStore for persisting chat completion logs
  http_client.py          # HTTP client utilities
  models_dev_registry.py  # Shared classify_model() for embedding/rerank model classification
  server_signature.py     # Engine verification via native endpoints (/props, /info)
  anthropic_mixin.py      # AnthropicMixin: native /v1/messages passthrough shared by providers
  anthropic_translation.py # Anthropic<->OpenAI translation and the SSE passthrough stream helper
  network_config.py       # NetworkConfig model and httpx client kwargs builder
  systemone.py            # Shared SystemOne (judgment) call path over the typesafe SDK
```

## OpenAIMixin (`openai_mixin.py`)

The central utility class. Provides implementations of:

- `openai_chat_completion()` -- Chat completions via `AsyncOpenAI`
- `openai_completion()` -- Text completions via `AsyncOpenAI`
- `openai_embeddings()` -- Embedding generation via `AsyncOpenAI`

Customizable via class attributes:

- `overwrite_completion_id` -- Replace response IDs with internal IDs
- `download_images` -- Download and base64-encode images for providers that need it
- `supports_stream_options` -- Disable stream_options for providers that don't support it

Providers extend this mixin and implement `get_base_url()` to point at their API. It also
provides `anthropic_messages()`/`anthropic_count_tokens()` via translation to OpenAI chat
completions, which is the default for providers without a native Messages endpoint.

## AnthropicMixin (`anthropic_mixin.py`)

Shared implementation of the native Anthropic Messages API passthrough for providers whose
server exposes its own `/v1/messages` endpoint (Anthropic, Meta AI, Ollama, vLLM, Fireworks, DeepSeek).
It extends `OpenAIMixin` and shadows the translation fallback with a direct forward of the
request body, which the translation cannot represent (extended thinking, cache control, tool
search). It also defines `AnthropicAPIError`, which carries the upstream HTTP status and
message so the `/v1/messages` router can return them instead of a generic 500.

Providers declare it before `OpenAIMixin` in the base list and configure it with
`ClassVar` class attributes (so they stay class variables rather than pydantic fields):

- `anthropic_auth_style` -- `"x-api-key"` (default) or `"bearer"`
- `anthropic_no_key_placeholder` -- value sent as the auth header when no key is configured;
  `None` omits the header for the `"bearer"` style and raises `ValueError` (with a
  provider-data hint) for the `"x-api-key"` style
- `anthropic_messages_timeout` / `anthropic_count_tokens_timeout` -- default client timeouts
  in seconds; a configured `network.timeout` takes precedence

Providers without a `/v1/messages/count_tokens` endpoint (Fireworks, DeepSeek) override
`_anthropic_count_tokens_url()` to return `None`; counting then falls through to
`OpenAIMixin`'s default, which counts by calling `anthropic_messages` with `max_tokens=1`.

DeepSeek's Anthropic surface lives at a separate host path than its OpenAI-compatible one
(config `anthropic_base_url`), so it also overrides `_get_anthropic_base_url()`; the default
builds the URL from `get_base_url()` with a trailing `/v1` stripped.

## ModelRegistryHelper (`model_registry.py`)

Maps between OGX model identifiers and provider-specific model IDs. Each provider declares its supported models as a list of `ProviderModelEntry` objects with aliases. The helper resolves user-facing model names to the provider's internal identifiers.

## Prompt Adapter (`prompt_adapter.py`)

Handles format conversion between OGX's message types and provider-specific formats. Key functions:

- `localize_image_content()` -- Downloads remote images and converts to base64
- Tool call formatting for different provider conventions

## InferenceStore (`inference_store.py`)

Persists chat completion request/response pairs to the SqlStore. Used by the inference router to enable conversation history retrieval via the Conversations API.

## Model classification (`models_dev_registry.py`)

`classify_model(identifier, provider_id)` classifies embedding and rerank models for remote adapters whose `/v1/models` response has no model task/type field (vLLM, llama.cpp servers), returning `None` when `identifier` is neither so callers can fall back to their own default classification. Only embedding classification consults the [models.dev](https://models.dev) registry, enriching `Model.metadata` with `embedding_dimension`/`context_length` when it has an entry, and falling back to a name heuristic (`"embed"` in the identifier) otherwise; models.dev has no rerank entries, so rerank classification is a name heuristic (`"rerank"` in the identifier) only.

## SystemOne judgment helper (`systemone.py`)

Shared call path for SystemOne (judgment) providers that speak the TypeSafe wire protocol:
the TypeSafe cloud API and local engines that serve `POST /v1/systemone` natively (Ollama,
llama.cpp server, SGLang, vLLM). `systemone_judge()` wraps the official `typesafe_sdk`
client, maps SDK errors to `SystemOneProviderError` (with the upstream status code), and
re-validates the raw response body into OGX's `SystemOneResponse` wire model, after dropping
any per-engine extension/diagnostic fields the caller names via `extension_fields` /
`extension_fields_by_type` / `top_level_extension_fields` (e.g. SGLang's `x_label_mass`, or
vLLM's `id`/`object`/`created`/`diagnostics` and its extra fields on `noul` answers).
`LOCAL_ENGINE_API_KEY` is the placeholder key for engines that ignore `Authorization`.

## Server signature verification (`server_signature.py`)

`verify_llama_cpp_server(base_url)` and `verify_text_embeddings_inference_server(base_url)` confirm that a server configured as an OpenAI-compatible endpoint is actually the expected engine, by GETting an engine-specific native endpoint on the server root (llama.cpp `GET /props`, TEI `GET /info`) and checking its response shape. They raise `ValueError` on an engine mismatch and `ServerUnreachableError` (a `ValueError` subclass) when the server cannot be reached at all. Adapters call these in `initialize()` to fail fast at construction time when a different engine is running on the configured port (only warning when the server is down, matching the Ollama adapter). The non-raising `check_llama_cpp_server()` / `check_text_embeddings_inference_server()` variants return a `HealthResponse` and back the adapters' `health()` methods.

---

### Overview (`src/ogx/providers/remote/files/s3/README.md`)

# S3 Files Provider

A remote S3-based implementation of the OGX Files API that provides scalable cloud file storage with metadata persistence.

## Features

- **AWS S3 Storage**: Store files in AWS S3 buckets for scalable, durable storage
- **Metadata Management**: Uses SQL database for efficient file metadata queries
- **OpenAI API Compatibility**: Full compatibility with OpenAI Files API endpoints
- **Flexible Authentication**: Support for IAM roles and access keys
- **Custom S3 Endpoints**: Support for MinIO and other S3-compatible services
- **Bucket Organization**: Optional key prefix to store files under a folder within the bucket

## Configuration

### Basic Configuration

```yaml
api: files
provider_type: remote::s3
config:
  bucket_name: my-ogx-files
  region: us-east-1
  metadata_store:
    type: sqlite
    db_path: ./s3_files_metadata.db
```

### Advanced Configuration

```yaml
api: files
provider_type: remote::s3
config:
  bucket_name: my-ogx-files
  region: us-east-1
  aws_access_key_id: YOUR_ACCESS_KEY
  aws_secret_access_key: YOUR_SECRET_KEY
  endpoint_url: https://s3.amazonaws.com  # Optional for custom endpoints
  metadata_store:
    type: sqlite
    db_path: ./s3_files_metadata.db
```

### Environment Variables

The configuration supports environment variable substitution:

```yaml
config:
  bucket_name: "${env.S3_BUCKET_NAME}"
  region: "${env.AWS_REGION:=us-east-1}"
  aws_access_key_id: "${env.AWS_ACCESS_KEY_ID:=}"
  aws_secret_access_key: "${env.AWS_SECRET_ACCESS_KEY:=}"
  endpoint_url: "${env.S3_ENDPOINT_URL:=}"
  key_prefix: "${env.S3_KEY_PREFIX:=}"
```

Note: `S3_BUCKET_NAME` has no default value since S3 bucket names must be globally unique.

## Authentication

### IAM Roles (Recommended)

For production deployments, use IAM roles:

```yaml
config:
  bucket_name: my-bucket
  region: us-east-1
  # No credentials needed - will use IAM role
```

### Access Keys

For development or specific use cases:

```yaml
config:
  bucket_name: my-bucket
  region: us-east-1
  aws_access_key_id: AKIAIOSFODNN7EXAMPLE
  aws_secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
```

## S3 Bucket Setup

### Required Permissions

The S3 provider requires the following permissions:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::your-bucket-name",
        "arn:aws:s3:::your-bucket-name/*"
      ]
    }
  ]
}
```

### Automatic Bucket Creation

By default, the S3 provider expects the bucket to already exist. If you want the provider to automatically create the bucket when it doesn't exist, set `auto_create_bucket: true` in your configuration:

```yaml
config:
  bucket_name: my-bucket
  auto_create_bucket: true  # Will create bucket if it doesn't exist
  region: us-east-1
```

**Note**: When `auto_create_bucket` is enabled, the provider will need additional permissions:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject",
        "s3:ListBucket",
        "s3:CreateBucket"
      ],
      "Resource": [
        "arn:aws:s3:::your-bucket-name",
        "arn:aws:s3:::your-bucket-name/*"
      ]
    }
  ]
}
```

### Storing Files in a Folder

By default files are stored at the root of the bucket. Set `key_prefix` to keep them under a folder
instead, which helps when one bucket is shared across projects:

```yaml
config:
  bucket_name: my-bucket
  key_prefix: ogx/files  # objects are stored as ogx/files/file-abc123...
  region: us-east-1
```

Leading, trailing and repeated slashes are normalized, so `ogx/files`, `/ogx/files/` and `ogx//files`
all name the same folder.

Unlike buckets, folders need no creation step. S3 stores objects under flat keys and the folders shown
by the AWS console are synthesized from those keys, so the provider writes no placeholder objects and
`key_prefix` needs no permissions beyond the ones listed above.

**Note**: the prefix is applied at request time and is not recorded per file. Changing it on a deployment
that already holds files makes those files unreachable, and because a missing S3 object is treated as a
deleted file, the first read of one also drops its metadata row. Pick a prefix before the first upload, or
copy the existing objects to the new prefix yourself.

### Bucket Policy (Optional)

For additional security, you can add a bucket policy:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OGXAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::YOUR-ACCOUNT:role/OGXRole"
      },
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::your-bucket-name/*"
    },
    {
      "Sid": "OGXBucketAccess",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::YOUR-ACCOUNT:role/OGXRole"
      },
      "Action": [
        "s3:ListBucket"
      ],
      "Resource": "arn:aws:s3:::your-bucket-name"
    }
  ]
}
```

## Implementation Details

### Metadata Persistence

File metadata is stored in a SQL database for fast queries and OpenAI API compatibility. The metadata includes:

- File ID
- Original filename
- Purpose (assistants, batch, etc.)
- File size in bytes
- Created and expiration timestamps

### TTL and Cleanup

Files currently have a fixed long expiration time (100 years).

## Development and Testing

### Using MinIO

For self-hosted S3-compatible storage:

```yaml
config:
  bucket_name: test-bucket
  region: us-east-1
  endpoint_url: http://localhost:9000
  aws_access_key_id: minioadmin
  aws_secret_access_key: minioadmin
```

### Using OCI Object Storage with S3 Compatibility

[Official Object Storage Amazon S3 Compatibility API Documentation](https://docs.oracle.com/en-us/iaas/Content/Object/Tasks/s3compatibleapi.htm)

OCI Object Storage can be utilized through the OCI S3 Compatibility API. Simply Update the `config.yaml` and set the env-vars as below.

#### config.yaml

```yaml
provider_type: remote::s3
config:
  bucket_name: "${env.S3_BUCKET_NAME}"
  region: "${env.AWS_REGION:=us-east-1}"
  aws_access_key_id: "${env.AWS_ACCESS_KEY_ID:=}"
  aws_secret_access_key: "${env.AWS_SECRET_ACCESS_KEY:=}"
  endpoint_url: "${env.S3_ENDPOINT_URL:=}"
  metadata_store:
    table_name: files_metadata
    backend: sql_default
```

#### .env

```bash
AWS_ACCESS_KEY_ID=OCI_ACCESS_KEY
AWS_SECRET_ACCESS_KEY=OCI_SECRET_KEY
S3_BUCKET_NAME=OCI_BUCKET_NAME
S3_ENDPOINT_URL=https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com
AWS_REQUEST_CHECKSUM_CALCULATION=when_required
AWS_RESPONSE_CHECKSUM_VALIDATION=when_required
```

## Monitoring and Logging

The provider logs important operations and errors. For production deployments, consider:

- CloudWatch monitoring for S3 operations
- Custom metrics for file upload/download rates
- Error rate monitoring
- Performance metrics tracking

## Error Handling

The provider handles various error scenarios:

- S3 connectivity issues
- Bucket access permissions
- File not found errors
- Metadata consistency checks

## Known Limitations

- Fixed long TTL (100 years) instead of configurable expiration
- No server-side encryption enabled by default
- No support for AWS session tokens
- No multipart upload support (all files uploaded as single objects)

---

### Docs Api Overview (`docs/docs/api-overview.mdx`)

---
title: API Reference
---

import ApiSurfaceGrid from '@site/src/components/ApiSurfaceGrid';

# API Reference

OGX implements the OpenAI API and organizes endpoints by stability level. Use any OpenAI-compatible client to access these APIs.

<ApiSurfaceGrid
  sections={[
    {
      title: 'Stable APIs',
      tone: 'stable',
      items: [
        { title: 'Inference', endpoint: '/v1/chat/completions, /v1/completions, /v1/embeddings', href: '/docs/api/inference', blurb: 'Chat completions, text completions, and embeddings' },
        { title: 'Responses', endpoint: '/v1/responses', href: '/docs/api/responses', blurb: 'Agent orchestration with tool use and multi-turn' },
        { title: 'Models', endpoint: '/v1/models', href: '/docs/api/models', blurb: 'Model listing and management' },
        { title: 'Files', endpoint: '/v1/files', href: '/docs/api/files', blurb: 'File upload and management' },
        { title: 'Vector IO', endpoint: '/v1/vector_stores', href: '/docs/api/vector-io', blurb: 'Document storage and semantic search' },
        { title: 'Batches', endpoint: '/v1/batches', href: '/docs/api/batches', blurb: 'Offline batch processing' },
        { title: 'Conversations', endpoint: '/v1/conversations', href: '/docs/api/conversations', blurb: 'Conversation state management' },
        { title: 'Prompts', endpoint: '/v1/prompts', href: '/docs/api/prompts', blurb: 'Prompt templates and versioning' },
      ],
    },
    {
      title: 'Experimental APIs',
      tone: 'experimental',
      items: [
        { title: 'Admin', endpoint: '/v1alpha/admin', href: '/docs/api-experimental/admin', blurb: 'Providers, routes, health, and version' },
        { title: 'Rerank', endpoint: '/v1alpha/inference/rerank', href: '/docs/api-experimental/rerank-v-1-alpha-inference-rerank-post', blurb: 'Document reranking for search relevance' },
        { title: 'File Processors', endpoint: '/v1alpha/file_processors', href: '/docs/api-experimental/file-processors', blurb: 'Document ingestion and chunking' },
        { title: 'Interactions', endpoint: '/v1alpha/interactions', href: '/docs/api-experimental/interactions', blurb: 'Google Interactions API compatibility layer' },
        { title: 'Connectors', endpoint: '/v1alpha/admin/connectors', href: '/docs/api-experimental/connectors', blurb: 'External tool and service connectors' },
      ],
    },
  ]}
/>

These APIs follow semantic versioning and maintain backward compatibility within major versions.

---

### Docs Index (`docs/docs/index.mdx`)

---
sidebar_position: 1
title: Welcome to OGX
description: Open-source AI application server. Inference, vector stores, tools, and agentic orchestration in one process.
sidebar_label: Intro
tags:
  - getting-started
  - overview
---

import DocCardList from '@theme/DocCardList';

# Welcome to OGX

**Open-source AI application server. Not just inference routing, the full stack.**

OGX composes inference, vector stores, file storage, tool calling, and agentic orchestration into a single OpenAI-compatible server. Use any client, any language, any model. Swap providers without changing application code.

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="fake")
response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Hello"}],
)
```

## Choose your path

<DocCardList items={[
  {
    type: 'link',
    label: 'Quickstart',
    href: '/docs/getting_started/quickstart',
    description: 'Install and run OGX in under 5 minutes',
  },
  {
    type: 'link',
    label: 'API Reference',
    href: '/docs/api-openai',
    description: 'OpenAI-compatible API endpoints and usage',
  },
  {
    type: 'link',
    label: 'Providers',
    href: '/docs/providers/',
    description: 'Inference, vector store, file, and tool providers',
  },
  {
    type: 'link',
    label: 'Core Concepts',
    href: '/docs/concepts/',
    description: 'Architecture, APIs, distributions, and resources',
  },
  {
    type: 'link',
    label: 'Building Applications',
    href: '/docs/building_applications/',
    description: 'RAG, agents, tools, evals, and more',
  },
  {
    type: 'link',
    label: 'Distributions',
    href: '/docs/distributions/',
    description: 'Pre-packaged deployment configurations',
  },
]} />

## What you get

| API | Endpoint | Description |
|-----|----------|-------------|
| **Chat Completions** | `/v1/chat/completions` | Text and vision inference, streaming, tool calling |
| **Responses** | `/v1/responses` | Server-side agentic orchestration with tool calling, [MCP](https://modelcontextprotocol.io/) integration, and built-in file search (RAG) |
| **Embeddings** | `/v1/embeddings` | Text embeddings for search and retrieval |
| **Vector Stores** | `/v1/vector_stores` | Managed document storage and search |
| **Files** | `/v1/files` | File upload and management |
| **Batches** | `/v1/batches` | Offline batch processing |
| **Models** | `/v1/models` | Model listing and management |
| **Messages** | `/v1/messages` | Anthropic Messages API adapter |

Beyond the OpenAI specification, OGX provides **Prompts** for prompt template management, **File Processors** for document ingestion, and **Connectors** for external tool registration.

The Responses API implementation conforms to the [Open Responses](https://www.openresponses.org/) specification. See the [API conformance report](/docs/api-openai/conformance) for detailed coverage.

## A server, not a library

OGX is an HTTP server. Your application talks to a standard API over HTTP. This is a different architectural choice than SDK-level frameworks that abstract at the Python import level.

The consequence: your application is language-agnostic. Write it in Python, Go, TypeScript, or curl. Swap the server without touching application code. Replace the entire inference backend without redeploying your application.

## 50+ pluggable providers

OGX has a pluggable provider architecture across every API, not just inference.

- **23 inference providers:** Ollama, vLLM, OpenAI, Anthropic, AWS Bedrock, Azure OpenAI, Gemini, Vertex AI, NVIDIA NIM, Fireworks, Together AI, Groq, SambaNova, Cerebras, WatsonX, and more
- **15 vector store providers:** FAISS, SQLite-vec, ChromaDB, Qdrant, Milvus, PGVector, Weaviate, Elasticsearch, and more
- **Built-in guardrails support:** Responses guardrails call an external OpenAI-compatible moderation endpoint configured by `moderation_endpoint`
- **9 tool runtimes:** File Search, Brave/Bing/Tavily/Nimble/Serply/Exa/SearchApi web search, MCP

Develop locally with Ollama and FAISS. Deploy to production with vLLM and PGVector. Wrap Bedrock or Vertex without lock-in. Same API surface, different backend.

See the [provider documentation](/docs/providers/) for the full list and the [provider compatibility matrix](./api-openai/provider_matrix.md) for tested feature coverage.

## Get started

```bash
# One-line install
curl -LsSf https://github.com/ogx-ai/ogx/raw/main/scripts/install.sh | bash

# Or install via pip
pip install ogx

# Start the server
uv run ogx go --insecure
```

:::tip
OGX works with any OpenAI-compatible client. Point your existing code at `http://localhost:8321/v1` and you're ready to go.

OGX is secure by default. `--insecure` forces the server to listen on http. By default it runs on https with a self-signed cert. You'll have to skip cert verification or trust the automatically generated cert.
:::

[Quick Start Guide](/docs/getting_started/quickstart) | [OpenAI API Compatibility](/docs/api-openai) | [GitHub](https://github.com/ogx-ai/ogx)

## Found an issue with the docs?

If you've found some issue with our documentation, please open up a Bug in our [GitHub Issues](https://github.com/ogx-ai/ogx/issues) referencing the page and the problem you are facing. Thank you for your help in improving our documentation!

---

### Docs Api Anthropic Messages Index (`docs/docs/api-anthropic-messages/index.mdx`)

---
title: Anthropic Messages API
description: Anthropic Messages API compatibility in OGX
sidebar_label: Anthropic Messages
sidebar_position: 1
---

# Anthropic Messages API

OGX provides native support for the Anthropic Messages API at `/v1/messages`. Point the official Anthropic SDK at your OGX server and use any model.

```python
from anthropic import Anthropic

client = Anthropic(base_url="http://localhost:8321/v1", api_key="fake")
message = client.messages.create(
    model="llama-3.3-70b",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello"}],
)
```

## How it works

The Messages adapter checks whether the configured inference provider natively supports the `/v1/messages` endpoint. If it does, the request is forwarded directly. Otherwise, the adapter translates between Anthropic and OpenAI formats.

```mermaid
flowchart TD
    A["Anthropic SDK\nPOST /v1/messages"] --> B["Messages Adapter"]
    B --> C{"Provider supports\n/v1/messages natively?"}
    C -- Yes --> D["Forward request directly\n(no translation)"]
    C -- No --> E["Translate Anthropic → OpenAI"]
    E --> F["inference_api.openai_chat_completion()"]
    F --> G["Translate OpenAI → Anthropic"]
    D --> H["Inference Provider\n(Ollama, vLLM)"]
    G --> I["Inference Provider\n(OpenAI, Bedrock, etc.)"]
    H --> J["Anthropic-format response"]
    I --> K["Translate response\nOpenAI → Anthropic"]
    K --> J
```

**Translation path** (most providers): the adapter converts the full request and response between formats:

- **Request**: Anthropic `system`, `messages`, `tools`, `tool_choice`, `stop_sequences`, and (for reasoning models) `thinking` are mapped to their OpenAI equivalents
- **Response**: OpenAI completions are converted back to Anthropic format, including `content` blocks, `stop_reason`, and `usage`
- **Streaming**: OpenAI streaming chunks are transformed into Anthropic SSE events (`message_start`, `content_block_delta`, `message_delta`, etc.)
- **Tool use**: Anthropic `tool_use` / `tool_result` blocks are translated to and from OpenAI `tool_calls` / `tool` messages

**Passthrough path** (Anthropic, Ollama, vLLM): the request is forwarded directly to the provider's `/v1/messages` endpoint without any translation, since these providers natively speak the Anthropic format. This is what lets features the OpenAI format cannot represent, such as extended thinking, work with the `anthropic` provider. `config.network` (proxy, TLS, headers, timeout) applies, and errors from Anthropic keep their status code and message.

## Implemented endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v1/messages` | POST | Create a message (streaming and non-streaming) |
| `/v1/messages/count_tokens` | POST | Count tokens for a message |

## Supported features

- System messages (string or content blocks)
- Multi-turn conversations
- Streaming via Server-Sent Events
- Tool definitions and tool use
- Extended thinking (thinking blocks), for reasoning models
- Temperature, top_p, top_k, stop sequences
- Token counting

## Extended thinking

On the translation path, `thinking` is supported for reasoning models. Providers that forward to a native `/v1/messages` endpoint (Ollama, vLLM) pass `thinking` through unchanged.

| Request | Backend request |
|---------|-----------------|
| `thinking: {"type": "enabled", "budget_tokens": N}` | `reasoning_effort`: `low` for N up to 2048, `medium` up to 8192, `high` above. `medium` when `budget_tokens` is omitted |
| `thinking: {"type": "adaptive"}` | Accepted with no explicit effort, so the backend's own default applies |
| `thinking: {"type": "disabled"}` or omitted | No reasoning control. Any reasoning text the backend returns is not surfaced |

When thinking is requested, reasoning text returned by the backend (`reasoning_content` or `reasoning`, as vLLM, DeepSeek and Ollama return it) becomes a leading `thinking` content block. Streaming responses emit it as `thinking_delta` events before the answer. The block's `signature` is empty because nothing signs it.

A request with `thinking` enabled or adaptive for a model that is not known to reason fails with a 400 (`Failed to process thinking request`) instead of dropping the field. A model counts as a reasoning model when the [models.dev](https://models.dev) registry lists it as one, or when its name matches a well-known reasoning family (`gpt-oss`, OpenAI o-series and `gpt-5`, `deepseek-r1`, `qwq`, `qwen3`, and names containing `thinking`). Unknown models are treated as not reasoning.

Limits:

- `budget_tokens` selects a coarse effort level. It is not enforced as a token cap.
- Backends that do not return reasoning text (OpenAI's Chat Completions API does not for o-series and `gpt-5` models) accept the request and apply the effort, but the response has no `thinking` block.

## Not yet implemented

- Message Batches (`/v1/messages/batches`)

For property-level conformance details and missing properties, see the [conformance report](/docs/api-anthropic-messages/conformance).

---

### Docs Api Experimental Index (`docs/docs/api-experimental/index.mdx`)

---
title: Experimental APIs
description: APIs in development that may change
sidebar_label: Experimental
sidebar_position: 1
---

# Experimental APIs

OGX exposes its experimental APIs under the `v1alpha` prefix. They are
functional and available for use, but they may change in breaking ways
between releases.

:::warning
Experimental APIs may introduce breaking changes in minor releases. Pin your
client version if stability is important for your use case.
:::

## v1alpha APIs

### Admin API
Server administration: health and version checks, provider listing, route
inspection, and management of external connectors (such as MCP servers) and
their tools.

**Endpoint prefix:** `v1alpha/admin`

### Interactions API
Google Interactions-compatible endpoint for streaming interactive sessions.

**Endpoint prefix:** `v1alpha/interactions`

### Skills API
Register, list, version, update, and delete skills uploaded to the server.

**Endpoint prefix:** `v1alpha/skills`

### Containers API
Manage container workloads, including uploading and retrieving files inside
a container.

**Endpoint prefix:** `v1alpha/containers`

### File Processors API
Submit asynchronous jobs that parse and chunk documents for vector storage,
and poll or cancel those jobs. The synchronous
`v1alpha/file-processors/process` endpoint is deprecated in favor of the
jobs endpoints.

**Endpoint prefix:** `v1alpha/file-processors`

### Inference Rerank
Rerank documents for search relevance.

**Endpoint:** `v1alpha/inference/rerank`

## Feedback

Report issues or suggest improvements through [GitHub Issues](https://github.com/ogx-ai/ogx/issues).

---

### Docs Api Google Interactions Index (`docs/docs/api-google-interactions/index.mdx`)

---
title: Google Interactions API Compatibility
description: Google Interactions API compatibility layer in OGX
sidebar_label: Google Interactions
sidebar_position: 1
---

# Google Interactions API Compatibility

OGX provides a compatibility layer for the [Google Interactions API](https://ai.google.dev/gemini-api/docs/interactions) (v1alpha), so teams using the Google GenAI SDK can point at a OGX server with minimal code changes.

```python
from google import genai
from google.genai import types

client = genai.Client(
    api_key="no-key-required",
    http_options=types.HttpOptions(
        base_url="http://localhost:8321",
        api_version="v1alpha",
    ),
)

response = client.interactions.create(
    model="llama-3.3-70b",
    input="Hello",
)
print(response.outputs[0].text)
```

## Implemented endpoints

| Endpoint | Method | Status |
|----------|--------|--------|
| `/v1alpha/interactions` | POST | Implemented |
| `/v1alpha/interactions/{id}` | GET | Not yet |
| `/v1alpha/interactions/{id}` | DELETE | Not yet |
| `/v1alpha/interactions/{id}/cancel` | POST | Not yet |

For property-level coverage details, see the [conformance report](/docs/api-google-interactions/conformance).

## How it works

The Interactions adapter checks whether the configured inference provider natively supports the `/v1alpha/interactions` endpoint. If it does, the request is forwarded directly. Otherwise, the adapter translates between Google and OpenAI formats.

```mermaid
flowchart TD
    A["Google GenAI SDK\nPOST /v1alpha/interactions"] --> B["Interactions Adapter"]
    B --> C{"Provider supports\n/interactions natively?"}
    C -- Yes --> D["Forward request directly\n(no translation)"]
    C -- No --> E["Translate Google → OpenAI"]
    E --> F["inference_api.openai_chat_completion()"]
    F --> G["Translate OpenAI → Google"]
    D --> H["Inference Provider\n(Gemini)"]
    G --> I["Inference Provider\n(OpenAI, vLLM, Ollama, etc.)"]
    H --> J["Google-format response"]
    I --> K["Translate response\nOpenAI → Google"]
    K --> J
```

**Translation path** (most providers): the adapter converts the full request and response between formats:

- **Text generation** with string or multi-turn conversation input
- **Streaming** via Server-Sent Events matching Google's event format
- **System instructions** mapped to the system role
- **Generation config** parameters (temperature, top_p, top_k, max_output_tokens)
- **Tool calling** with function declarations, function_call outputs, and function_response inputs

**Passthrough path** (Gemini): when using the Gemini inference provider, requests are forwarded directly to Google's API without translation, including raw SSE streaming.

## Using with Google ADK

The [Google Agent Development Kit (ADK)](https://google.github.io/adk-docs/) can use the Interactions API as its inference backend when `use_interactions_api=True` is set on the `Gemini` model. However, ADK's `Gemini` class currently creates its own `google.genai.Client` internally and does not allow injecting a pre-configured client with a custom `base_url`.

This means you cannot point ADK at an OGX server out of the box. There is an [open PR](https://github.com/google/adk-python/pull/5035) to add a `client` parameter to the `Gemini` class. Until it merges, using ADK with OGX requires either:

- Monkey-patching `Gemini.api_client` with a custom `genai.Client` pointed at the OGX server
- Implementing a custom `BaseLlm` subclass that uses `genai.Client(http_options={"base_url": "..."})` directly

The GenAI SDK itself works without issues - you can create a `genai.Client` with a custom `base_url` and call `client.interactions.create(...)` directly against OGX.

## Known limitations

- Only text content is supported; multimodal inputs (images, audio, video) are not yet implemented
- Conversation chaining via `previous_interaction_id` is not yet available
- Background execution is not available
- The GET, DELETE, and Cancel endpoints are not yet implemented
- Response modalities are accepted for compatibility but ignored

---

### Docs Api Openai Index (`docs/docs/api-openai/index.mdx`)

---
title: OpenAI API Compatibility
description: OpenAI-compatible APIs and features in OGX
sidebar_label: OpenAI
sidebar_position: 1
---

# OpenAI API Compatibility

OGX is OpenAI-first. The primary API surface implements the OpenAI spec, so you can use any OpenAI-compatible client, just change the base URL.

OGX also provides compatibility layers for other SDKs:

- **Anthropic Messages API** at `/v1/messages` for teams using the Anthropic SDK. See the [Anthropic Messages API](/docs/api-anthropic-messages) docs, including a [conformance report](/docs/api-anthropic-messages/conformance).
- **Google Interactions API** at `/v1alpha/interactions` for teams using the Google GenAI SDK. See the [Google Interactions compatibility guide](/docs/api-google-interactions) for details.

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="fake")
response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Hello"}],
)
```

This works with the [OpenAI Python client](https://github.com/openai/openai-python), [TypeScript client](https://github.com/openai/openai-node), or any framework that speaks the OpenAI API (LangChain, LlamaIndex, CrewAI, etc.).

## Implemented endpoints

| API | Endpoint | Description |
|-----|----------|-------------|
| Chat Completions | `/v1/chat/completions` | Text and vision inference, streaming, tool calling |
| Completions | `/v1/completions` | Text completions |
| Embeddings | `/v1/embeddings` | Text embeddings |
| Models | `/v1/models` | Model listing and management |
| Files | `/v1/files` | File upload and management |
| Vector Stores | `/v1/vector_stores` | Document storage and search |
| Batches | `/v1/batches` | Offline batch processing |
| Responses | `/v1/responses` | Server-side agentic orchestration with tool calling, MCP, and file search |
| Conversations | `/v1/conversations` | Conversation state management |

For property-level conformance details and missing endpoints, see the [conformance report](/docs/api-openai/conformance).

OGX also provides additional APIs beyond the OpenAI specification, including **Prompts** for prompt template management and **File Processors** for document ingestion pipelines.

## Responses API

The Responses API is OGX's most distinctive feature. It moves the agentic loop to the server, so a single API call can:

- **Call tools** — the server executes tool calls and feeds results back to the model automatically
- **Connect to MCP servers** — use any [Model Context Protocol](https://modelcontextprotocol.io/) server as a tool source
- **Search files** — built-in RAG via vector stores, no external retrieval pipeline needed
- **Manage conversations** — server-side state with `previous_response_id` chaining

The implementation conforms to the [Open Responses](https://www.openresponses.org/) specification. See [how the Responses API works internally](/docs/api-openai/responses-flow) for an interactive flow diagram showing how requests are processed.

```python
response = client.responses.create(
    model="llama-3.3-70b",
    input="What files mention the Q4 results?",
    tools=[{
        "type": "file_search",
        "vector_store_ids": ["vs_abc123"],
    }],
)
```

## Provider compatibility

Not all features are available on all inference providers. See the [provider compatibility matrix](./provider_matrix.md) for tested feature coverage across Azure, Bedrock, OpenAI, vLLM, WatsonX, and others.

## Known limitations

For a detailed breakdown of schema differences and conformance issues by endpoint, see the [conformance report](/docs/api-openai/conformance) and the [Responses API limitations](/docs/providers/openai_responses_limitations).

---

### Docs Api Index (`docs/docs/api/index.mdx`)

---
title: API Reference
description: Complete reference for OGX APIs
sidebar_label: Overview
sidebar_position: 1
---

# API Reference

OGX provides a comprehensive set of APIs for building generative AI applications. All APIs follow OpenAI-compatible standards and can be used interchangeably across different providers.

## Core APIs

### Inference API
Run inference with Large Language Models (LLMs) and embedding models.

**Supported Providers:**
- Builtin (Single Node)
- Ollama (Single Node)
- Fireworks (Hosted)
- Together (Hosted)
- NVIDIA NIM (Hosted and Single Node)
- vLLM (Hosted and Single Node)
- AWS Bedrock (Hosted)
- Cerebras (Hosted)
- Groq (Hosted)
- SambaNova (Hosted)
- PyTorch ExecuTorch (On-device iOS, Android)
- OpenAI (Hosted)
- Anthropic (Hosted)
- Gemini (Hosted)
- WatsonX (Hosted)

### Agents API
Run multi-step agentic workflows with LLMs, including tool usage, memory (RAG), and complex reasoning.

**Supported Providers:**
- Builtin (Single Node)
- Fireworks (Hosted)
- Together (Hosted)
- PyTorch ExecuTorch (On-device iOS)

### Vector IO API
Perform operations on vector stores, including adding documents, searching, and deleting documents.

**Supported Providers:**
- FAISS (Single Node)
- SQLite-Vec (Single Node)
- Chroma (Hosted and Single Node)
- Milvus (Hosted and Single Node)
- Postgres (PGVector) (Hosted and Single Node)
- Weaviate (Hosted)
- Qdrant (Hosted and Single Node)

### Files API (OpenAI-compatible)
Manage file uploads, storage, and retrieval with OpenAI-compatible endpoints.

**Supported Providers:**
- Local Filesystem (Single Node)
- S3 (Hosted)

### Vector Store Files API (OpenAI-compatible)
Integrate file operations with vector stores for automatic document processing and search.

**Supported Providers:**
- FAISS (Single Node)
- SQLite-vec (Single Node)
- Milvus (Single Node)
- ChromaDB (Hosted and Single Node)
- Qdrant (Hosted and Single Node)
- Weaviate (Hosted)
- Postgres (PGVector) (Hosted and Single Node)

### Responses Guardrails
Optionally moderate input and generated text within the Responses API. Configure an
external OpenAI-compatible `moderation_endpoint` on the builtin responses provider,
then enable it per request with `guardrails: true`. Authentication headers, when
needed, are configured on the server through `moderation_headers`.

Safety and Shields are no longer separate APIs or registered provider categories.
See [Configuring Responses Guardrails](/docs/distributions/configuration#configuring-responses-guardrails)
for configuration details.

### Post Training API
Fine-tune models for specific use cases and domains.

**Supported Providers:**
- Builtin (Single Node)
- HuggingFace (Single Node)
- TorchTune (Single Node)
- NVIDIA NEMO (Hosted)

### Eval API
Generate outputs and perform scoring to evaluate system performance.

**Supported Providers:**
- Builtin (Single Node)
- NVIDIA NEMO (Hosted)

### Telemetry API
Collect telemetry data from the system for monitoring and observability.

**Supported Providers:**
- Builtin (Single Node)

## API Compatibility

All OGX APIs are designed to be OpenAI-compatible, allowing you to:
- Use existing OpenAI API clients and tools
- Migrate from OpenAI to other providers seamlessly
- Maintain consistent API contracts across different environments

## Getting Started

To get started with OGX APIs:

1. **Choose a Distribution**: Select a pre-configured distribution that matches your environment
2. **Configure Providers**: Set up the providers you want to use for each API
3. **Start the Server**: Launch the OGX server with your configuration
4. **Use the APIs**: Make requests to the API endpoints using your preferred client

For detailed setup instructions, see our [Getting Started Guide](/docs/getting_started/quickstart).

## Provider Details

For complete provider compatibility and setup instructions, see our [Providers Documentation](/docs/providers/).

## API Stability

OGX APIs are organized by stability level:
- **[Stable APIs](/docs/api/)** - Production-ready APIs with full support
- **[Experimental APIs](/docs/api-experimental/)** - APIs in development with limited support

## OpenAI Integration

For specific OpenAI API compatibility features, see our [OpenAI Compatibility Guide](/docs/api-openai/).

---

### Docs Building Applications Index (`docs/docs/building_applications/index.mdx`)

---
title: Building Applications
description: Guides for building AI applications with OGX
sidebar_label: Overview
sidebar_position: 5
---

import DocCardList from '@theme/DocCardList';

# Building Applications

OGX provides the building blocks for AI applications. Start with the notebook for a hands-on walkthrough, then dive into specific topics.

:::tip
New to OGX? Start with the [Quickstart](/docs/getting_started/quickstart) — pick a backend, server mode, and use case, and follow the steps for your exact setup.
:::

## Core patterns

<DocCardList items={[
  {
    type: 'link',
    label: 'RAG',
    href: '/docs/building_applications/rag',
    description: 'Retrieval-augmented generation with vector stores and file search',
  },
  {
    type: 'link',
    label: 'Agent Framework',
    href: '/docs/building_applications/agent',
    description: 'Components and design patterns for building agents',
  },
  {
    type: 'link',
    label: 'Agent Execution Loop',
    href: '/docs/building_applications/agent_execution_loop',
    description: 'How agents process, decide, and act step by step',
  },
  {
    type: 'link',
    label: 'Responses vs Agents API',
    href: '/docs/building_applications/responses_vs_agents',
    description: 'Choosing the right API for your use case',
  },
]} />

## Extend and operate

<DocCardList items={[
  {
    type: 'link',
    label: 'Tools',
    href: '/docs/building_applications/tools',
    description: 'Extend capabilities with web search, MCP, and custom functions',
  },
  {
    type: 'link',
    label: 'Telemetry',
    href: '/docs/building_applications/telemetry',
    description: 'Monitor performance, traces, and behavior in production',
  },
  {
    type: 'link',
    label: 'Codex CLI Integration (Alpha)',
    href: '/docs/building_applications/codex_cli_integration',
    description: 'Use Codex CLI with OGX as a proxy for unified provider access',
  },
]} />

---

### Docs Concepts Index (`docs/docs/concepts/index.mdx`)

---
title: Core Concepts
description: Understanding OGX's service-oriented philosophy and key concepts
sidebar_label: Overview
sidebar_position: 1
---

import DocCardList from '@theme/DocCardList';

# Core Concepts

OGX is a service-oriented platform. A few concepts arise from this design which may not feel natural if you're coming from other LLM frameworks.

:::info
Understanding these concepts will help you make the most of OGX's modular architecture and provider system.
:::

<DocCardList items={[
  {
    type: 'link',
    label: 'Architecture',
    href: '/docs/concepts/architecture',
    description: 'How the system is structured, request flow, and provider dispatch',
  },
  {
    type: 'link',
    label: 'APIs',
    href: '/docs/concepts/apis/',
    description: 'The core APIs and their stability levels',
  },
  {
    type: 'link',
    label: 'Distributions',
    href: '/docs/distributions/',
    description: 'Pre-configured deployment packages for different environments',
  },
  {
    type: 'link',
    label: 'Resources',
    href: '/docs/concepts/resources',
    description: 'Models, vector stores, tool groups, and their lifecycle',
  },
]} />

---

### Docs Contributing Index (`docs/docs/contributing/index.mdx`)

---
title: Contributing
description: Contributing to OGX
sidebar_label: Contributing to OGX
sidebar_position: 3
hide_title: true
---

# Contributing to OGX

We want to make contributing to this project as easy and transparent as
possible.

The canonical contributing guide lives in the repository's
[CONTRIBUTING.md](https://github.com/ogx-ai/ogx/blob/main/CONTRIBUTING.md). It covers
setting up your development environment, pre-commit hooks, the issue and pull request
process, how to add a new provider, coding style, and common tasks. Read it before you
start contributing.

## Provider how-to guides

- [Adding a New API Provider](./new_api_provider.mdx)
- [Adding a New Vector Database](./new_vector_database.mdx)
- [Testing with the Record/Replay System](./testing/record-replay.mdx)

---

### Docs Deploying Index (`docs/docs/deploying/index.mdx`)

---
title: Deploying OGX
description: Production deployment guides for OGX in various environments
sidebar_label: Overview
sidebar_position: 1
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Deploying OGX

[**→ Kubernetes Deployment Guide**](/docs/deploying/kubernetes_deployment)
[**→ AWS EKS Deployment Guide**](/docs/deploying/aws_eks_deployment)

---

### Docs Distributions Index (`docs/docs/distributions/index.mdx`)

---
title: Distributions Overview
description: Pre-packaged sets of OGX components for different deployment scenarios
sidebar_label: Overview
sidebar_position: 1
---

import DocCardList from '@theme/DocCardList';

# Distributions Overview

A distribution is a pre-packaged set of OGX components that can be deployed together. Pick a distribution that matches your deployment target, or build your own.

:::tip
Not sure which distribution to use? Start with the **[Available Distributions](/docs/distributions/list_of_distributions)** page to compare options side by side.
:::

## Getting started

<DocCardList items={[
  {
    type: 'link',
    label: 'Available Distributions',
    href: '/docs/distributions/list_of_distributions',
    description: 'Complete list and comparison of all distributions',
  },
  {
    type: 'link',
    label: 'Starting the Server',
    href: '/docs/distributions/starting_ogx_server',
    description: 'How to run a distribution and start serving requests',
  },
  {
    type: 'link',
    label: 'OGX UI',
    href: '/docs/distributions/ogx_ui',
    description: 'Web-based interface for interacting with OGX servers',
  },
]} />

## Configuration and customization

<DocCardList items={[
  {
    type: 'link',
    label: 'Building Custom Distributions',
    href: '/docs/distributions/building_distro',
    description: 'Create your own distribution from scratch',
  },
  {
    type: 'link',
    label: 'Customizing Configuration',
    href: '/docs/distributions/customizing_run_yaml',
    description: 'Customize config.yaml for your deployment needs',
  },
  {
    type: 'link',
    label: 'Configuration Reference',
    href: '/docs/distributions/configuration',
    description: 'Configuration file format and available options',
  },
  {
    type: 'link',
    label: 'Importing as Library',
    href: '/docs/distributions/importing_as_library',
    description: 'Use distributions programmatically in your Python code',
  },
]} />

---

### Docs Getting Started Quickstart (`docs/docs/getting_started/quickstart.mdx`)

---
description: Get up and running with OGX in under a minute.
sidebar_label: Quickstart
sidebar_position: 1
title: Quickstart
---

import QuickstartSelector from '@site/src/components/QuickstartSelector';
import manifest from './quickstart/steps.json';
import appPy from '!!raw-loader!./quickstart/app.py';
import ragPy from '!!raw-loader!./quickstart/rag.py';
import systemonePy from '!!raw-loader!./quickstart/systemone.py';

Pick a model backend, how to run the server, and what to build. The steps below update to match.

<QuickstartSelector
  manifest={manifest}
  files={{'app.py': appPy, 'rag.py': ragPy, 'systemone.py': systemonePy}}
/>

:::tip Project setup
`uvx` is great for trying things out. For a real project, install into a persistent environment:

```bash
uv init my-ai-app && cd my-ai-app
uv add ogx openai
uv run ogx go
```
:::

## Troubleshooting

<details>
<summary><strong>Port already in use</strong></summary>

If you see `Address already in use`, another process is using port 8321. Either stop it or run on a different port, and use that port in `OGX_BASE_URL`:

```bash
uvx ogx go --port 8322
```

</details>

<details>
<summary><strong>Connection refused or connection error</strong></summary>

If `curl` returns `Connection refused`, the server has not finished starting. Wait a few seconds for model registration to complete, then try again. Check the terminal where you started the server for errors.

If the Python client raises `APIConnectionError`, check that `OGX_BASE_URL` starts with `https://`. `ogx go` only listens on http when started with `--insecure`.

</details>

<details>
<summary><strong>Authentication required</strong></summary>

If the API returns `Authentication required`, the request is missing a valid API key. Export one of the keys printed by the running `ogx go`:

```bash
export OGX_API_KEY=ogk_...
```

Keys from an earlier run stop working when the server restarts.

</details>

<details>
<summary><strong>Responses API returns Not Found</strong></summary>

If `client.responses.create` fails with `Not Found`, look for this line in the `ogx go` output:

```text
  ✗ No embedding model detected — vector stores, file-search, and responses disabled.
```

Pull an embedding model and restart the server:

```bash
ollama pull nomic-embed-text
uvx ogx go
```

To use a different embedding model, pass `--default-embedding-model PROVIDER_ID/MODEL_ID --default-embedding-dimension DIMENSION`.

</details>

<details>
<summary><strong>Model not found</strong></summary>

If the API returns an error about a model not being found, make sure you pulled the model first. For Ollama:

```bash
ollama pull llama3.2:3b
```

Then restart the OGX server, and check which models it registered:

```bash
curl -k -s -H "Authorization: Bearer $OGX_API_KEY" $OGX_BASE_URL/models
```

</details>

<details>
<summary><strong>Coding agent replies are empty</strong></summary>

Ollama's default context window is smaller than a coding agent's prompt, so the model only sees part of it. Restart Ollama with a larger window:

```bash
OLLAMA_CONTEXT_LENGTH=16384 ollama serve
```

</details>

## What's next?

- [Use the OpenAI SDK](/docs/api-openai) - full compatibility guide
- [Try the Responses API](../building_applications/agent) - build agents with tool calling
- [Add vector search](../building_applications/rag) - RAG with file search and vector stores
- [Connect Claude Code](../building_applications/claude_code_integration), [Codex](../building_applications/codex_cli_integration), or [opencode](../building_applications/opencode_integration) - coding agents on your own models
- [See all providers](../providers) - swap to vLLM, Bedrock, Azure, and more

---

### Docs Providers Index (`docs/docs/providers/index.mdx`)

---
title: API Providers
description: 50+ pluggable providers across inference, vector stores, and file storage
sidebar_label: Overview
sidebar_position: 1
---

import { ProviderGrid, ProviderReference } from '@site/src/components/ProviderGrid';

# API Providers

OGX composes 23 inference providers, 15 vector stores, and 3 file storage options into a single deployable server. No other open-source project covers this surface area in one process.

Providers come in two types:

- **Remote**: adapts an external service (Ollama, OpenAI, vLLM, Bedrock, etc.)
- **Inline**: runs in-process within OGX (FAISS, sentence-transformers, etc.)

:::info
At least one inline provider exists for each API so you can run a fully featured stack locally without any external dependencies.
:::

## Provider categories

<ProviderGrid />

## Reference

<ProviderReference />

## Why this matters

Gateways like LiteLLM route inference requests to multiple providers. That's useful, but inference routing is one API.

OGX composes the full application: an agent running on the Responses API can call a model via any inference provider, search documents in any vector store, invoke tools via MCP, and stream the result back. All in one server process, all through OpenAI-compatible endpoints.

The composition is the hard part. Making inference + vector stores + files + tools + agentic orchestration work together correctly across dozens of provider combinations is what takes years, not months.

## OpenAI Compatibility

OGX is OpenAI-first. The primary API surface implements the OpenAI spec. An Anthropic Messages adapter (`/v1/messages`) translates to the inference API for teams that use the Anthropic SDK.

See the [OpenAI compatibility guide](/docs/api-openai/) and [known Responses API limitations](/docs/providers/openai_responses_limitations).

---

### Docs References Index (`docs/docs/references/index.mdx`)

---
title: References
description: Reference documentation for OGX
sidebar_label: Overview
sidebar_position: 1
---

# References

- [Python SDK Reference](/docs/references/python_sdk_reference/)
- [Llama CLI](/docs/references/ogx_cli_reference/) for building and running your OGX server
- [OGX Client CLI](./ogx_client_cli_reference.md) for interacting with your OGX server

---

### Docs Concepts Apis Index (`docs/docs/concepts/apis/index.mdx`)

---
title: APIs
description: How OGX's APIs work together
sidebar_label: APIs
sidebar_position: 1
---

# APIs

OGX exposes OpenAI-compatible REST APIs. For the full endpoint list, see the [API Reference](/docs/api-overview).

## Stability Levels

APIs are organized by maturity. Stable APIs (`/v1/`) follow semantic versioning and won't break between minor releases. Experimental APIs (`/v1alpha/`, `/v1beta/`) may change based on feedback. See [API Leveling](/docs/concepts/apis/api_leveling) for details.

## How the APIs work together

### Files + Vector Stores + Responses

These three APIs combine to give you RAG in a few calls:

1. Upload a document via `/v1/files`
2. Create a vector store and attach the file via `/v1/vector_stores`
3. OGX automatically chunks, embeds, and indexes the document
4. Use `file_search` in a `/v1/responses` request to search it

See [File Operations and Vector Store Integration](/docs/concepts/file_operations_vector_stores) for details.

### Tool Runtime

The Responses API orchestrates tools server-side. The model decides which tools to call, OGX executes them and feeds results back automatically:

- **file_search** - searches your vector stores
- **web_search** - queries configured search providers
- **MCP** - connects to any MCP server
- **Custom functions** - your own function tools

### Providers and External APIs

Not every provider supports every feature. See [API Providers](/docs/concepts/apis/api_providers) for how providers map to APIs, and [External APIs](/docs/concepts/apis/external) for extending OGX with custom endpoints.

---

### Docs Distributions Remote Hosted Distro Index (`docs/docs/distributions/remote_hosted_distro/index.mdx`)

# Remote-Hosted Distributions

Remote-hosted distributions are OGX endpoints hosted by partners that you can connect to directly.

| Distribution | Endpoint | Inference |
|-------------|----------|-----------|
| Together | [https://llama-stack.together.ai](https://llama-stack.together.ai) | remote::together |
| Fireworks | [https://llama-stack-preview.fireworks.ai](https://llama-stack-preview.fireworks.ai) | remote::fireworks |

## Connecting

Point any OpenAI-compatible client at the endpoint:

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://llama-stack.together.ai/v1",
    api_key="your-together-api-key",
)

response = client.chat.completions.create(
    model="meta-llama/Llama-3.2-3B-Instruct",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)
```

Or use the CLI:

```bash
pip install ogx-client
ogx-client configure --endpoint https://llama-stack.together.ai
ogx-client models list
```

---

### Docs Providers Batches Index (`docs/docs/providers/batches/index.mdx`)

---
description: |
  The Batches API enables efficient processing of multiple requests in a single operation,
  particularly useful for processing large datasets, batch evaluation workflows, and
  cost-effective inference at scale.

  The API is designed to allow use of openai client libraries for seamless integration.

  This API provides the following extensions:
   - idempotent batch creation

  Note: This API is currently under active development and may undergo changes.
sidebar_label: Batches
title: Batches
---

# Batches

## Overview

The Batches API enables efficient processing of multiple requests in a single operation,
particularly useful for processing large datasets, batch evaluation workflows, and
cost-effective inference at scale.

The API is designed to allow use of openai client libraries for seamless integration.

This API provides the following extensions:
 - idempotent batch creation

Note: This API is currently under active development and may undergo changes.

This section contains documentation for all available providers for the **batches** API.

---

### Docs Providers Container Runtime Index (`docs/docs/providers/container_runtime/index.mdx`)

---
sidebar_label: Container Runtime
title: Container Runtime
---

# Container Runtime

## Overview

This section contains documentation for all available providers for the **container_runtime** API.

---

### Docs Providers External Index (`docs/docs/providers/external/index.mdx`)

# External Providers

OGX supports external providers that live outside of the main codebase. This allows you to:
- Create and maintain your own providers independently
- Share providers with others without contributing to the main codebase
- Keep provider-specific code separate from the core OGX code

## External Provider Documentation

- [Known External Providers](/docs/providers/external/external-providers-list)
- [Creating External Providers](/docs/providers/external/external-providers-guide)

---

### Docs Providers File Processors Index (`docs/docs/providers/file_processors/index.mdx`)

---
sidebar_label: File Processors
title: File Processors
---

# File Processors

## Overview

This section contains documentation for all available providers for the **file_processors** API.

---

### Docs Providers Files Index (`docs/docs/providers/files/index.mdx`)

---
description: "Files API for managing file uploads and retrieval."
sidebar_label: Files
title: Files
---

# Files

## Overview

Files API for managing file uploads and retrieval.

This section contains documentation for all available providers for the **files** API.

---

### Docs Providers Inference Index (`docs/docs/providers/inference/index.mdx`)

---
description: |
  Inference

  OGX Inference API for generating completions, chat completions, and embeddings.

  This API provides the raw interface to the underlying models. Four kinds of models are supported:
  - LLM models: these models generate "raw" and "chat" (conversational) completions.
  - Embedding models: these models generate embeddings to be used for semantic search.
  - Rerank models: these models reorder the documents based on their relevance to a query.
  - SystemOne (judgment/decision) models: these models answer calibrated questions about a
    piece of state (a probability, a choice, or a rubric score) instead of generating text.
sidebar_label: Inference
title: Inference
---

# Inference

## Overview

Inference

OGX Inference API for generating completions, chat completions, and embeddings.

This API provides the raw interface to the underlying models. Four kinds of models are supported:
- LLM models: these models generate "raw" and "chat" (conversational) completions.
- Embedding models: these models generate embeddings to be used for semantic search.
- Rerank models: these models reorder the documents based on their relevance to a query.
- SystemOne (judgment/decision) models: these models answer calibrated questions about a
  piece of state (a probability, a choice, or a rubric score) instead of generating text.

This section contains documentation for all available providers for the **inference** API.

---

### Docs Providers Interactions Index (`docs/docs/providers/interactions/index.mdx`)

---
description: "Protocol for the Google Interactions API."
sidebar_label: Interactions
title: Interactions
---

# Interactions

## Overview

Protocol for the Google Interactions API.

This section contains documentation for all available providers for the **interactions** API.

---

### Docs Providers Messages Index (`docs/docs/providers/messages/index.mdx`)

---
description: "Protocol for the Anthropic Messages API."
sidebar_label: Messages
title: Messages
---

# Messages

## Overview

Protocol for the Anthropic Messages API.

This section contains documentation for all available providers for the **messages** API.

---

### Docs Providers Responses Index (`docs/docs/providers/responses/index.mdx`)

---
description: "Protocol for managing OpenAI-compatible responses."
sidebar_label: Responses
title: Responses
---

# Responses

## Overview

Protocol for managing OpenAI-compatible responses.

This section contains documentation for all available providers for the **responses** API.

---

### Docs Providers Skills Index (`docs/docs/providers/skills/index.mdx`)

---
description: |
  Skills API for managing versioned skill bundles.

  Skills are zip archives containing a SKILL.md manifest and supporting files.
  Conforms to the OpenAI Skills API wire format.
sidebar_label: Skills
title: Skills
---

# Skills

## Overview

Skills API for managing versioned skill bundles.

Skills are zip archives containing a SKILL.md manifest and supporting files.
Conforms to the OpenAI Skills API wire format.

This section contains documentation for all available providers for the **skills** API.

---

### Docs Providers Vector Io Index (`docs/docs/providers/vector_io/index.mdx`)

---
sidebar_label: Vector Io
title: Vector Io
---

# Vector Io

## Overview

This section contains documentation for all available providers for the **vector_io** API.

---

### Docs Providers Web Search Index (`docs/docs/providers/web_search/index.mdx`)

---
sidebar_label: Web Search
title: Web Search
---

# Web Search

## Overview

This section contains documentation for all available providers for the **web_search** API.

---

### Docs References Ogx Cli Reference Index (`docs/docs/references/ogx_cli_reference/index.md`)

# llama (server-side) CLI Reference

The `ogx` CLI tool helps you set up and use the OGX. The CLI is available on your path after installing the `ogx` package.

## Installation

You have two ways to install OGX:

1. **Install as a package**:
   You can install the repository directly from [PyPI](https://pypi.org/project/ogx/) by running the following command:

   ```bash
   pip install ogx
   ```

2. **Install from source**:
   If you prefer to install from the source code, follow these steps:

   ```bash
    mkdir -p ~/local
    cd ~/local
    git clone git@github.com:ogx-ai/ogx.git

    uv venv myenv --python 3.13
    source myenv/bin/activate  # On Windows: myenv\Scripts\activate

    cd ogx
    pip install -e .
   ```

## `ogx` subcommands

1. `stack`: Allows you to build a stack using the `ogx` distribution and run a OGX server. You can read more about how to build a OGX distribution in the [Build your own Distribution](/docs/distributions/building_distro) documentation.
2. `connect`: Connect third-party tools to the running OGX server. Supports [`claude`](/docs/building_applications/claude_code_integration), [`opencode`](/docs/building_applications/opencode_integration), and [`codex`](/docs/building_applications/codex_cli_integration).

For downloading models, we recommend using the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli). See [Downloading models](#downloading-models) for more information.

### Sample Usage

```bash
llama --help
```

```text
usage: ogx [-h] {stack,connect} ...

Welcome to the OGX CLI

options:
  -h, --help      show this help message and exit

subcommands:
  {stack,connect}

  stack                 Operations for the OGX / Distributions
  connect               Connect third-party tools to the running OGX server
```

## Downloading models

You first need to have models downloaded locally. We recommend using the [Hugging Face CLI](https://huggingface.co/docs/huggingface_hub/guides/cli) to download models.

First, install the Hugging Face CLI:

```bash
pip install huggingface_hub[cli]
```

Then authenticate and download models:

```bash
# Authenticate with Hugging Face
huggingface-cli login

# Download a model
huggingface-cli download meta-llama/Llama-3.2-3B-Instruct --local-dir ~/.ogx/Llama-3.2-3B-Instruct
```

## List the downloaded models

To list the downloaded models, you can use the Hugging Face CLI:

```bash
# List all downloaded models in your local cache
huggingface-cli scan-cache
```

---

### Docs References Python Sdk Reference Index (`docs/docs/references/python_sdk_reference/index.md`)

# Python SDK Reference

## Shared Types

```python
from ogx_client.models import (
    InterleavedContent,
    InterleavedContentItem,
    ParamType,
    SamplingParams,
    SystemMessage,
    ToolResponseMessage,
    URL,
    UserMessage,
)
```

## Tools

Types:

```python
from ogx_client.models import ListToolDefsResponse, ToolDef
```

## Inspect

Types:

```python
from ogx_client.models import HealthInfo, VersionInfo
```

Methods:

- <code title="get /v1/health">client.inspect.health() -> HealthInfo</code>
- <code title="get /v1/version">client.inspect.version() -> VersionInfo</code>

## Inference

Types:

```python
from ogx_client.models import RerankRequest, RerankResponse
```

Methods:

- <code title="post /v1alpha/inference/rerank">client.inference.rerank(rerank_request) -> RerankResponse</code>

## Embeddings

Types:

```python
from ogx_client.models import (
    OpenAIEmbeddingsRequestWithExtraBody,
    OpenAIEmbeddingsResponse,
)
```

Methods:

- <code title="post /v1/embeddings">client.embeddings.create(open_ai_embeddings_request_with_extra_body) -> OpenAIEmbeddingsResponse</code>

## VectorIo

:::warning DEPRECATED API

**This API is deprecated and will be removed in a future version.**

Use the OpenAI-compatible Vector Stores API instead:

- Instead of `client.vector_io.insert()`, use `client.vector_stores.files.create()`
- Instead of `client.vector_io.query()`, use `client.vector_stores.search()`

See the [RAG documentation](/docs/building_applications/rag) for migration examples.

Related: [Issue #2981](https://github.com/ogx-ai/ogx/issues/2981)

:::

Types:

```python
from ogx_client.models import QueryChunksResponse
```

Methods:

- <code title="post /v1/vector-io/insert">client.vector_io.insert(insert_chunks_request) -> None</code>
- <code title="post /v1/vector-io/query">client.vector_io.query(query_chunks_request) -> QueryChunksResponse</code>

## Models

Types:

```python
from ogx_client.models import (
    GetModelV1ModelsModelIdGet200Response,
    ListModelsV1ModelsGet200Response,
    OpenAIModel,
)
```

Methods:

- <code title="get /v1/models/{model_id}">client.models.retrieve(model_id) -> GetModelV1ModelsModelIdGet200Response</code>
- <code title="get /v1/models">client.models.list() -> ListModelsV1ModelsGet200Response</code>

## Providers

Types:

```python
from ogx_client.models import ListProvidersResponse
```

Methods:

- <code title="get /v1/providers">client.providers.list() -> ListProvidersResponse</code>

## Routes

Types:

```python
from ogx_client.models import ListRoutesResponse
```

Methods:

- <code title="get /v1/inspect/routes">client.routes.list(api_filter=None) -> ListRoutesResponse</code>

---

### License Header (`docs/license_header.txt`)

Copyright (c) The OGX Contributors.
All rights reserved.

This source code is licensed under the terms described in the LICENSE file in
the root directory of this source tree.

---

### Package.Json (`docs/package.json`)

{
  "name": "docusaurus-template-openapi-docs",
  "version": "4.3.7",
  "private": true,
  "scripts": {
    "docusaurus": "docusaurus",
    "start": "docusaurus start",
    "build": "docusaurus build",
    "swizzle": "docusaurus swizzle",
    "deploy": "docusaurus deploy",
    "clear": "docusaurus clear",
    "serve": "docusaurus serve",
    "write-translations": "docusaurus write-translations",
    "write-heading-ids": "docusaurus write-heading-ids",
    "gen-api-docs": "docusaurus gen-api-docs",
    "clean-api-docs": "docusaurus clean-api-docs",
    "gen-api-docs:version": "docusaurus gen-api-docs:version",
    "clean-api-docs:version": "docusaurus clean-api-docs:version",
    "sync-files": "node scripts/sync-files.js",
    "postinstall": "bash scripts/patch-openapi-theme.sh"
  },
  "dependencies": {
    "@docusaurus/core": "^3.10.2",
    "@docusaurus/preset-classic": "^3.10.2",
    "@docusaurus/theme-mermaid": "^3.10.2",
    "@easyops-cn/docusaurus-search-local": "^0.55.3",
    "@mdx-js/react": "^3.0.0",
    "clsx": "^2.0.0",
    "docusaurus-plugin-openapi-docs": "^5.2.0",
    "docusaurus-theme-openapi-docs": "^5.2.0",
    "prism-react-renderer": "^2.3.0",
    "react": "^19.3.0",
    "react-dom": "^19.3.0",
    "remark-code-import": "^1.2.0"
  },
  "overrides": {
    "glob": "^10.5.0",
    "js-yaml": "^4.3.2",
    "node-forge": "^1.3.2",
    "qs": "^6.17.1",
    "serialize-javascript": "^7.1.4",
    "tinypool": "^2.2.0"
  },
  "browserslist": {
    "production": [
      ">0.5%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "raw-loader": "^4.0.2",
    "react-markdown": "^10.1.0"
  }
}

---

### Tsconfig.Json (`docs/tsconfig.json`)

{
  "extends": "@docusaurus/tsconfig",
  "compilerOptions": {
    "baseUrl": "."
  },
  "exclude": [".docusaurus", "build"]
}

---

### Adrs 0001 Gateway First Architecture (`docs/adrs/0001-gateway-first-architecture.md`)

# ADR-0001: Gateway-First Architecture

- **Status:** Accepted
- **Date:** 2025-05-06
- **Authors:** Sebastien Han

## Context

OGX is an OpenAI-compatible agentic API server with pluggable inference
backends. As the project moves toward production multi-tenant deployments,
we need to define what OGX is responsible for versus what belongs in the
infrastructure layer (gateway, service mesh, load balancer).

The server previously included middleware for TLS termination, CORS,
request quota/rate limiting, and application-level authentication and
authorization. Some of these duplicate concerns that purpose-built gateways
(Envoy, Solo, Kong) handle better.

## Decision

OGX adopts a gateway-first architecture. Edge concerns are offloaded to the
gateway. Resource authorization and tenant isolation stay in OGX because
they require application state.

### What the gateway handles

- **TLS termination at the edge.** Handled by the gateway or load balancer
  in front of OGX. OGX retains server-level TLS config for east-west
  encryption (mTLS between gateway and backend) and non-gateway
  deployments.

- **Edge rate limiting and IP allowlisting.** The gateway has better
  visibility into client identity at the network layer and can enforce these
  policies with purpose-built tooling.

- **CORS.** A browser-facing concern handled at the gateway or CDN layer.

- **Circuit breaking and load balancing.** Infrastructure-level concerns
  that belong in the service mesh or gateway.

- **Request routing across OGX instances.** The gateway or service mesh
  handles this.

- **Authentication (production).** The gateway validates tokens against
  the IdP and injects identity headers (tenant_id, user_id, claims)
  before forwarding to OGX. The gateway must strip any client-supplied
  identity headers to prevent spoofing. Direct auth providers (OAuth2,
  Kubernetes, custom, GitHub) remain supported for development and
  single-tenant deployments where a gateway is optional.

### What OGX handles

- **Identity and tenant extraction.** OGX extracts principal, tenant_id,
  and user attributes from the auth result. In gateway mode, this comes
  from injected headers via `UpstreamHeaderAuthProvider`. In direct auth
  mode, from JWT claims, Kubernetes tokens, or custom auth responses.

- **Resource authorization (ABAC).** OGX matches user attributes against
  resource-level `access_attributes` and checks resource ownership. This
  covers models, vector stores, files, shields, and tool groups.

- **Tenant isolation on stored resources.** Stateful resources
  (conversations, response items, files, vector store entries, registry
  entries) are tagged with tenant_id and user_id. All queries filter by
  tenant context.

- **Semantic request metrics.** Application-level metrics (per-API method
  latency, concurrent requests by API) that the gateway cannot produce.

- **Request context propagation.** Provider data, test context, and client
  version checks.

### Why resource authorization cannot move to the gateway

Consider a `POST /v1/responses` call that references a model, attached
files, a vector store for retrieval, and a previous conversation:

```http
POST /v1/responses
Authorization: Bearer <token>

{
  "model": "llama3",
  "input": "Summarize the Q3 report",
  "tools": [{"type": "file_search", "vector_store_ids": ["vs_abc123"]}],
  "previous_response_id": "resp_xyz789"
}
```

The gateway can validate the token and inject identity headers. It can even
see "llama3" in the request body. But it cannot verify:

- Whether `vs_abc123` belongs to this user's tenant in OGX's storage
- Whether `resp_xyz789` is a conversation this user owns
- Whether the files attached to the vector store are accessible to this user
- Whether the model's `access_attributes` match this user's claims

All of those checks require querying OGX's database. The gateway would need
to make callouts to OGX for every resource reference in every request, which
defeats the purpose of having a gateway.

### Trust boundary

The following are hard deployment invariants, not soft guidance:

- **Gateway-only reachability.** OGX must not be directly reachable by
  clients when using `upstream_header` auth. The
  `UpstreamHeaderAuthProvider` trusts gateway-injected headers without
  validation. If clients can reach OGX directly, they can forge identity
  headers. Network policy or firewall rules must enforce this.

- **Header stripping.** The gateway must strip any client-supplied
  identity headers (principal, tenant, attribute headers) before
  forwarding to OGX. If the gateway does not strip these headers, a
  client can inject arbitrary identity claims.

- **Tenant context is auth-resolved only.** Tenant partitioning always
  uses the tenant_id resolved by the auth provider from trusted sources
  (gateway headers, JWT claims, auth endpoint response). It must never
  come from client-controlled request body fields, search filters, or
  `X-OGX-Provider-Data` headers. The passthrough provider infrastructure
  already forwards arbitrary provider-data keys downstream, so these
  namespaces must remain strictly separated.

## Consequences

### Middleware removed

As a direct result of this decision, the following middleware and
configuration were removed from OGX:

- **QuotaMiddleware** and `QuotaConfig` -- gateway handles rate limiting
- **CORSMiddleware** and `CORSConfig` -- gateway handles CORS

Server-level TLS config (`tls_certfile`, `tls_keyfile`, `tls_cafile` on
`ServerConfig`) is retained for east-west encryption and non-gateway
deployments. Auth provider TLS fields (for outbound connections to auth
endpoints) are also unaffected.

### Middleware retained

- **AuthenticationMiddleware** -- extracts identity from tokens or
  gateway-injected headers
- **RouteAuthorizationMiddleware** -- enforces route-level access policies
- **RequestMetricsMiddleware** -- semantic per-API metrics
- **ProviderDataMiddleware** -- request context propagation
- **ClientVersionMiddleware** -- protocol compatibility checks
- **ZstdDecompressionMiddleware** -- request body decompression

### Planned: Identity Header Contract

There is no IETF standard for passing authenticated user identity from a
gateway to a backend service. RFC 7239 covers network-level forwarding
(IP, protocol, host) but not user claims. Each gateway has its own
mechanism for extracting JWT claims and injecting them as headers:

- Envoy Gateway: SecurityPolicy `claimToHeaders` mapping
- Istio: `RequestAuthentication` with `claim-to-header`
- Envoy ext_authz: `allowed_upstream_headers` from the auth response
- Kong, Solo, etc.: similar claim-to-header mechanisms

The common pattern is: the gateway extracts individual JWT claims and maps
each one to a named HTTP header. The backend declares which headers it
expects.

**Current limitation.** The `UpstreamHeaderAuthProvider` accepts one
`principal_header` (a plain string) and one optional `attributes_header`
(a JSON-encoded dict). The JSON blob approach forces the gateway to
serialize all claims into a single header value, which most gateway
claim-to-header mechanisms cannot do natively. They map one claim to one
header.

**Planned change.** Replace the single JSON attributes header with
per-attribute header mapping so that each user attribute gets its own
header. This aligns with how gateways actually work:

```yaml
server:
  auth:
    provider_config:
      type: upstream_header
      principal_header: x-user-id
      tenant_header: x-tenant-id
      attribute_headers:
        roles: x-user-roles
        teams: x-user-teams
        namespaces: x-user-namespaces
```

On the gateway side, the claim-to-header config maps directly:

```yaml
# Envoy Gateway SecurityPolicy example
claimToHeaders:
  - claim: sub
    header: x-user-id
  - claim: tenant
    header: x-tenant-id
  - claim: roles
    header: x-user-roles
  - claim: groups
    header: x-user-teams
```

Each header value is either a single string or a comma-separated list.
OGX normalizes each value to `list[str]` (splitting on commas for
multi-valued attributes). No JSON encoding required.

The existing `attributes_header` (JSON blob) should be retained for
backward compatibility but documented as deprecated in favor of the
per-attribute header mapping.

### Planned: Tenant Isolation Model

Multi-tenant isolation does not exist today. The current system provides
ABAC (`access_attributes` matching) and resource ownership
(`owner_principal`) but not tenant scoping.

#### Why ABAC alone is not a tenancy boundary

The current default ABAC policy is: owner OR any overlapping attribute
category OR unowned. This is a sharing mechanism, not an isolation
boundary. If two tenants accidentally share an attribute value (e.g. both
have `teams: ["engineering"]`), their data becomes visible to each other.
Using ABAC attributes as the implicit tenant boundary provides no hard
isolation guarantee.

#### Design: explicit `tenant_id` as the partition key

Treat `tenant_id` like a Kubernetes namespace: it is the hard partition
key, not just another attribute. ABAC operates within a tenant for
fine-grained sharing. One active tenant per request.

**Tenant resolution is auth-provider-agnostic.** Every auth provider can
resolve a tenant, not just upstream headers:

| Auth provider | Tenant source |
|---------------|---------------|
| `upstream_header` | Dedicated `tenant_header` |
| `oauth2_token` | JWT claim (e.g. `tenant` or `org`) via `tenant_claim` config |
| `kubernetes` | Namespace or service account annotation |
| `custom` | Auth endpoint response field |
| `github_token` | Organization |
| None (dev mode) | `default_tenant_id` in server config |

**Tenancy modes:**

- **`disabled`** (default, current behavior) — no tenant enforcement.
  Existing single-tenant and ABAC-only deployments continue unchanged.
- **`single`** — all resources belong to one configured tenant. For
  single-tenant production or dev mode. A `default_tenant_id` is set in
  config and injected into every request. No gateway required.
- **`multi`** — full tenant isolation. Every request must resolve a
  tenant_id. Requests without one are rejected on tenant-scoped routes.

#### Request context

Extend the auth result to include `tenant_id` as a first-class field
alongside `principal` and `attributes`. This becomes part of the request
context propagated through `request_headers.py` and `task.py` for
background work.

```python
# Conceptual — extend User or create a new type
class User(BaseModel):
    principal: str
    tenant_id: str | None = None
    attributes: dict[str, list[str]] | None = None
```

#### Storage enforcement

`tenant_id` is applied **before** ABAC. The query path becomes:

1. Filter by `tenant_id = current_tenant` (hard partition)
2. Then apply ABAC: owner OR matching attributes (intra-tenant sharing)

**SQL-backed storage:**

- Add `tenant_id` column to every tenant-scoped table
- `AuthorizedSqlStore` applies `WHERE tenant_id = ?` before ABAC filters
- On PostgreSQL, add Row-Level Security (RLS) as defense-in-depth after
  the app-level filter is in place

**KV-backed storage:**

- Add a `TenantScopedKVStore` wrapper that prefixes keys with tenant_id
- Applies to: vector store metadata/chunks/file batches
  (`OpenAIVectorStoreMixin`), agent state persistence, and any KV surface
  not yet migrated to SQL

**File storage:**

- Partition physical/object storage paths by tenant, not just metadata

#### Global catalog vs tenant state

Split the resource registry into two layers:

- **Global catalog.** Provider-listed models and distro-defined shared
  resources (`source: listed_from_provider`). Cached process-wide.
  Visible to all tenants.
- **Tenant registry.** User-created resources
  (`source: via_register_api`). Scoped to the creating tenant. Queried
  per-request by current tenant, not preloaded into a global cache.

The current `DistributionRegistry` is a single global KV keyspace with
process-wide caching. In multi-tenant mode, tenant-created entries must
not be cached globally, as that leaks resource existence across tenants.

#### Storage surfaces requiring tenant partitioning

All of the following currently use global keys or lack tenant scoping:

**SQL-backed (via `AuthorizedSqlStore`):**

- Conversations (`openai_conversations` table)
- Conversation messages (`conversation_messages` table)
- Response objects and response items
- File metadata
- Prompts (after migration from KV to SQL)
- Connectors (after migration from KV to SQL)
- Batches (after migration from KV to SQL)

**KV-backed:**

- Distribution registry (`DistributionRegistry` in `registry.py`)
- Vector store metadata, file metadata, chunks, file batches
  (`OpenAIVectorStoreMixin` keyspaces)
- Agent state persistence (inline responses provider)

#### Cross-tenant access

Cross-tenant admin access must not use overlapping attributes (that
defeats the isolation boundary). Instead:

- Explicit tenant switch: admin authenticates, then selects a target
  tenant via a platform role (e.g. `platform_admin`)
- Audit logging for all cross-tenant operations
- Use opaque stable tenant IDs, not human-readable names

#### Migration strategy

**Phase 1: Tenant context and config.**
Add tenancy mode config (`disabled` / `single` / `multi`), tenant
resolution to all auth providers, and `tenant_id` to request context.
Existing deployments default to `disabled` and are unaffected.

**Phase 2: SQL tenant column.**
Add `tenant_id` to conversations, responses, and file metadata tables
(already centralized through `AuthorizedSqlStore`). Backfill existing
rows. In `single` mode, backfill to the configured default tenant. In
`multi` mode, require an operator-supplied mapping. Do not auto-infer
tenants from ABAC attributes.

**Phase 3: Prompts, connectors, batches.**
Complete the KV-to-SQL migration (aligned with PR #5614's direction)
behind tenant-aware storage. These resources move to
`AuthorizedSqlStore` with `tenant_id` from the start.

**Phase 4: Registry and KV surfaces.**
Split the distribution registry into global and tenant halves. Add
`TenantScopedKVStore` for remaining KV surfaces (vector store metadata,
agent state). Stop preloading tenant-created state into process-wide
cache.

**Phase 5: Hardening.**
Enable PostgreSQL RLS as defense-in-depth. Add tenant-scoped audit
logging. Remove the `disabled` tenancy mode for new deployments.

**Backfill rules:**

- Existing rows with empty `owner_principal` are currently treated as
  public. When tenant isolation is enabled, untagged rows must not be
  accessible to any tenant (default deny).
- A migration must tag existing rows with a `tenant_id` before switching
  to `single` or `multi` mode.
- Running with mixed tagged/untagged rows and tenant isolation enabled
  is not supported.

---

### Adrs Original Rfc (`docs/adrs/original_rfc.md`)

# The OGX API


*Originally authored Jul 23, 2024*

**Authors:**

* Meta: @raghotham, @ashwinb, @hjshah, @jspisak

## Summary

As part of the Llama 3.1 release, Meta is releasing an RFC for ‘OGX’, a comprehensive set of interfaces / API for ML developers building on top of Llama foundation models. We are looking for feedback on where the API can be improved, any corner cases we may have missed and your general thoughts on how useful this will be. Ultimately, our hope is to create a standard for working with Llama models in order to simplify the developer experience and foster innovation across the Llama ecosystem.

## Motivation

Llama models were always intended to work as part of an overall system that can orchestrate several components, including calling external tools. Our vision is to go beyond the foundation models and give developers access to a broader system that gives them the flexibility to design and create custom offerings that align with their vision. This thinking started last year when we first introduced a system-level safety model. Meta has continued to release new components for orchestration at the system level and, most recently in Llama 3.1, we’ve introduced the Llama Guard 3 safety model that is multilingual, a prompt injection filter, Prompt Guard and refreshed v3 of our CyberSec Evals. We are also releasing a reference implementation of an agentic system to demonstrate how all the pieces fit together.

While building the reference implementation, we realized that having a clean and consistent way to interface between components could be valuable not only for us but for anyone leveraging Llama models and other components as part of their system. We’ve also heard from the community as they face a similar challenge as components exist with overlapping functionality and there are incompatible interfaces and yet don't cover the end-to-end model life cycle.

With these motivations, we engaged folks in industry, startups, and the broader developer community to help better define the interfaces of these components. We’re releasing this OGX RFC as a set of standardized and opinionated interfaces for how to surface canonical toolchain components (like inference, fine-tuning, evals, synthetic data generation) and agentic applications to ML developers. Our hope is to have these become well adopted across the ecosystem, which should help with easier interoperability. We would like for builders of multiple components to provide implementations to these standard APIs so that there can be vertically integrated “distributions” of the OGX that can work out of the box easily.

We welcome feedback and ways to improve the proposal. We’re excited to grow the ecosystem around Llama and lower barriers for both developers and platform providers.

## Design decisions

Meta releases weights of both the pretrained and instruction fine-tuned Llama models to support several use cases. These weights can be improved  -  fine tuned and aligned - with curated datasets to then be deployed for inference to support specific applications. The curated datasets can be produced manually by humans or synthetically by other models or by leveraging human feedback by collecting usage data of the application itself. This results in a continuous improvement cycle where the model gets better over time. This is the model life cycle.

### Model Lifecycle



For each of the operations that need to be performed (e.g. fine tuning, inference, evals etc) during the model life cycle, we identified the capabilities as toolchain APIs that are needed. Some of these capabilities are primitive operations like inference while other capabilities like synthetic data generation are composed of other capabilities. The list of APIs we have identified to support the lifecycle of Llama models is below:

* /datasets - to support creating training and evaluation data sets
* /post_training - to support creating and managing supervised finetuning (SFT) or preference optimization jobs
* /evaluations - to support creating and managing evaluations for capabilities like question answering, summarization, or text - generation
* /synthetic_data_generation - to support generating synthetic data using data generation model and a reward model
* /reward_scoring - to support synthetic data generation
* /inference - to support serving the models for applications

### Agentic System



In addition to the model lifecycle, we considered the different components involved in an agentic system. Specifically around tool calling and shields. Since the model may decide to call tools, a single model inference call is not enough. What’s needed is an agentic loop consisting of tool calls and inference. The model provides separate tokens representing end-of-message and end-of-turn. A message represents a possible stopping point for execution where the model can inform the execution environment that a tool call needs to be made. The execution environment, upon execution, adds back the result to the context window and makes another inference call. This process can get repeated until an end-of-turn token is generated.
Note that as of today, in the OSS world, such a “loop” is often coded explicitly via elaborate prompt engineering using a ReAct pattern (typically) or preconstructed execution graph. Llama 3.1 (and future Llamas) attempts to absorb this multi-step reasoning loop inside the main model itself.

**Let's consider an example:**

1. The user asks the system "Who played the NBA finals last year?"
1. The model "understands" that this question needs to be answered using web search. It answers this abstractly with a message of the form "Please call the search tool for me with the query: 'List finalist teams for NBA in the last year' ". Note that the model by itself does not call the tool (of course!)
1. The executor consults the set of tool implementations which have been configured by the developer to find an implementation for the "search tool". If it does not find it, it returns an error to the model. Otherwise, it executes this tool and returns the result of this tool back to the model.
1. The model reasons once again (using all the messages above) and decides to send a final response "In 2023, Denver Nuggets played against the Miami Heat in the NBA finals." to the executor
1. The executor returns the response directly to the user (since there is no tool call to be executed.)

The sequence diagram that details the steps is in the [agentic system docs](https://github.com/meta-llama/llama-agentic-system/blob/main/docs/sequence-diagram.md).

* /memory_banks - to support creating multiple repositories of data that can be available for agentic systems
* /agentic_system - to support creating and running agentic systems. The sub-APIs support the creation and management of the steps, turns, and sessions within agentic applications.
  * /step - there can be inference, memory retrieval, tool call, or shield call steps
  * /turn - each turn begins with a user message and results in a loop consisting of multiple steps, followed by a response back to the user
  * /session - each session consists of multiple turns that the model is reasoning over
  * /memory_bank - a memory bank allows for the agentic system to perform retrieval augmented generation

## OGX API/CLI

We define the OGX as a layer cake shown below.



The API is defined in the [YAML](../static/ogx-spec.yaml) file.

## Sample implementations

To prove out the API, we implemented a handful of use cases to make things more concrete. The [Llama Stack Apps](https://github.com/ogx-ai/llama-stack-apps) repository contains [6 different examples](https://github.com/ogx-ai/llama-stack-apps/tree/main/examples) ranging from very basic to a multi turn agent.

There is also a sample inference endpoint implementation in the [OGX](https://github.com/ogx-ai/ogx/blob/main/src/ogx/core/server/server.py) repository.

## Limitations

The reference implementation for OGX APIs to date only includes sample implementations using the inference API. We are planning to flesh out the design of OGX Distributions (distros) by combining capabilities from different providers into a single vertically integrated stack. We plan to implement other APIs and, of course, we’d love contributions!!

Thank you in advance for your feedback, support and contributions to make this a better API.

Cheers!

---

### Blog 2026 01 13 Introducing Llama Stack (`docs/blog/2026-01-13-introducing-llama-stack.md`)

---
slug: introducing-ogx
title: Introducing OGX - The Open-Source Platform for Building AI Applications
authors: [ogx-team]
tags: [announcement, introduction, getting-started]
date: 2026-01-22
---

Welcome to our blog!

We're excited to introduce you to **OGX** - the open-source platform that simplifies building production-ready generative AI applications.



## What is OGX?

OGX defines and standardizes the core building blocks needed to bring generative AI applications to market, centered on the [Open Responses specification](https://www.openresponses.org/). By aligning with OpenAI’s open-sourced Responses API, OGX provides a consistent, interoperable foundation for building agentic and generative systems. It offers a growing suite of open-source APIs—including prompts, conversations, files, models, embeddings, fine-tuning, and MCP—enabling seamless transitions from local development to production across providers and environments.

Think of OGX as a universal interface that abstracts away the complexity of working with different AI tools and provider (e.g., vector databases, model inference providers, and deployment environments). Whether you're building locally, deploying on-premises, or scaling in the cloud, OGX provides a consistent developer experience.

## Key Features

### Unified API Layer

OGX provides standardized APIs across six core capabilities:

- **Inference**: Run models locally or in the cloud with a consistent interface
- **Vector Stores**: Build knowledge and agentic retrieval systems
- **Agents**: Create intelligent agent flows with responses/conversations
- **Tools and MCP**: Integrate with external tools and services directly or via MCP
- **Moderations**: Built-in safety guardrails and content filtering via moderations api

### Plugin Architecture

The plugin architecture supports a rich ecosystem of API implementations across different environments:

- **Local Development**: Start with CPU-only setups for rapid iteration
- **On-Premises**: Deploy in your own infrastructure
- **Cloud**: Scale with hosted providers

### Prepackaged Distributions

Distributions are pre-configured bundles of provider implementations that make it easy to get started. You can begin with a local setup using Ollama and seamlessly transition to production with vLLM - all without changing your application code.

### Multiple Developer Interfaces

OGX supports various developer interfaces:

- **CLI**: Command-line tools for server management
- **Python SDK**: [`ogx-client-python`](https://github.com/ogx-ai/ogx-client-python)
- **TypeScript SDK**: [`ogx-client-typescript`](https://github.com/ogx-ai/ogx-client-typescript)

## Why OGX?

### Flexibility Without Compromise

Developers can choose their preferred infrastructure without changing APIs. This means you can:

- Start locally for development
- Test with different providers
- Deploy to production with your chosen infrastructure
- Switch providers as your needs evolve

All while maintaining the same codebase and APIs.

### Consistent Experience

With unified APIs, OGX makes it easier to:

- Build applications with consistent behavior
- Test across different environments
- Deploy with confidence
- Maintain and update your codebase

### Robust Ecosystem

OGX integrates with distribution partners including:

- **Cloud Providers**: AWS Bedrock, Together, Fireworks, and more
- **Hardware Vendors**: NVIDIA, Cerebras, SambaNova
- **Vector Databases**: ChromaDB, Milvus, Qdrant, Weaviate, PostgreSQL, ElasticSearch
- **AI Companies**: OpenAI, Anthropic, Google Gemini

For a complete list, check out our [Providers Documentation](/docs/providers).

## How It Works

OGX consists of two main components:

1. **Server**: A server with pluggable API providers that can run in various environments
2. **Client SDKs**: Libraries for your applications to interact with the server

The server handles all the complexity of managing different providers, while the client SDKs provide a simple, consistent interface for your application code.

Refer to the [Quick Start Guide](https://ogx-ai.github.io/docs/getting_started/quickstart) to get started building your first AI application with OGX.

## What's Next?

See the [OGX Office Hours Content Calendar](https://docs.google.com/document/d/1it-OsGFgAIwAUctQRQ-j1CBxFHhvSm530YR67eYGW1I/edit?tab=t.4uf22mux1a94) for upcoming topics and the blog roadmap.

## Join the Community

We'd love to have you join our growing community:

- [Star us on GitHub](https://github.com/ogx-ai/ogx)
- [Join our Discord](https://discord.gg/bUYRqEvK6)
- [Read the Documentation](/docs)
- [Report Issues](https://github.com/ogx-ai/ogx/issues)

## Conclusion

OGX is designed to make building AI applications simpler, more flexible, and more maintainable. By providing unified APIs and a rich ecosystem of providers, we're enabling developers to focus on what matters most - building great applications.

Whether you're just getting started with AI or building production systems at scale, OGX has something to offer. We're excited to see what you'll build!

---

### Blog 2026 01 30 How To Get Started (`docs/blog/2026-01-30-how-to-get-started.md`)

---
slug: how-to-get-started-with-ogx
title: How to Get Started with OGX
authors: [cdoern, nathan-weinberg, ogx-team]
tags: [introduction, how-to]
date: 2026-01-30
---

There is no shortage of GenAI hosted services like OpenAI, Gemini, and Bedrock.



Often, these services require tailoring your GenAI application directly to them, requiring developers to consider things that have nothing to do with their applications. OGX is an open source project aiming to standardize and offer a set of APIs for AI applications that stay the same, regardless of the backend services being provided via those APIs.

OGX’s APIs allow for a variety of use cases from running inference with Ollama on your laptop to a self-managed GPU system running inference with vLLM to a pure SaaS-based solution like Vertex. The standardized set of APIs each have providers that follow the same REST API implementation. An admin of the stack can specify which provider they want for each API and expose the REST API to users who get the same frontend experience regardless of the provider. This can allow you to run a single API surface layer using whatever Inference, Vector IO, or other solutions you may want while keeping your GenAI applications simple.

A OGX is defined by its `config.yaml` file which holds key information like which APIs you want to expose, which providers you want to initialize for those APIs, their configuration, and more. OGX features a CLI that allows you to launch and manage servers, either run locally on your machine or in a container!

Here is a sample portion of a `config.yaml`:

```yaml
version: 2
distro_name: starter
apis:
- agents
- batches
- datasetio
- eval
- files
- inference
- post_training
- safety
- scoring
- tool_runtime
- vector_io
providers:
inference:
- provider_id: ${env.OLLAMA_URL:+ollama}
provider_type: remote::ollama
config:
base_url: ${env.OLLAMA_URL:=http://localhost:11434/v1}
...

```

The current set of OGX APIs can be found here: [https://ogx-ai.github.io/docs/api-overview](https://ogx-ai.github.io/docs/api-overview)

All of these APIs, if set in the `config.yaml` which defines the stack to be stood up, will be available via a REST API with their initialized providers. Each API can have one or more providers and the `provider_id` can be specified at request time.

To get started quickly, all you need is OGX, Ollama, and your favorite inference model! For this example, we are using `gpt-oss:20b`.

If you already have Ollama installed as a service, you can simply pull the model:

```bash
ollama pull gpt-oss:20b
uv run --with ogx ogx stack list-deps --providers inference=remote::ollama --format uv | sh
uv run --with ogx ogx run --providers inference=remote::ollama

```

If you don't have Ollama running as a service, you can start it manually:

```bash
ollama serve > /dev/null 2>&1 &
ollama run gpt-oss:20b --keepalive 60m # you can exit this once the model is running due to --keepalive
uv run --with ogx ogx --providers inference=remote::ollama --format uv | sh
uv run --with ogx ogx run --providers inference=remote::ollama

```

Now you have Ollama running with `gpt-oss:20b`, and OGX running pointing to Ollama as the inference provider. This minimal setup is sufficient to connect to local Ollama and respond to `/v1/chat/completions` requests.

For a more feature-rich setup, you can use the starter distribution which gives you a full stack with additional APIs and providers:

```bash
ollama serve > /dev/null 2>&1 &
ollama run gpt-oss:20b --keepalive 60m # you can exit this once the model is running due to --keepalive
uv run --with ogx ogx stack list-deps starter --format uv | sh
export OLLAMA_URL=http://localhost:11434/v1
uv run --with ogx ogx run starter

```

A sample chat completion request would look like this:

```bash
curl -X POST http://localhost:8321/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "ollama/gpt-oss:20b",
"messages": [{"role": "user", "content": "Hello!"}]
}'

```

Notice, the model name must be prefixed with the `provider_id` in order for the request to route properly! In this example, we are just utilizing the `/chat/completions` route in the Inference API. The starter distribution has a large amount of APIs and ready to use providers baked in. Example API requests, similar to the one above, for other APIs can be found in the [OGX API specification](https://ogx-ai.github.io/docs/api/ogx-specification). Take it for a spin and see what you can do with OGX!

---

### Blog 2026 03 01 Building Agentic Flows (`docs/blog/2026-03-01-building-agentic-flows.md`)

---
slug: building-agentic-flows-with-conversations-and-responses
title: "Building a Self-Improving Agent with OGX"
authors: [raghotham]
tags: [agents, responses-api, conversations, prompts, tutorial]
date: 2026-03-01
---

What if your AI agent could improve itself? Most agent tutorials show a single loop — user asks a question, the agent calls some tools, returns an answer. But what happens when you need to systematically improve your agent's behavior over time?

In this post, we build a **ResearchAgent** that answers questions from an internal engineering knowledge base — and gets better at it automatically. The agent uses the Responses API agentic loop with `file_search` and client-side tools to research questions, and it owns its own system prompt. Every N calls, it benchmarks itself by using a different model to judge the results, and rewrites its own prompt via the Prompts API.

This is literally self-referential: **a OGX agent evaluating and improving itself** using the Responses API, Prompts API, and Vector Stores as its toolkit.



## What We're Building

A single `ResearchAgent` class that does two things:

1. **Research** (agentic): Uses the Responses API `while True` loop with server-side `file_search` and client-side function tools (`read_local_file`, `index_document`, `list_local_files`). The agent decides what to search, discovers unindexed local files, reads them, indexes the relevant ones, and searches again with the enriched knowledge base.
2. **Self-improvement** (deterministic): Every N calls to `research()`, the agent runs `evaluate_self()` to benchmark against test cases and `improve_self()` to rewrite its own system prompt. This is a fixed sequence — no LLM-driven tool selection, just the agent measuring and improving its own performance.

```text
┌──────────────────────────────────────────────────────────┐
│  ResearchAgent                                           │
│                                                          │
│  research(question)                                      │
│    Responses API agentic loop (while True):              │
│      Server-side: file_search → Vector Store             │
│      Client-side: read_local_file, index_document,       │
│                   list_local_files                       │
│    Increments call counter; triggers self-improvement    │
│    every N calls                                         │
│                                                          │
│  evaluate_self()                                         │
│    Run all test cases → judge answers (Responses API)    │
│    → log scores (SQLite ledger)                          │
│                                                          │
│  improve_self()                                          │
│    Read feedback → propose new prompt (Responses API)    │
│    → save new version (Prompts API)                      │
└──────────────────────────────────────────────────────────┘
```

## Prerequisites

- [Ollama](https://ollama.com) running locally with two models pulled: `llama3.1:8b` for the research agent and `gpt-oss:20b` as the judge
- A OGX server using the starter distribution, pointed at Ollama via the `OLLAMA_URL` environment variable
- Python SDK: `uv pip install ogx-client`

## The Research Loop

The research agent is the heart of the system — and the showcase for the Responses API agentic pattern. Unlike a simple single-call RAG agent, it has real decisions to make: the vector store might not have enough context, so the agent can discover local files, read them, index the relevant ones, and search again.

It has one server-side tool and three client-side function tools:

- **`file_search`** (server-side): Searches the vector store for relevant documents. The Responses API executes this automatically — no client code needed.
- **`read_local_file(path)`**: Reads an unindexed local file (e.g., a newly written postmortem not yet in the knowledge base).
- **`index_document(file_path)`**: Uploads a file to the vector store via the Files API and `vector_stores.files.create()`. This is the key insight: the agent actively curates the knowledge base.
- **`list_local_files(directory)`**: Discovers available `.md` and `.txt` files in a directory.

The internal `_run_query()` method is the standard Responses API agentic loop — keep calling `responses.create()` until the model stops emitting tool calls:

```
/* Detailed source-code truncated for AI context efficiency. */
```

The public `research()` method reads the agent's current prompt, runs the agentic loop, and increments a counter. Every N calls, it triggers self-improvement:

```python
class ResearchAgent:
    ...

    def research(self, question):
        """Answer a question.  Automatically self-improves every N calls."""
        current = self.client.prompts.retrieve(self.prompt_id)
        answer = self._run_query(question, current.prompt)

        self._call_count += 1
        if self.test_cases and self._call_count % self.optimize_every == 0:
            self.evaluate_self()
            self.improve_self()

        return answer
```

In a typical call, the agent searches the vector store via `file_search` (handled server-side). If the retrieved context is insufficient — say, a question about a recent outage whose postmortem hasn't been indexed yet — the agent calls `list_local_files` to discover available documents, `read_local_file` to inspect the relevant one, and `index_document` to add it to the vector store. Then it searches again with the enriched store and writes its final answer.

The `index_document` tool is worth highlighting — it's the agent actively curating its own knowledge base:

```python
class ResearchAgent:
    ...

    def _index_document(self, file_path):
        """Upload a local file to the vector store so it becomes searchable."""
        file = self.client.files.create(
            file=open(file_path, "rb"), purpose="assistants"
        )
        attach = self.client.vector_stores.files.create(
            vector_store_id=self.vector_store_id, file_id=file.id
        )
        while attach.status == "in_progress":
            time.sleep(0.5)
            attach = self.client.vector_stores.files.retrieve(
                vector_store_id=self.vector_store_id, file_id=file.id
            )
        return f"Indexed {file_path} (file_id={file.id}, status={attach.status})"
```

This uses the Files API to upload the document and `vector_stores.files.create()` to attach it to the store. After polling until indexing completes, the file is searchable by `file_search` in subsequent turns of the same query — or in future queries.

## Self-Improvement

The self-improvement cycle is where the agent benchmarks itself, then rewrites its own prompt based on the feedback.

### evaluate_self

`evaluate_self` runs the agent on every test case using its current system prompt, judges each answer with the judge model, and logs scores to the ledger:

```python
class ResearchAgent:
    ...

    def evaluate_self(self):
        """Benchmark against test cases and log scores."""
        current = self.client.prompts.retrieve(self.prompt_id)
        results = []
        for tc in self.test_cases:
            answer = self._run_query(tc["question"], current.prompt)
            judgment = self.client.responses.create(
                model=self.judge_model,
                input=(
                    f"Score the following answer on a scale of 0.0 to 1.0.\n\n"
                    f"Question: {tc['question']}\n"
                    f"Expected: {tc['expected']}\nActual: {answer}\n\n"
                    f'Respond with JSON: {{"score": <float>, "reasoning": "..."}}'
                ),
                stream=False,
            )
            score_data = json.loads(judgment.output_text)
            results.append({**tc, "actual": answer, **score_data})

        avg_score = sum(r["score"] for r in results) / len(results)
        self.ledger.log(self.prompt_id, current.version, avg_score, feedback)
        return {"results": results, "average_score": avg_score, "feedback": feedback}
```

### improve_self

`improve_self` reads the latest evaluation feedback from the ledger and uses the judge model to generate an improved system prompt, then saves it via the Prompts API:

```python
class ResearchAgent:
    ...

    def improve_self(self):
        """Propose and save an improved system prompt."""
        history = self.ledger.history(self.prompt_id)
        latest = history[-1]
        current = self.client.prompts.retrieve(self.prompt_id)

        response = self.client.responses.create(
            model=self.judge_model,
            input=(
                f"Improve this research agent's system prompt based on feedback.\n\n"
                f"Current prompt:\n{current.prompt}\n\n"
                f"Feedback:\n{latest['reasoning']}\n\n"
                f"Return ONLY the improved prompt text."
            ),
            stream=False,
        )
        new_prompt = response.output_text.strip()
        self.client.prompts.update(
            self.prompt_id, prompt=new_prompt, version=current.version
        )
```

The judge model does double duty — scoring answers *and* proposing improvements based on its own feedback. The Prompts API auto-increments versions on each `update()`, and the `version` parameter provides optimistic locking so concurrent experiments don't silently overwrite each other.

### optimize

For initial tuning (before the agent starts serving real queries), `optimize` runs the evaluate/improve cycle in a `for` loop:

```python
class ResearchAgent:
    ...

    def optimize(self, max_iterations=5):
        """Run the evaluate/improve cycle for N iterations."""
        for iteration in range(max_iterations):
            self.evaluate_self()
            self.improve_self()
```

## Running It

First, pull the models and start Ollama, then run the OGX starter distribution pointing at it:

```bash
ollama pull llama3.1:8b
ollama pull gpt-oss:20b
OLLAMA_URL=http://localhost:11434/v1 uv run --with ogx ogx run starter
```

The `OLLAMA_URL` environment variable tells the starter distribution to use Ollama as its inference provider. The server starts on `http://localhost:8321` by default.

Then create the agent with some engineering documents. Some docs are indexed in the vector store up front; others live in a local directory for the agent to discover and index on demand:

```
/* Detailed source-code truncated for AI context efficiency. */
```

The full implementation with tool schema generation and all supporting code is available at [self_improving_agent.py](./self_improving_agent.py).

## How It Works Under the Hood

The agent uses *both* kinds of Responses API tools for research:

- **Server-side tools** like `file_search` are executed automatically — the Responses API searches the vector store, retrieves relevant chunks, and feeds them to the model without any client code. This is what makes knowledge base search a single API call.
- **Client-side function tools** (`read_local_file`, `index_document`, `list_local_files`) return tool call objects for you to execute. The `while True` loop dispatches these, and the results feed back into the next `responses.create()` call. This is what lets the agent actively curate its knowledge base.

The agent combines both in a single loop: `file_search` results come back automatically within the response, while function calls need client-side execution. The model sees both sources of information and decides what to do next.

The self-improvement methods don't need any of this machinery. They call `responses.create()` directly for judging and prompt generation — no tool calling, no agentic loop. The Prompts API stores versioned prompt text with optimistic locking, and the SQLite ledger tracks how well each version performed. The `research()` counter ties it all together: the agent serves queries normally, and every N calls it pauses to evaluate and improve itself.

## What's Next

The pattern here — a self-improving agent that benchmarks and rewrites its own prompt — generalizes well beyond research assistants:

- **MCP tools** for connecting to external services (databases, APIs, code execution sandboxes) — the research agent could pull in live data alongside static documents
- **Web search** alongside `file_search` for agents that combine local knowledge with live web results
- **Multiple research agents** with different vector stores, each self-improving independently and specializing in a different knowledge domain

To learn more:

- [Responses API documentation](/docs/building_applications/responses_vs_agents)
- [Conversations API documentation](/docs/api-openai/conformance#conversations)
- [OpenAI API compatibility](/docs/api-openai)
- [Vector Stores documentation](/docs/building_applications/rag)
- [Join our Discord](https://discord.gg/bUYRqEvK6)

---

### Blog 2026 03 18 Responses Api (`docs/blog/2026-03-18-responses-api.md`)

---
slug: responses-api
title: "Your Agent, Your Rules: Building Powerful Agents with the Responses API in OGX"
authors:
  - jwm4
tags: [responses-api, agents, rag, mcp, open-responses]
date: 2026-03-18
---

The [Responses API](https://developers.openai.com/blog/responses-api) is rapidly emerging as one of the most influential interfaces for building AI agents. It handles multi-step reasoning, tool orchestration, and conversational state in a single interaction, which is a big improvement over the manual orchestration loops that developers had to build on top of chat completion APIs. OGX's implementation of the Responses API brings these capabilities to the open source world, where you can choose your own models and run on your own infrastructure.

This post covers why the Responses API matters, what OGX's implementation enables, and how it connects to the broader move toward open agent standards like Open Responses.



## Why the Responses API?

Before the Responses API, building an agent that could use tools was a multi-step exercise in client-side orchestration. Your application had to call the model with a list of available tools, inspect the response for tool call requests, execute those tools, send the results back, and repeat until the model produced a final answer. All of the state management, error handling, and retry logic lived in your code.

This approach put a real burden on application developers. The orchestration logic got duplicated across every application, and subtle mistakes in state management could lead to poor accuracy or unnecessary model calls.

The Responses API moves this orchestration to the server. The client sends a question along with a set of available tools and documents, and the server handles the planning, tool execution, and synthesis internally. Your client code gets much simpler, and the behavior is more consistent because the orchestration logic is shared rather than reimplemented by every application.

## What OGX brings to the table

OGX is an open source server for building AI applications. It provides a unified set of APIs for inference, RAG, tool calling, safety, evaluation, and more, backed by a pluggable provider architecture that lets you swap components without changing application code.

OGX implements the Responses API with support for built-in RAG through `file_search`, automated multi-tool orchestration through the Model Context Protocol (MCP), conversation state management, and compatibility with the OpenAI client ecosystem.

But the interesting part is what OGX adds beyond the API surface itself.

### Model freedom

With a proprietary hosted service, the Responses API is tied to a specific set of models from a single provider. With OGX, you can use any model accessible through its inference providers: open source models like the Llama family, fine-tuned models you've created yourself, or optimized models from the broader ecosystem. The same Responses API interface works regardless of which model backs it. You can start with a small model during development, scale up for production, or swap models entirely, and your application code stays the same.

### Data sovereignty

If you work in a regulated industry like finance, healthcare, or government, sending sensitive documents to a third-party cloud service is often a non-starter. OGX lets you run the entire stack on your own infrastructure: the model, the vector store for RAG, and the tool execution environment. Documents stay within your security perimeter, and the agent's reasoning about those documents does too.

### Open, extensible architecture

OGX's provider architecture means you are not locked into a single implementation for any component. Need FAISS for your vector store in development and Milvus in production? Change a configuration setting. Want to use Ollama locally and a cloud inference provider in production? Same application code, different distribution. This flexibility extends across the full OGX API surface, not just inference.

## Private RAG with `file_search`

Retrieval-augmented generation (RAG) grounds a model's responses in authoritative documents, which reduces hallucination and enables accurate answers from private knowledge bases.

The Responses API formalizes RAG with the `file_search` tool. You create a vector store, upload documents to it, and then include `file_search` as an available tool when calling the Responses API. The model generates search queries, retrieves relevant passages, and synthesizes them into a grounded answer, all in a single API call.

With OGX, this entire pipeline runs on your infrastructure. Document ingestion, embedding, storage, retrieval, and synthesis all happen locally. The response includes references to the source passages, so your application can provide citations for verification.

This makes it practical to build RAG applications over sensitive internal documents like compliance policies, medical records, or proprietary research, with confidence that the data never leaves your environment.

## Multi-tool orchestration with MCP

The Responses API gets especially interesting when an agent needs to coordinate multiple tools to answer a complex question. Consider a question like: "What parks are in Rhode Island, and are there any upcoming events at them?" Answering this requires discovering available tools, searching for parks, querying events for each park found, and synthesizing all the results.

With OGX's Responses API and MCP integration, this entire workflow happens within a single API call. The model discovers available tools from a connected MCP server, plans and executes a sequence of tool calls, and produces a consolidated answer. The client application doesn't need to write any orchestration logic.

MCP is an open standard for tool integration, so the ecosystem of available tools is broad and growing. Any MCP server can be connected to OGX and used by the Responses API, whether it provides access to databases, internal services, or external data sources.

OGX also provides fine-grained control over tool access. You can restrict which tools are available for a given request, pass per-request authentication headers to MCP servers so that an agent can only access data for the current user, and configure tool behavior without modifying the agent's prompt. This matters a lot in production deployments where security and access control are real concerns.

## Framework compatibility

OGX exposes OpenAI-compatible endpoints at `/v1`, so you can use the official OpenAI Python client, the OGX client, or any other client that speaks the OpenAI API. They all work the same way.

If you have existing code built with the OpenAI client, migrating to OGX means pointing your client at your OGX server. That's it. This also applies to frameworks like LangChain that build on top of OpenAI's API. Switching the inference backend to OGX requires changing a constructor parameter, not rewriting your agent logic.

This drop-in compatibility has practical implications beyond convenience. You can develop and test against a local OGX server, deploy against a production OGX distribution, or switch between OGX and other OpenAI-compatible providers, all with the same application code.

## Toward an open standard: Open Responses

When OGX first implemented the Responses API, the specification was proprietary. OGX had to track a moving target, and there was always a gap between when OpenAI added a feature and when OGX could implement it.

The [Open Responses specification](https://www.openresponses.org/) changes this. Open Responses is an open source specification backed by a broad community including OpenAI, Hugging Face, and providers like Ollama, vLLM, and LM Studio. It formalizes the core concepts of the Responses API into an open standard: items as the atomic unit of context, semantic streaming events, and the agentic loop of reasoning and tool invocation.

For OGX, Open Responses provides a stable, community-governed specification to build against rather than a proprietary one. It also means that OGX's Responses API implementation is part of a broader ecosystem of interoperable providers. Applications built against the Open Responses specification can run on OGX, on OpenAI, on Hugging Face's infrastructure, or on local providers like Ollama, without code changes.

The Open Responses specification also introduces concepts that matter for production deployments:

- **Reasoning visibility:** The specification formalizes how models expose their reasoning process, which enables audit trails and governance workflows.
- **Internal vs. external tools:** A clear distinction between tools executed within the provider's infrastructure (like `file_search`) and tools executed by the client, so developers know exactly where computation happens.
- **Extensibility without fragmentation:** Providers can add custom capabilities while maintaining a stable, interoperable core.

For the OGX community, this means that investing in the Responses API is about more than compatibility with one vendor. It's about building on an open standard that the industry is starting to converge around.

## Getting started

If you're new to OGX, the [Getting Started guide](https://ogx-ai.github.io/docs/getting_started/) will walk you through setting up a server with your preferred inference provider. From there, the [OpenAI Implementation Guide](https://ogx-ai.github.io/docs/providers/openai) has examples of using the Responses API for everything from simple text generation to multi-tool agentic workflows.

The Responses API is still evolving, both in OGX and in the Open Responses specification, and contributions are welcome. Whether it's implementing new features, improving test coverage, or reporting issues, the project benefits from developers who are building real applications and sharing what they learn.

---

### Blog 2026 03 20 Open Responses Openai Compatibility (`docs/blog/2026-03-20-open-responses-openai-compatibility.md`)

---
slug: open-responses-openai-compatibility
title: "OGX Achieves 100% Open Responses Compliance: Enterprise-Grade OpenAI Compatibility for Your Infrastructure"
authors: [franciscojavierarceo, cdoern]
tags: [openai-compatibility, open-responses, enterprise, mcp, connectors]
date: 2026-03-20
---

We're excited to share that OGX has achieved **100% compliance with the Open Responses specification** and been officially recognized as part of the [Open Responses community](https://github.com/openresponses/openresponses/pull/29). This milestone represents more than just compatibility: it's about bringing enterprise-grade AI capabilities to your own infrastructure with the familiarity of OpenAI APIs.

With comprehensive support for Files, Vector Stores, Search, Conversations, Prompts, Chat Completions, the full Responses API, plus powerful extensions like MCP tool integration, Tool Calling, and Connectors, OGX offers something unique in the AI infrastructure landscape: a SaaS-like experience that runs entirely on your terms.



## Recognition by the Open Responses Community

The [Open Responses initiative](https://www.openresponses.org/) represents a collaborative effort to standardize agentic AI interfaces across the industry, with backing from OpenAI, Hugging Face, and leading providers like Ollama, vLLM, and LM Studio. Our acceptance into this community validates OGX's commitment to open standards and interoperability.

What makes this recognition particularly meaningful is our approach to compliance. We don't just aim for compatibility—**we run the full Open Responses acceptance test suite on every pull request as a blocking requirement**. This means our perfect 6/6 test pass rate isn't a one-time achievement; it's a maintained standard that ensures consistent, reliable behavior for developers building on open standards.

## Comprehensive OpenAI API Feature Support

OGX delivers comprehensive feature parity across multiple API surfaces, giving you the full power of modern AI APIs.

> **A note on model IDs:** The model ID you pass depends on the inference provider backing your OGX server. For example, with Ollama you'd use `ollama/llama3.2:3b`, while with Fireworks or Together you'd use the HuggingFace-style `meta-llama/Llama-3.2-3B-Instruct`. The API calls are identical either way.

### **Files API** - OpenAI-Compatible Document Management

Upload, manage, and process documents with the same interface you'd use with OpenAI:

```python
# Works identically with OpenAI or OGX clients
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1/", api_key="none")

file = client.files.create(file=open("document.pdf", "rb"), purpose="assistants")

# List and manage files
files = client.files.list()
content = client.files.content(file.id)
```

### **Vector Stores API** - RAG Without Vendor Lock-in

Build retrieval-augmented generation applications using the full Vector Stores API:

```python
# Create vector stores with nested file management
vector_store = client.vector_stores.create(name="knowledge_base")

# Add files and manage vector store content
client.vector_stores.files.create(vector_store_id=vector_store.id, file_id=file.id)

# Search functionality built-in
results = client.vector_stores.search(
    vector_store_id=vector_store.id, query="What is our refund policy?"
)
```

### **Conversations API** - Persistent Context Management

Manage conversation state and continuity across interactions:

```python
# Create a conversation
conversation = client.conversations.create()

# Add items to a conversation
client.conversations.items.create(
    conversation_id=conversation.id,
    items=[
        {"role": "user", "content": "Tell me about our product features"},
        {"role": "assistant", "content": "I'd be happy to explain..."},
    ],
)

# Retrieve conversation history
items = client.conversations.items.list(conversation_id=conversation.id)
```

### **Chat Completions & Responses** - Simple Chat to Agentic Workflows

From straightforward inference to multi-tool orchestration:

```python
# Standard chat completions (e.g., with Ollama)
completion = client.chat.completions.create(
    model="ollama/gpt-oss:20b", messages=[{"role": "user", "content": "Explain RAG"}]
)

# Advanced responses with tool orchestration (e.g., with Fireworks)
response = client.responses.create(
    model="ollama/gpt-oss:20b",
    input="What documents mention our pricing strategy?",
    tools=[{"type": "file_search"}],
)
```

### **Prompts API** - Programmatic Prompt Management

OGX extends OpenAI compatibility with full programmatic prompt management. With OpenAI, prompts are created through their admin portal and referenced by ID in the Responses API. OGX provides the same referencing pattern, plus a complete CRUD API for creating and managing prompts programmatically:

```python
from ogx_client import OgxClient

ls_client = OgxClient()

# Create reusable prompt templates with variables
prompt = ls_client.prompts.create(
    prompt="You are a {{ role }} assistant. Analyze this: {{ content }}",
    variables=["role", "content"],
)

# Reference prompts in responses — compatible with OpenAI's pattern
response = client.responses.create(
    model="ollama/gpt-oss:20b",
    input=[{"role": "user", "content": "Review our Q1 report"}],
    prompt={
        "id": prompt.prompt_id,
        "variables": {
            "role": {"type": "input_text", "text": "financial analyst"},
            "content": {"type": "input_text", "text": "Q1 2026 earnings report"},
        },
    },
)
```

This gives you the best of both worlds: compatibility with OpenAI's prompt referencing pattern in the Responses API, plus the ability to manage prompts as code rather than through a web interface.

### **MCP Integration** - Extensible Tool Ecosystem

Leverage the Model Context Protocol to connect to any MCP server and dynamically discover tools:

```python
# Connect to MCP servers for dynamic tool discovery
response = client.responses.create(
    model="ollama/gpt-oss:20b",
    input="What parks are in Rhode Island, and are there upcoming events?",
    tools=[
        {
            "type": "mcp",
            "server_label": "parks-service",
            "server_url": "http://parks-mcp-server:8000/sse",
        }
    ],
)
```

MCP tools support per-request authorization, allowed tool filtering, and automatic session management. Connect to databases, APIs, and internal services through the growing ecosystem of standard MCP servers—no custom integration work required.

### **Connectors** - Declarative Service Integration

Connectors provide a configuration-driven approach to integrating external services with your OGX deployment. Define your data sources and services in your stack configuration, and they're automatically available as tools for your agents to use.

## The Value Proposition: SaaS Experience, Your Infrastructure

### **Data Sovereignty & Security**

For regulated industries like finance, healthcare, and government, sending sensitive documents to external APIs isn't an option. OGX solves this by running entirely on your infrastructure:

- **Documents never leave your environment**: RAG pipelines, vector storage, and model inference all happen locally
- **Compliance-ready**: Meet HIPAA, SOC 2, GDPR, and other regulatory requirements
- **Audit trails**: Full visibility into data processing and model decisions

### **Cost Control & Predictability**

Unlike consumption-based pricing models, OGX offers:

- **Fixed infrastructure costs**: Pay for compute, not tokens
- **No usage surprises**: Predictable costs regardless of application load
- **Efficient resource utilization**: Choose the right model size for your use case

### **Model Freedom**

Break free from vendor-specific models:

```python
# Same API, different models — swap without code changes
for model in ["ollama/gpt-oss:20b", "ollama/llama3.2:3b", "your-org/custom-model"]:
    response = client.chat.completions.create(model=model, messages=messages)
```

## Getting Started in Minutes

Whether you're prototyping locally or deploying at scale, OGX makes it easy:

### **Local Development**

```bash
# Set up your environment
uv venv --python 3.12 --seed
source .venv/bin/activate
uv pip install -U ogx
uv run ogx stack list-deps starter | xargs -L1 uv pip install

# Start Ollama and pull a model
ollama serve
ollama run gpt-oss:20b

# Launch OGX with the starter distribution

OLLAMA_URL=http://localhost:11434/v1 uv run ogx run starter
```

```python
# Use with the OpenAI client
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="none")

response = client.responses.create(
    model="ollama/gpt-oss:20b", input="Write a haiku about open source."
)
print(response.output_text)
```

### **Production Deployment**

```bash
# Deploy with your preferred infrastructure
# Docker, Kubernetes, or bare metal — your choice
docker run -p 8321:8321 ogxai/distribution-starter:latest
```

## Framework Ecosystem Compatibility

One of OGX's biggest advantages is **drop-in compatibility** with existing tooling:

### **Direct OpenAI Client**

```python
from openai import OpenAI

# Same code, different backend
client = OpenAI(base_url="http://your-ogx/v1", api_key="none")
```

### **LangChain Integration**

```python
from langchain_openai import ChatOpenAI

# Point to your OGX server
llm = ChatOpenAI(
    base_url="http://your-ogx/v1/openai/v1",
    api_key="none",
    model="ollama/gpt-oss:20b",
)
```

### **Native OGX Client**

```python
from ogx_client import OgxClient

# Access the full OGX API surface
client = OgxClient(base_url="http://your-ogx")
```

## Built for Open Standards

Our 100% Open Responses compliance reflects a broader philosophy: **open standards enable innovation**. When you build on OGX, you're not just adopting our implementation—you're investing in an ecosystem where:

- **Applications are portable**: Move between providers without rewriting code
- **Standards evolve collaboratively**: Community-driven development rather than vendor dictates
- **Innovation is shared**: Improvements benefit the entire ecosystem

## Technical Excellence Through Testing

Achieving 100% Open Responses compliance required rigorous engineering:

- **Perfect conformance testing**: Every PR runs the full Open Responses test suite with 6/6 passing tests
- **Automated compliance validation**: Blocking requirements ensure compliance is maintained, not achieved once
- **Production testing**: Integration tests with real workloads and multi-provider scenarios
- **Comprehensive API coverage**: Full implementation of the Open Responses specification

## What's Next

OGX's OpenAI compatibility is just the beginning. We're actively working on:

- **Enhanced streaming support**: Improved real-time response handling
- **Extended MCP ecosystem**: Deeper tool integration and connector development
- **Performance optimizations**: Faster inference and better resource utilization
- **Broader OpenAI API coverage**: Expanding compatibility beyond our current feature set

## Join the Open AI Infrastructure Movement

OGX represents something new in the AI infrastructure landscape: **enterprise-grade capabilities without vendor lock-in**. Whether you're a startup building your first AI application or an enterprise looking to bring AI workloads in-house, OGX provides the reliability, security, and compatibility you need.

Ready to get started?

- **📚 [Documentation](https://ogx-ai.github.io/docs/)**: Comprehensive guides and API references
- **🚀 [Getting Started](https://ogx-ai.github.io/docs/getting_started/)**: Quick setup tutorials
- **🔧 [OpenAI Implementation Guide](https://ogx-ai.github.io/docs/providers/openai)**: Detailed compatibility examples
- **🔌 [MCP Integration](https://ogx-ai.github.io/docs/building_applications/)**: Tool ecosystem and connector guides
- **💬 [Community](https://github.com/ogx-ai/ogx)**: Join discussions and contribute

The future of AI infrastructure is open, interoperable, and under your control. Welcome to OGX.

---

### Blog 2026 03 30 Observability (`docs/blog/2026-03-30-observability.md`)

---
slug: observability-for-ogx
title: "OGX Observability: Metrics, Traces, and Dashboards with OpenTelemetry"
authors: [gyliu513]
tags: [observability, opentelemetry, metrics, tracing, monitoring]
date: 2026-03-30
---

Running an LLM application in production is nothing like running a traditional web service. Responses are non-deterministic. Latency swings wildly with model size and token count. And failures are often silent — a tool call that returns garbage still comes back as a 200 OK. You can stare at your HTTP dashboard all day and have no idea that half your users are getting bad answers.

We recently shipped built-in observability for OGX, powered by [OpenTelemetry](https://opentelemetry.io/). Three environment variables, zero code changes, and you get metrics and traces from every layer — HTTP requests, inference calls, tool invocations, vector store operations, all the way down.

This post explains the architecture behind it, walks through a hands-on tutorial, and shows what you can actually see once it's running.



## Why Observability Matters for LLM Applications

If you've operated traditional services, you know the drill: uptime checks, error rates, latency percentiles. LLM applications need all of that, plus a whole category of signals that don't exist in conventional backends.

**Latency is multi-dimensional.** A single `/v1/responses` call might fan out to an inference provider, three tool calls, and two vector store queries. Knowing the overall P99 is 4 seconds doesn't help you — you need to know which leg is slow.

**Token economics drive cost.** Without tracking tokens-per-second and usage patterns across models and providers, capacity planning is guesswork.

**Time-to-first-token (TTFT) defines user experience.** A streaming response with a 5-second TTFT feels broken to the user, even if total latency is fine.

**Silent failures are common.** A tool invocation that times out, a vector search that returns zero results, a safety shield that blocks unexpectedly — none of these produce HTTP errors, but all degrade quality. You won't find them in your access logs.

**Provider comparison requires data.** When you run multiple inference backends (vLLM, Ollama, OpenAI), you need apples-to-apples latency and reliability numbers, not vibes.

## How We Instrumented OGX

We chose [OpenTelemetry](https://opentelemetry.io/) (OTel) — the CNCF's vendor-neutral standard for metrics, traces, and logs. The practical upside: you export to Prometheus, Grafana, Jaeger, Datadog, or any OTLP-compatible backend, and you can switch without touching application code.

The instrumentation has two layers that work together. Both feed into the OpenTelemetry SDK, which batches and exports signals to the Collector via OTLP.

### Auto instrumentation: the infrastructure view

Launch OGX with the `opentelemetry-instrument` CLI wrapper and you get — with zero code changes:

- Inbound HTTP spans and metrics from FastAPI (every API request)
- Outbound HTTP spans and metrics from httpx (calls to inference providers)
- Database query spans from SQLAlchemy and asyncpg
- GenAI call spans from OTel ecosystem packages for OpenAI, Bedrock, Vertex AI, etc. — model name, token counts, finish reasons, all captured at the SDK level

This covers the "infrastructure view": request flow, provider latency, GenAI call details, database performance.

### Manual instrumentation: the application view

Auto instrumentation doesn't know about OGX's domain concepts. So we added manual instrumentation directly in the routers and middleware to capture:

- **API request metrics** — total count, duration histogram, concurrent request gauge
- **Inference metrics** — end-to-end duration, TTFT, tokens-per-second
- **Vector IO metrics** — insert, query, and delete counts with duration
- **Tool runtime metrics** — invocation count and duration by tool name and status
- **Safety spans** — shield evaluation traces with attribute context

The two layers are complementary. Auto instrumentation tells you what's happening at the network and SDK level; manual instrumentation tells you what's happening at the application level. As a user, you don't need to care about any of this — just launch with `opentelemetry-instrument` and everything lights up.

## The OpenTelemetry Collector

Between OGX and your observability backends sits the [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/). It receives OTLP data, processes it, and fans out to one or more destinations.

```mermaid
graph LR
    LSS["OGX Server"] -->|"OTLP/HTTP push<br/>metrics + traces"| R
    LSC["OGX Client"] -->|"OTLP/HTTP push<br/>metrics + traces"| R

    subgraph "OpenTelemetry Collector"
        R["Receivers"] -->|"raw telemetry"| P["Processors"]
        P -->|"processed"| E["Exporters"]
    end

    E -->|"remote_write"| Prom["Prometheus"]
    E -->|"OTLP/gRPC"| Tempo["Grafana Tempo"]
    E -->|"OTLP"| Jaeger["Jaeger"]
    E -->|"OTLP"| DD["Datadog"]
```

The pipeline has three stages:

**Receivers** define how data enters. OGX pushes to the OTLP receiver on port 4318 (HTTP) or 4317 (gRPC). You can run additional receivers in parallel — for example, a Prometheus scrape receiver for other services in your infrastructure.

**Processors** transform data in flight. The ones that matter for production: `batch` (groups telemetry for efficient network transfer), `memory_limiter` (drops data under memory pressure instead of OOM-ing), `attributes` (inject labels like `environment=production`), and `filter` (drop noise like health check spans). They run in the order you define them — a typical chain is `memory_limiter → batch → attributes`.

**Exporters** send data to backends. `prometheusremotewrite` for Prometheus-compatible stores, `otlp` for Jaeger/Tempo/Datadog, `debug` for stdout during development. A single Collector can export metrics to Prometheus for dashboarding AND to Datadog for alerting simultaneously.

The key benefit: OGX only speaks OTLP. The Collector handles format conversion, retries, and routing. Swap backends without changing a line of application code.

## End-to-End Data Flow

Here's what happens when a request comes in:

```mermaid
sequenceDiagram
    participant Client
    participant LS as OGX
    participant SDK as OTel SDK (in-process)
    participant Collector as OTel Collector
    participant Prom as Prometheus
    participant Grafana

    Client->>LS: POST /v1/responses

    Note over LS: Auto: FastAPI creates inbound HTTP span
    Note over LS: Manual: RequestMetricsMiddleware<br/>increments concurrent_requests
    Note over LS: Manual: InferenceRouter records<br/>duration, TTFT, tokens/sec
    Note over LS: Auto: httpx creates outbound span<br/>to inference provider
    Note over LS: Manual: ToolRuntime records<br/>invocation count and duration

    LS->>Client: 200 OK (streaming response)

    Note over LS: Manual: RequestMetricsMiddleware records<br/>requests_total, request_duration_seconds,<br/>decrements concurrent_requests

    Note over LS,SDK: Metrics and spans buffered in SDK

    loop Periodic export (default: every 60s)
        SDK->>Collector: OTLP/HTTP POST /v1/metrics
        SDK->>Collector: OTLP/HTTP POST /v1/traces
        Note over Collector: Pipeline: memory_limiter → batch → attributes
        Collector->>Prom: remote_write (metrics)
    end

    Grafana->>Prom: PromQL query
    Note over Grafana: Dashboard shows latency,<br/>throughput, error rates
```

Two things worth noting. First, recording is non-blocking — metrics write to an in-memory buffer, so they add negligible latency to the request path. Second, export is batched — the SDK flushes every 60 seconds by default, which means dashboards have up to a minute of delay, but request handling is never blocked by network I/O to the Collector.

## Hands-On Tutorial

Let's set everything up. By the end you'll have distributed tracing in Jaeger, metrics in Prometheus, and pre-built dashboards in Grafana.

### Step 0: Prerequisites

You'll need:

- **Docker** or **Podman** for running the observability stack
- A working **OGX** installation with `uv`

Clone the repo if you haven't:

```bash
git clone https://github.com/ogx-ai/ogx.git
cd ogx
```

The telemetry configs live in [`scripts/telemetry/`](https://github.com/ogx-ai/ogx/tree/main/scripts/telemetry):

| File | What it does |
|---|---|
| `setup_telemetry.sh` | Starts all telemetry services |
| `otel-collector-config.yaml` | Collector pipeline config |
| `prometheus.yml` | Prometheus scrape config |
| `grafana-datasources.yaml` | Grafana datasource provisioning |
| `grafana-dashboards.yaml` | Grafana dashboard provisioning |
| `ogx-dashboard.json` | Pre-built Grafana dashboard |

### Step 1: Deploy the Observability Stack

One script brings up Jaeger, the OTel Collector, Prometheus, and Grafana:

```bash
# Auto-detect container runtime (podman or docker)
./scripts/telemetry/setup_telemetry.sh

# Or specify explicitly
./scripts/telemetry/setup_telemetry.sh --container docker
```

This creates a `llama-telemetry` container network, starts all four services, and provisions Grafana with a pre-built dashboard.

### Step 2: Install OpenTelemetry Packages

```bash
uv pip install opentelemetry-distro opentelemetry-exporter-otlp
uv run opentelemetry-bootstrap -a requirements | uv pip install --requirement -
```

`opentelemetry-bootstrap` detects your installed libraries (FastAPI, httpx, SQLAlchemy, OpenAI SDK, etc.) and installs the matching instrumentation packages automatically.

### Step 3: Launch the Server

Set three environment variables and wrap the launch command with `opentelemetry-instrument`:

```bash
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_SERVICE_NAME=ogx-server

uv run opentelemetry-instrument ogx run starter
```

That's it. When `OTEL_EXPORTER_OTLP_ENDPOINT` is set, both auto and manual instrumentation activate. When it's not set, metrics are recorded in memory but never exported — no overhead, no errors.

| Variable | Purpose | Example |
|----------|---------|---------|
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Collector endpoint | `http://localhost:4318` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Transport protocol | `http/protobuf` |
| `OTEL_SERVICE_NAME` | Service name in telemetry | `ogx-server` |
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval (ms) | `60000` (default) |

> **Tip**: If you see duplicate database traces, set `OTEL_PYTHON_DISABLED_INSTRUMENTATIONS="sqlite3,asyncpg"` to disable overlapping instrumentors.

### Step 4: Launch Your Client

To get end-to-end distributed tracing, launch your client the same way:

```bash
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_SERVICE_NAME=my-ogx-app

opentelemetry-instrument python my_app.py
```

A minimal example:

```python
from openai import OpenAI

client = OpenAI(api_key="fake", base_url="http://localhost:8321/v1/")

response = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello, how are you?"}],
)
print(response.choices[0].message.content)
```

With `opentelemetry-instrument`, this client automatically generates GenAI spans (model, token counts, finish reasons) and HTTP spans, all correlated with server-side traces via W3C trace context propagation.

By default, message content (prompts, outputs, tool arguments) is **not** captured for privacy. To enable content capture for debugging:

```bash
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true \
opentelemetry-instrument python my_app.py
```

Captured content appears as log events (`gen_ai.user.message`, `gen_ai.choice`) correlated with trace spans via `trace_id`/`span_id`. The spans themselves carry structured metadata (model, token usage, latency) but not the raw text.

### Step 5: Explore the Data

Once traffic is flowing:

| Service | URL | Credentials |
|---|---|---|
| **Jaeger** (traces) | [http://localhost:16686](http://localhost:16686) | N/A |
| **Prometheus** (metrics) | [http://localhost:9090](http://localhost:9090) | N/A |
| **Grafana** (dashboards) | [http://localhost:3000](http://localhost:3000) | admin / admin |

#### Jaeger: Distributed Traces

Select the `ogx-server` or `my-ogx-app` service to see request traces. Each trace shows the full request lifecycle — client HTTP call → FastAPI handler → inference provider call → database operations. You can pinpoint exactly where time is spent.



#### Prometheus: Metrics Queries

Some useful PromQL to get you started:

| What you want to know | PromQL |
|---|---|
| Input token usage by model | `sum by(gen_ai_request_model) (ogx_gen_ai_client_token_usage_sum{gen_ai_token_type="input"})` |
| Output token usage by model | `sum by(gen_ai_request_model) (ogx_gen_ai_client_token_usage_sum{gen_ai_token_type="output"})` |
| P95 HTTP server latency | `histogram_quantile(0.95, rate(ogx_http_server_duration_milliseconds_bucket[5m]))` |
| P99 inference duration | `histogram_quantile(0.99, rate(ogx_inference_duration_seconds_bucket[5m]))` |
| P95 TTFT by model | `histogram_quantile(0.95, rate(ogx_inference_time_to_first_token_seconds_bucket[5m]))` |
| Median tokens/sec by provider | `histogram_quantile(0.5, rate(ogx_inference_tokens_per_second_bucket[5m]))` |
| Tool invocation errors | `rate(ogx_tool_runtime_invocations_total{status="error"}[5m])` |



#### Grafana: Pre-built Dashboard

A **OGX** dashboard is automatically provisioned with panels for prompt tokens, completion tokens, P95/P99 HTTP duration, and request volume. It's a starting point — extend it with the PromQL queries above for inference-specific views.



### Step 6: Set Up Alerts

With metrics in Prometheus, you can set up alerts for the things that actually page you at 3 AM:

- **High latency**: P99 inference duration > 10s sustained for 5 minutes
- **Error rate spike**: Error rate > 5% over a 5-minute window
- **Provider down**: Zero successful requests to a provider for 2 minutes
- **Capacity warning**: Concurrent requests consistently above threshold

### Cleanup

```bash
docker stop jaeger otel-collector prometheus grafana
docker rm jaeger otel-collector prometheus grafana
docker network rm llama-telemetry
```

## What's Next

The instrumentation is in place, and we're planning to expand it. If you have ideas for metrics that would help you operate OGX in production or if you've built interesting dashboards on top of what's there, we'd love to hear about it. Open an issue or check the [contributing guide](https://github.com/ogx-ai/ogx/blob/main/CONTRIBUTING.md).

---

### Blog 2026 04 06 Mlflow Observability (`docs/blog/2026-04-06-mlflow-observability.md`)

---
slug: mlflow-observability
title: "Tracing OGX Applications with MLflow: SDK vs OTel Collector"
authors: [gyliu513]
tags: [mlflow, observability, opentelemetry, metrics, tracing, monitoring]
date: 2026-04-06
---

As LLM-powered applications grow in complexity, observability becomes essential. You need to understand what your application is doing — what prompts are being sent, what responses come back, how long each call takes, and how many tokens are consumed. [MLflow](https://mlflow.org/) provides a powerful tracing framework that captures all of this, which can be integrated with [ogx](https://github.com/ogx-ai/ogx) for observability.

In this post, we'll walk through two approaches for exporting OGX traces into MLflow:

1. **MLflow SDK** — Direct instrumentation using MLflow's built-in tracing and autologging
2. **OTel Collector** — Decoupled telemetry pipeline using OpenTelemetry auto-instrumentation and an OTel Collector as the intermediary

By the end, you'll understand when to use each approach and how to set them up.



## MLflow Tracing: A Quick Overview

MLflow is an open-source platform for managing the ML lifecycle. Starting with version 2.14, MLflow introduced **GenAI tracing** — a first-class feature for capturing LLM interactions including:

- **Traces and Spans**: Hierarchical representation of operations (API calls, tool invocations, chain steps)
- **Token Usage & Latency**: Automatic capture of input/output tokens and response times
- **Input/Output Logging**: Full request and response payloads for debugging
- **Web UI**: A built-in dashboard for exploring, filtering, and analyzing traces

MLflow also supports ingesting traces via the **OpenTelemetry (OTLP) protocol** at its `/v1/traces` endpoint, which opens the door to vendor-neutral instrumentation, more on that in the OTel Collector section.

## OGX and Its OpenAI-Compatible API

OGX provides an OpenAI-compatible API, meaning any tooling that works with OpenAI's chat completions API or responses API also works with OGX. This is key for tracing, we can leverage existing OpenAI instrumentation libraries (both MLflow's `openai.autolog()` and OpenTelemetry's `opentelemetry-instrumentation-openai-v2`) to capture traces without writing custom code.

## Architecture Overview

Before diving into the details, here's a high-level view of both approaches:

```mermaid
graph TB
    subgraph "Approach 1: MLflow SDK"
        A1[OGX App] -->|MLflow SDK autolog| M1[MLflow Server]
        M1 --> U1[MLflow UI]
    end
```

```mermaid
graph TB
    subgraph "Approach 2: OTel Collector"
        A2[OGX App] -->|OTLP/HTTP :4318| C[OTel Collector]
        C -->|OTLP/HTTP /v1/traces| M2[MLflow Server]
        M2 --> U2[MLflow UI]
    end
```

## Prerequisites

For both approaches, you'll need:

- **Python 3.10+**
- **A running OGX server** (e.g., at `http://localhost:8321`)
- **MLflow >= 3.10** with GenAI extras:

```bash
pip install "mlflow[genai]>=3.10" "openai>=2.20.0"
```

### Start the MLflow Tracking Server

Launch a local MLflow server with SQLite as the backend store:

```bash
mlflow server \
  --backend-store-uri sqlite:///mlflow.db \
  --default-artifact-root ./mlruns \
  --host 0.0.0.0 --port 5000
```

The MLflow UI will be available at [http://localhost:5000](http://localhost:5000).

## Approach 1: Tracing via MLflow SDK

This approach uses MLflow's native tracing SDK to capture and export traces directly to the MLflow server. It's the simplest way to get started.

```mermaid
sequenceDiagram
    participant App as OGX App
    participant SDK as MLflow SDK
    participant Server as MLflow Server
    participant UI as MLflow UI

    App->>SDK: mlflow.openai.autolog()
    App->>SDK: client.responses.create()
    SDK->>SDK: Capture span (inputs, outputs, tokens)
    SDK->>Server: POST trace via MLflow Tracking API
    Server->>UI: Trace visible in dashboard
```

### Step 1: Instrument Your Code

Add MLflow tracing to your OGX client code. The example below uses the [Responses API](https://platform.openai.com/docs/api-reference/responses) (`client.responses.create`), which is the recommended way to interact with OGX:

```python
import mlflow
import mlflow.tracing as mlflow_tracing
from openai import OpenAI

# Configure MLflow
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("OGX Demo")

# Enable tracing and OpenAI autologging
mlflow_tracing.enable()
mlflow.openai.autolog()

# Create an OpenAI-compatible client pointing to OGX
client = OpenAI(
    base_url="http://localhost:8321/v1",
    api_key="fake",
)

response = client.responses.create(
    model="meta-llama/Llama-3.1-8B-Instruct",
    input="Give a one-sentence description of OGX.",
)
print(response.output_text)
```

MLflow's `openai.autolog()` automatically captures every `client.responses.create()` call as a trace, including inputs, outputs, token usage, and latency — with zero additional instrumentation code.

### Step 2: Run the Application

```bash
MLFLOW_TRACKING_URI=http://localhost:5000 \
python your_app.py
```

### Step 3: View Traces in MLflow

Open [http://localhost:5000](http://localhost:5000), navigate to your experiment ("OGX Demo"), and click the **Traces** tab. You'll see each request with:

- Full input/output payloads
- Token usage (input, output, total)
- Latency breakdown
- Span hierarchy



### Pros and Cons

| Aspect | Details |
|---|---|
| **Simplicity** | Minimal setup — just a few lines of Python |
| **Rich data** | MLflow autolog captures detailed OpenAI-specific metadata |
| **Coupling** | Application code depends on `mlflow` package |
| **Flexibility** | Traces go directly to MLflow — no intermediary routing or fan-out |

## Approach 2: Tracing via OTel Collector

This approach decouples instrumentation from the trace backend. The application uses **OpenTelemetry auto-instrumentation** to emit spans, which flow through an **OTel Collector** before being forwarded to MLflow's OTLP endpoint.

```mermaid
sequenceDiagram
    participant App as OGX App
    participant OTel as OTel Auto-Instrumentation
    participant Col as OTel Collector
    participant Server as MLflow Server
    participant UI as MLflow UI

    App->>OTel: opentelemetry-instrument wraps app
    App->>App: client.chat.completions.create()
    OTel->>OTel: Capture span (openai instrumentation)
    OTel->>Col: Export via OTLP/HTTP (:4318)
    Col->>Server: Forward to /v1/traces (OTLP/HTTP)
    Server->>UI: Trace visible in dashboard
```

### Step 1: Install OpenTelemetry Dependencies

```bash
pip install opentelemetry-api \
            opentelemetry-sdk \
            opentelemetry-exporter-otlp \
            opentelemetry-instrumentation-openai
```

### Step 2: Configure the OTel Collector

Create an `otel-collector-config.yaml`:

```yaml
receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

exporters:
  otlphttp/mlflow:
    endpoint: http://host.docker.internal:5000
    traces_endpoint: /v1/traces
    tls:
      insecure: true
    headers:
      x-mlflow-experiment-id: "1"

processors:
  batch:
    timeout: 5s

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlphttp/mlflow]
```

Key configuration points:

- **`receivers.otlp`**: Accepts OTLP data on port 4318 (HTTP)
- **`exporters.otlphttp/mlflow`**: Forwards traces to MLflow's `/v1/traces` OTLP endpoint
- **`x-mlflow-experiment-id`**: Determines which MLflow experiment receives the traces
- **`host.docker.internal`**: Allows the containerized collector to reach the host machine's MLflow server

### Step 3: Run the OTel Collector

```bash
docker run -d \
  --name otel-collector \
  -p 4318:4318 \
  -v $(pwd)/otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml \
  otel/opentelemetry-collector-contrib:0.143.1
```

### Step 4: Run the Application with OTel Instrumentation

The key difference here: we use `opentelemetry-instrument` to wrap the application, and we **disable** MLflow's built-in tracing to avoid double-writing:

```bash
MLFLOW_ENABLE_TRACING=0 \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf \
OTEL_SERVICE_NAME=ogx-app \
opentelemetry-instrument python your_app.py
```

Note that the application code itself does **not** need any MLflow imports for tracing. The OpenTelemetry auto-instrumentation handles span creation, and the collector handles routing.

### Step 5: Verify Traces

Check that traces are flowing into MLflow:

```bash
# Via CLI
MLFLOW_TRACKING_URI=http://localhost:5000 \
mlflow traces search --experiment-id 1

# Or check the database directly
sqlite3 mlflow.db "SELECT count(*) FROM trace_info;"
```

Then open the MLflow UI at [http://localhost:5000](http://localhost:5000) to explore the traces visually.



### Pros and Cons

| Aspect | Details |
|---|---|
| **Decoupling** | App has no MLflow SDK dependency — only standard OTel |
| **Fan-out** | Collector can export to multiple backends simultaneously (e.g., Jaeger + MLflow) |
| **Production-ready** | OTel Collector provides buffering, retry, and batching |
| **Complexity** | Requires running and configuring an additional service (the collector) |
| **Data richness** | OTel OpenAI instrumentation may capture different fields than MLflow autolog |

### Responses API Support

**Note:** OpenTelemetry auto-instrumentation for the Responses API is not yet available upstream. Progress is tracked in [ogx/ogx#5192](https://github.com/ogx-ai/ogx/issues/5192). In the meantime, Approach 1 (MLflow SDK) fully supports tracing Responses API calls via `mlflow.openai.autolog()`.

## Approach Comparison

```mermaid
graph LR
    subgraph "MLflow SDK Path"
        direction LR
        S1[Simple Setup] --> S2[Tight Integration]
        S2 --> S3[Best for Dev/Prototyping]
    end
```

```mermaid
graph LR
    subgraph "OTel Collector Path"
        direction LR
        O1[Vendor Neutral] --> O2[Decoupled Architecture]
        O2 --> O3[Best for Production]
    end
```

| Criteria | MLflow SDK | OTel Collector |
|---|---|---|
| **Setup complexity** | Low — a few lines of code | Medium — collector config + container |
| **Code coupling** | Coupled to `mlflow` package | No MLflow dependency in app code |
| **Multi-backend support** | MLflow only | Fan-out to any OTLP-compatible backend |
| **Buffering & retry** | Basic (in-process) | Production-grade (collector handles it) |
| **Best for** | Development, prototyping, quick experiments | Production deployments, multi-tool observability stacks |
| **Instrumentation** | `mlflow.openai.autolog()` | `opentelemetry-instrument` + OTel OpenAI plugin |

## Bonus: Tracing the OGX Server Itself

Both approaches above trace the **client side** — the application making calls to OGX. But you can also trace the **OGX server** using the OTel approach:

```bash
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://localhost:5000/v1/traces \
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf \
OTEL_EXPORTER_OTLP_TRACES_HEADERS="x-mlflow-experiment-id=1" \
OTEL_SERVICE_NAME=ogx-server \
opentelemetry-instrument ogx run starter
```

This gives you end-to-end visibility: client-side spans showing the request lifecycle, and server-side spans showing internal OGX processing.

> **Important:** MLflow SDK tracing only instruments the **client side**. The OGX server itself is not instrumented by MLflow, so server-side spans (inference routing, tool execution, etc.) are only visible through OpenTelemetry auto-instrumentation (Approach 2).
>
## Common Gotchas

1. **MLflow OTLP endpoint path**: Use `/v1/traces`, not `/api/2.0/otlp/v1/traces` (the latter returns 404 in MLflow 3.10+).

2. **Double-writing**: If you enable both MLflow autolog and OTel instrumentation, traces may be written twice. Set `MLFLOW_ENABLE_TRACING=0` when using the OTel path.

3. **Missing spans with OTel**: The `opentelemetry-instrument` wrapper is required — simply setting `OTEL_*` environment variables without it won't produce any spans because no instrumentation is active.

4. **Docker networking**: When running the OTel Collector in Docker, use `host.docker.internal` to reach services on the host machine.

5. **Time range in UI**: If the MLflow UI looks empty, check the time range filter — it may default to a narrow window that excludes your traces.

## Conclusion

Both approaches get your OGX traces into MLflow, but they serve different needs:

- **Start with the MLflow SDK** when you want quick, low-friction observability during development. A few lines of code and you're tracing.
- **Move to the OTel Collector** when you need production-grade telemetry infrastructure — decoupled from your application, with the ability to fan out to multiple observability backends.

The good news: since OGX exposes an OpenAI-compatible API, both paths leverage existing, well-maintained instrumentation libraries. You're not writing custom tracing code — you're plugging into an ecosystem.

## Quick Start With Containers

A pending PR, [feat: add MLflow support for OGX](https://github.com/ogx-ai/ogx/pull/5409), will let you run OGX alongside MLflow, Grafana, and Prometheus in containers with a single command. Once that PR lands, use the [telemetry scripts](https://github.com/ogx-ai/ogx/tree/main/scripts/telemetry) in the OGX repository for the full walkthrough.

## References

- [MLflow Tracing Documentation](https://mlflow.org/docs/latest/llms/tracing/index.html)
- [OpenTelemetry Collector Documentation](https://opentelemetry.io/docs/collector/)
- [OpenTelemetry OpenAI Instrumentation](https://github.com/open-telemetry/opentelemetry-python-contrib)

---

### Blog 2026 04 28 From Llama Stack To Ogx (`docs/blog/2026-04-28-from-llama-stack-to-ogx.md`)

---
slug: from-llama-stack-to-ogx
title: "From Llama Stack to OGX: A New Name, A Sharper Mission"
authors: [ogx-team]
tags: [announcement, ogx, rename, agentic, multi-sdk]
date: 2026-04-28
---

Llama Stack is now OGX. The name changed, but more importantly, so did the mission.

When this project started, it was an API standardization effort — a set of specs for building AI applications, anchored to the Llama model family. That framing attracted contributors and integrations, but it also created confusion about what the project actually *is*. People thought it was a spec. Or a Llama-only thing. Or another framework.

It's none of those. OGX is a server. Specifically, it's a **server-side agentic loop** that speaks the native API of every major frontier lab — OpenAI, Anthropic, and Google — so your application code doesn't have to care which one you're using.

This post explains why we renamed, what changed in the project's direction, and what that means for you.



## Why the rename

Three problems with "Llama Stack":

**The Llama association was limiting.** The project supports 23 inference providers. You can run GPT-4, Claude, Gemini, Mistral, or any model you want behind OGX. But "Llama Stack" made people think it only worked with Llama models. That was never true, and the gap between name and reality kept growing.

**"Stack" suggested a framework.** Developers hear "stack" and think of a collection of libraries you import into your code — something like LangChain or LlamaIndex. OGX is fundamentally different: it's an HTTP server with a pluggable provider architecture. Your application talks to it over the network, in any language, with any client. That architectural distinction matters and the old name obscured it.

**The project outgrew its origin.** What started as an API around Meta's models became a multi-provider, multi-SDK server implementing the OpenAI Responses API, the Anthropic Messages API, and the Google Interactions API. The name needed to reflect where the project is, not where it started.

OGX is short, neutral, and doesn't tie the project to a single model family or company. It's a name that can grow with the project.

## What actually changed

The rename touched 1,696 files across the codebase. Source directories moved from `llama_stack` to `ogx`. The CLI changed from `llama` to `ogx`. Environment variables changed from `LLAMA_STACK_*` to `OGX_*`. The GitHub org moved to `ogx-ai`.

But the rename was also a moment to clarify what OGX is *for*. The project's identity shifted from "an AI API standard" to something more specific and more useful:

**OGX is a server-side agentic loop that speaks any frontier lab API.**

Let's break that down.

## Server-side agentic loop

Before the Responses API existed, building an agent meant writing a client-side orchestration loop. Your code called the model, checked if it wanted to use a tool, executed the tool, sent results back, and repeated. Every application reimplemented this loop, and every implementation had its own bugs.

The Responses API moved that loop to the server. You send a question and a set of tools. The server handles the planning, tool execution, and synthesis internally. Your client gets a final answer.

OGX implements this loop with full support for:

- **Built-in RAG** via `file_search` — the server searches your vector store, retrieves relevant passages, and grounds the response, all within the agentic loop
- **MCP integration** — connect any MCP server and the agent discovers and uses its tools automatically
- **Multi-step reasoning** — the server handles chains of tool calls, not just single-shot inference
- **Conversation state** — persistent context across interactions without client-side state management

This is the core value proposition. OGX doesn't just route inference requests to different backends. It runs the agentic loop — the reasoning, tool calling, and synthesis — server-side, so your application stays simple.

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="fake")

# Single API call. Server handles multi-step tool orchestration.
response = client.responses.create(
    model="llama-3.3-70b",
    input="What documents mention our pricing strategy?",
    tools=[
        {"type": "file_search", "vector_store_ids": ["vs_123"]},
        {
            "type": "mcp",
            "server_label": "internal-api",
            "server_url": "http://api-server:8000/sse",
        },
    ],
)
```

## Speaks any frontier lab API

OGX isn't an inference server — it routes to inference backends like vLLM, Ollama, or Bedrock. What makes it different is that it doesn't just expose the OpenAI API in front of those backends. It implements three API surfaces natively, so teams using different SDKs can all point at the same server.

**OpenAI API** — `/v1/chat/completions`, `/v1/responses`, `/v1/embeddings`, and the full suite of supporting endpoints (files, vector stores, batches, models).

**Anthropic Messages API** — `/v1/messages`. Use the Anthropic Python or TypeScript SDK directly. OGX handles the format translation server-side.

**Google Interactions API** — `/v1alpha/interactions`. Use the Google GenAI SDK directly.

All three hit the same underlying inference providers. The same OGX server can serve clients using different SDKs simultaneously:

```python
# All three work against the same OGX server, same model
from openai import OpenAI

openai_client = OpenAI(base_url="http://localhost:8321/v1", api_key="fake")

from anthropic import Anthropic

anthropic_client = Anthropic(base_url="http://localhost:8321/v1", api_key="fake")

from google import genai

google_client = genai.Client(api_version="v1alpha", api_key="fake")
```

This decouples two decisions that used to be coupled: **which SDK your team prefers** and **which model or provider you deploy**. Use the Anthropic SDK with Ollama. Use the Google SDK with vLLM. Use the OpenAI SDK with Bedrock. The server translates; your code doesn't change.

For providers that natively support a given API format, OGX passes requests through directly — no translation overhead. For everything else, it converts between formats transparently.

## What OGX is not

It's worth being explicit about what the project is *not*, because the old framing created some misconceptions:

**Not primarily an API standard.** OGX implements existing standards where they exist (OpenAI API, Open Responses, Anthropic Messages API, Google Interactions API). Where no frontier lab provides an equivalent — like file processing for document ingestion — OGX defines its own APIs to fill the gap. If a frontier lab later ships a standard for one of those gaps, we'll adopt it rather than maintain our own. The project's value is in the server, not in spec authorship.

**Server-first, not a framework.** The primary deployment model is an HTTP server that your application talks to over the network, in any language. A library mode exists for embedding OGX in-process, but the architecture is designed around the server: pluggable providers, API translation, and agentic orchestration all happen on the server side.

**Not Llama-only.** It never was, but now the name makes that clear. OGX works with any model accessible through its 23 inference providers.

**Not just inference routing.** Proxy servers that forward requests to different backends are useful but limited. OGX runs the full agentic loop server-side: inference, tool calling, RAG, MCP integration, conversation management, safety, and file processing. That's the difference between a proxy and an application server.

## Migration from Llama Stack

If you're upgrading from `llama-stack`:

- **Package name**: `llama-stack` → `ogx`
- **CLI**: `llama` → `ogx`
- **Environment variables**: `LLAMA_STACK_*` → `OGX_*`
- **HTTP headers**: `x-llamastack-*` → `x-ogx-*`
- **Client SDK**: The Python client package (`llama_stack_client`) has not changed yet — that migration will happen separately

The server API itself is unchanged. If your application talks to OGX over HTTP (as it should), your client code doesn't need to change at all. Just point it at the new server.

## What's next

The rename clears the way for the project to grow in the direction it's already heading:

- **Deeper multi-SDK support** — expanding Anthropic and Google API coverage beyond basic inference to include tool calling and agentic features
- **Extended agentic capabilities** — richer server-side orchestration patterns, better conversation management, and more built-in tools
- **Performance** — faster inference routing, more efficient agentic loops, and better resource utilization across providers

The name is new. The mission is sharper. The server is the same one you've been using — just with a name that finally matches what it does.

Get started at [ogx-ai.github.io/docs](https://ogx-ai.github.io/docs), or join the conversation on [Discord](https://discord.gg/bUYRqEvK6).

— Charlie, Francisco, Matt, Raghu, Seb

---

### Blog 2026 05 05 Opencode Blog (`docs/blog/2026-05-05-opencode-blog.md`)

---
slug: opencode-blog
title: "OGX ❤️ OpenCode"
authors: [nathan-weinberg]
tags: []
date: 2026-05-05
---

[OpenCode](https://opencode.ai/) is an open source AI coding agent that helps you write code in your terminal, IDE, or desktop. It is a popular open source alternative
for tools like Claude Code and Codex.

OpenCode has a concept of [providers](https://opencode.ai/docs/providers/) that is similar to OGX's inference providers - they are a local or cloud-based model inference endpoint that expose an LLM for OpenCode to utilize. This is similar but does differ from [OGX providers](https://ogx-ai.github.io/docs/providers) which are inclusive of inference but also include providers for vector stores, safety backends, tool runtimes, etc.

OGX as a OpenCode provider has some strong advantages over providers that offer only inference:

- Unified API for tools + RAG + storage
- Multiple providers behind one endpoint
- Built-in orchestration layer

In this blog I am going to share how to start running OpenCode with OGX as a provider, using OpenCode's [custom provider](https://opencode.ai/docs/providers/#custom-provider) feature.

The blog assumes you already have an OGX server up and running - see our [Getting Started guide](https://ogx-ai.github.io/docs/getting_started/quickstart) to learn more.

## Download OpenCode

Downloading OpenCode is simple and can be done in various ways. You can see a full list of methods [here](https://opencode.ai/download) but generally the below `curl` command is suifficient in most cases.

```bash
curl -fsSL https://opencode.ai/install | bash
```

## Configure OGX as a provider for OpenCode

As mentioned before, this blog assumes an OGX server is already running at `localhost:8321` - in this case, we are also making the following assumptions:

- The `remote::vllm` provider is enabled, serving the `Qwen/Qwen3-8B` model
- The `remote::watsonx` provider is enabled, with the `gpt-oss-120b` model available
- No authentication has been added

You can verify what models your OGX server has available with `curl http://localhost:8321/v1/models`

We can now configure OpenCode to use our OGX server via a custom provider.

Create a file `~/.config/opencode/opencode.json` with the following content:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ogx": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "OGX",
      "options": {
        "baseURL": "http://localhost:8321/v1"
      },
      "models": {
        "vllm-inference/Qwen/Qwen3-8B": {
          "name": "Qwen3-8B"
        },
        "watsonx/openai/gpt-oss-120b": {
          "name": "gpt-oss-120b"
        }
      }
    }
  }
}
```

Once the file is created, start OpenCode - it should look something like this:



Run `/connect` in the TUI. If you search `OGX` the provider should come up with our two models listed.



Select `gpt-oss-120b` and hit enter. If you are prompted for an API key, you can just put `None` since we haven't configured one in this case.

## Use OpenCode with OGX

Now that you have your OGX-provided model selected, it's time to start using OpenCode with OGX! Go ahead and start prompting in the TUI - it should look something like this:



And that is it! You can tweak your OGX server and OpenCode custom provider configuration to add additional providers, models, and whatever else you might need for yourself or your enterprise.

Thanks for reading, and happy coding!

---

### Blog 2026 05 11 Consistent Agentic Api Layer (`docs/blog/2026-05-11-consistent-agentic-api-layer.md`)

---
slug: consistent-agentic-api-layer
title: "Every Protocol. Every Framework. Zero Code Changes."
authors: [leseb]
tags: [agentic, multi-sdk, sovereignty, architecture]
date: 2026-05-11
---

Agents shouldn't change a line of code to run on your infrastructure.

That sentence sounds simple, but it represents a fundamental shift in how enterprises can adopt AI agents. Today, every agentic framework speaks a different protocol. Teams using Claude Agents talk Anthropic Messages. Teams using ADK talk Google Interactions. Most agents still call OpenAI Chat Completions or the newer Responses API. Each choice creates a hard dependency on a vendor's infrastructure, SDK, and API contract.

OGX exists to break that coupling. It's a server that speaks every major agentic protocol natively, translating them to any model running on any infrastructure. No vendor lock-in. No SDK rewrites.



## The problem: protocol fragmentation

Enterprise AI adoption doesn't happen in a vacuum. Different teams pick different frameworks based on their use case, their experience, and their model preference. One team builds with Claude Code. Another ships with OpenAI's Responses API. A third experiments with Google's ADK. Each choice is reasonable in isolation.

But at the platform level, this creates a mess. Every protocol means a different API contract. Every API contract means a different deployment path, a different set of credentials, a different operational surface. The platform team ends up managing $N$ distinct integration points instead of one.

Worse, the choice of SDK becomes coupled to the choice of model and infrastructure. Want to use the Anthropic SDK with an open-weight model running on-prem? Want to use the OpenAI SDK against a model served by vLLM? Want to switch providers without rewriting your application? In the current landscape, each of those requires work.

This is the fragmentation tax. It slows adoption, increases operational burden, and creates vendor lock-in at the API layer — even when the models themselves are open.

## OGX as the translation layer

OGX solves this by implementing three API surfaces natively on a single server:

**OpenAI API** — Chat Completions, Responses, Embeddings, and the full suite of supporting endpoints. This is the baseline most agents and frameworks already use.

**Anthropic Messages API** — the multi-turn conversation protocol that Claude Agents and Claude Code speak natively.

**Google Interactions API** — the emerging agentic protocol from the ADK and Gemini ecosystem.

All three share the same underlying inference providers. A single OGX deployment can serve clients using different SDKs simultaneously, against the same models:

```python
from openai import OpenAI

openai_client = OpenAI(base_url="http://ogx-server:8321/v1", api_key="key")

from anthropic import Anthropic

anthropic_client = Anthropic(base_url="http://ogx-server:8321/v1", api_key="key")

from google import genai
from google.genai import types

google_client = genai.Client(
    api_key="key",
    http_options=types.HttpOptions(
        base_url="http://ogx-server:8321",
        api_version="v1alpha",
    ),
)
```

Three SDKs. One server. Same model. No translation code in your application.

## More than a proxy

OGX isn't just routing requests to different backends. That would be a reverse proxy, and those already exist. What makes OGX different is that it runs a **server-side agentic loop** — inference, tool calling, RAG, MCP integration, conversation state management — on supported API surfaces, with feature parity continuing to expand across protocols.

When a client sends a request through the Responses API with `file_search` and MCP tools attached, the server handles the entire orchestration: searching vector stores, calling MCP servers, chaining tool results back into the model, and synthesizing a final answer. Your client gets a response. It doesn't manage a loop.

This is the difference between a proxy and an application server. A proxy translates formats. OGX translates formats *and* runs the agentic logic that makes those formats useful.

```python
from openai import OpenAI

client = OpenAI(base_url="http://ogx-server:8321/v1", api_key="key")

response = client.responses.create(
    model="llama-3.3-70b",
    input="Summarize the Q1 compliance updates and check if any affect our deployment timeline.",
    tools=[
        {"type": "file_search", "vector_store_ids": ["vs_compliance"]},
        {
            "type": "mcp",
            "server_label": "project-tracker",
            "server_url": "http://internal-api:8000/sse",
        },
    ],
)
```

One API call. Multiple tools. Multi-step reasoning. All server-side.

## What sovereignty actually means

The conversation around AI sovereignty usually focuses on model weights. Can we run the model on our own hardware? Can we fine-tune it? Do we control the training data? These are important questions, and open-weight models answer them.

But sovereignty at the model layer isn't enough. If your application is written against a proprietary API, you're still locked in — just at a different layer. Switching from one provider to another means rewriting your agent code, re-testing your tool integrations, and re-validating your orchestration logic.

OGX extends sovereignty to the API contract. Your application talks to OGX using whatever SDK your team prefers. OGX talks to whatever inference provider you've deployed. The two decisions are independent:

- Use the Anthropic SDK with Ollama running on-prem
- Use the OpenAI SDK with vLLM on your Kubernetes cluster
- Use the Google SDK with Bedrock in AWS
- Switch any of these without touching application code

And once the platform owns the API contract, it can enforce policy at the protocol layer. Attribute-based access control determines which models, tools, or APIs a given team or user can reach — regardless of which SDK they're calling through. A data science team gets access to large reasoning models and file search. An internal chatbot gets a smaller model and no tool access. The controls live in the platform, not scattered across framework configs.

This is something you can't do when each framework talks directly to its own provider. Centralized policy enforcement is a natural consequence of centralized API translation.

The customer owns the API contract, not just the model weights. That's what sovereignty means at the platform level.

## Framework-agnostic by design

The protocol diversity in the agentic ecosystem isn't going away. Claude Code, Codex, ADK, Strands, LangGraph, OpenClaw — each framework has its own strengths and its own protocol preferences. Telling teams to standardize on one framework is unrealistic and counterproductive.

OGX takes a different approach: let teams choose whatever framework fits their use case, and make the platform handle the protocol differences. A team building with Claude Code doesn't need to know or care that the platform is running open-weight models on OpenShift. A team using ADK doesn't need to rewrite their agents if the organization decides to switch inference providers.

This is what "zero code changes" means in practice. Not zero effort to set up the platform — that takes real engineering. But zero changes to the agent code that teams have already built and tested.

## Where this is heading

OGX already supports the core API surfaces. The work ahead is deepening that support:

- **Richer tool orchestration** across all three protocols — parallel tool calls, code interpretation, and response branching
- **Full agentic feature parity** — making sure every protocol surface gets the same server-side capabilities, not just basic inference
- **Production hardening** — storage persistence, multi-provider auth, telemetry, and upgrade paths that enterprise deployments require

The goal is straightforward: any agent, any framework, any model, any infrastructure. One server.

If your team is building agents and doesn't want to bet on a single vendor's API contract, [get started with OGX](https://ogx-ai.github.io/docs) or join the conversation on [Discord](https://discord.gg/bUYRqEvK6).

---

### Blog 2026 05 12 Ogx V1 (`docs/blog/2026-05-12-ogx-v1.md`)

---
slug: ogx-v1
title: "OGX 1.0: The Open Agentic API Server is Production-Ready"
authors: [ogx-team]
tags: [announcement, ogx, v1, release, agentic, multi-sdk, production]
date: 2026-05-12
---

Two weeks ago, we told you [the name changed](./2026-04-28-from-llama-stack-to-ogx.md). Today, we're telling you it's done.

OGX 1.0 is a server that replaces the OpenAI API with something you own. Point your existing OpenAI, Anthropic, or Google SDK at it. Run any model on any infrastructure. Get server-side agentic orchestration, built-in RAG, MCP tool integration, multi-tenancy, and production observability out of the box. No vendor lock-in. No code changes.

This is not a beta. This is not "production-ready with caveats." This is v1.



## The shortest version

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="any")

response = client.responses.create(
    model="gpt-4o",
    input="Find all documents about Q3 revenue and summarize the key trends.",
    tools=[
        {"type": "file_search", "vector_store_ids": ["vs_finance"]},
        {
            "type": "mcp",
            "server_label": "analytics",
            "server_url": "http://analytics:8000/sse",
        },
    ],
)
```

That's a real agentic workflow. The server searches your vector store, calls your MCP tools, reasons over the results, and returns an answer. One API call. Your code stays simple. Swap `gpt-4o` for `claude-sonnet-4-6` or `llama-3.3-70b` and nothing else changes.

## What got us here

OGX started as an API standardization effort around Llama models called Llama Stack. It grew into something different: a server-side agentic loop that speaks the native API of every major frontier lab. Along the way, we made hard choices that v1 reflects.

**We killed our own APIs.** The fine-tuning API, the agents API, the knowledge_search tool, the `meta-reference` naming, the TGI and HuggingFace providers. Gone. Every one of them was replaced with something that aligns to existing industry standards or simplifies the system. The agents API became the Responses API. knowledge_search became file_search. We adopted OpenAI's terminology not because OpenAI is the standard, but because most developers already know it. Meeting developers where they are beats inventing new names.

**We earned our compliance scores.** OGX passes the [Open Responses](https://www.openresponses.org/) conformance test suite at 100%. The OpenAI API conformance score sits above 91%. These are not aspirational targets. They are tested on every commit.

**We shipped the hard infrastructure.** Multi-tenancy with attribute-based access control. Structured observability with per-request metrics, token throughput tracking, and model-level latency. A gateway-first architecture that delegates rate limiting and CORS to your infrastructure layer where it belongs. These are the features that separate a project from a product.

239 contributors across the project's lifetime. 23 inference providers. 21 vector store backends. And a rename that touched 1,696 files because we decided the name should match the mission.

## Three SDKs, one server

Most "OpenAI-compatible" servers give you `/v1/chat/completions` and call it a day. OGX implements three API surfaces natively:

```python
# OpenAI SDK
from openai import OpenAI

openai_client = OpenAI(base_url="http://localhost:8321/v1", api_key="any")

# Anthropic SDK
from anthropic import Anthropic

anthropic_client = Anthropic(base_url="http://localhost:8321/v1", api_key="any")

# Google GenAI SDK
from google import genai
from google.genai import types

google_client = genai.Client(
    api_key="any",
    http_options=types.HttpOptions(
        base_url="http://localhost:8321",
        api_version="v1alpha",
    ),
)
```

All three hit the same inference providers. The same OGX server can serve a team using the OpenAI SDK, another team using Anthropic's, and a third using Google's. Simultaneously. Against the same model running on the same GPU.

This decouples two decisions that used to be welded together: which SDK your team prefers and which model you deploy. Use the Anthropic SDK with Ollama. Use the Google SDK with vLLM. Use the OpenAI SDK with Bedrock. The server translates. Your code doesn't change.

## Coding assistants work too

OGX is not just for app SDKs. You can also point coding assistants at the same OGX server:

```bash
# Claude Code -> Anthropic Messages API via OGX
export ANTHROPIC_BASE_URL="http://localhost:8321"
export ANTHROPIC_API_KEY="fake"
```

```toml
# Codex CLI -> OpenAI Responses API via OGX
model = "openai/gpt-4o"
model_provider = "ogx"

[model_providers.ogx]
name = "OpenAI"
base_url = "http://localhost:8321/v1"
wire_api = "responses"
supports_websockets = false
```

That means Claude Code, Codex CLI, your OpenAI SDK apps, and your Anthropic SDK apps can all share one OGX deployment and one provider layer.

See: [Claude Code integration](/docs/building_applications/claude_code_integration) and [Codex CLI integration](/docs/building_applications/codex_cli_integration).

## The agentic loop, server-side

Before the Responses API, building an agent meant writing a client-side orchestration loop. Call the model. Check if it wants a tool. Execute the tool. Send results back. Repeat. Every application reimplemented this. Every implementation had its own bugs.

OGX moves that loop to the server. You send a question and a set of tools. The server handles planning, tool execution, and synthesis internally. Your client gets a final answer.

What the server handles for you:

- **Built-in RAG** via `file_search`. Upload documents, create a vector store, and the server searches, retrieves, and grounds responses automatically. No external RAG pipeline needed.
- **MCP integration.** Connect any MCP server and the agent discovers and uses its tools. Server-side tool orchestration means your client code doesn't need to know about tool schemas.
- **Multi-step reasoning.** The server chains tool calls, not just single-shot inference. Complex workflows that would require dozens of lines of client code happen in one API call.
- **Conversation state.** Persistent context across interactions without client-side state management. The server handles it.
- **Reasoning output.** Models that expose thinking traces return them as part of the response. You see the reasoning, not just the answer.

## Run anywhere, same API

OGX has a pluggable provider architecture. Develop locally with Ollama, deploy to production with vLLM, connect to a managed service when you need to, and the API never changes.

**Commercial APIs:** OpenAI, Anthropic, Google (Gemini + Vertex AI), Azure OpenAI

**Self-hosted inference:** Ollama, vLLM, llama.cpp

**Cloud platforms:** AWS Bedrock, Databricks, NVIDIA NIM, IBM WatsonX, Oracle OCI

**Specialized:** Fireworks, Together, Groq, Cerebras, SambaNova, RunPod

**Vector stores:** FAISS, SQLite-vec, Qdrant, Milvus, Chroma, PGVector, Elasticsearch, Infinispan, and more

**File processing:** MarkItDown, Docling, pypdf. Upload a PDF, Word doc, or text file and OGX converts it to embeddings for your vector store.

**Guardrails:** Configure `moderation_endpoint` on the builtin responses provider, then pass `extra_body={"guardrails": True}` in Responses requests. OGX calls your moderation service inline during generation and blocks unsafe content when violations are flagged.

Configuration is YAML with environment variable substitution. Conditional provider activation means you can declare twenty providers in your config and only the ones with credentials present will start. Switch from development to production by changing environment variables, not code.

## Production infrastructure, not a prototype

v1 ships features that matter when you're running OGX for real:

**Multi-tenancy.** Attribute-based access control on files, vector stores, conversations, and responses. Tenant isolation is built into the storage layer. Run one OGX server for multiple teams or customers.

**Observability.** Request counts, latency histograms, error rates, token throughput, model-level performance metrics. All exposed via OpenTelemetry. Plug into Prometheus, Grafana, Jaeger, or whatever your ops team already uses.

**Gateway-first architecture.** OGX delegates rate limiting, CORS, and TLS termination to your infrastructure gateway (Envoy, Kong, Istio, whatever you run). The server focuses on what it's good at: inference routing, agentic orchestration, and API translation.

**Structured logging.** Every log line is structured key-value via structlog. Parse it, index it, alert on it. No more regex over log files.

**Background tasks.** Queue long-running responses and cancel them if you need to. Production workloads need job control, not just fire-and-forget.

## Get started in 60 seconds

```bash
uvx --from 'ogx[starter]' ogx run starter
```

Then point any OpenAI client at `http://localhost:8321/v1` and go.

For production deployments, see the [distribution documentation](https://ogx-ai.github.io/docs/distributions). Distributions are pre-built configurations for specific environments: NVIDIA NIM, IBM WatsonX, Oracle OCI, or build your own.

## The road from here

v1 is a foundation, not a finish line. Here's where we're headed:

- **Deeper multi-SDK coverage.** Expanding Anthropic and Google API support beyond basic inference to full tool calling and agentic features.
- **Library mode.** Embed OGX in-process for latency-sensitive applications that don't need the HTTP layer.
- **More agentic patterns.** Richer orchestration primitives, better conversation management, more built-in tools.
- **Performance.** Faster inference routing, more efficient agentic loops, better resource utilization across providers.

## This is the beginning

OGX started as a set of API specs around one model family. It became a server that speaks every frontier lab's API, runs any model on any infrastructure, and handles the hard parts of agentic orchestration so your application code stays clean.

v1 means we're confident enough to put a number on it. The APIs are stable. The provider ecosystem is mature. The production infrastructure is real. 239 contributors believed in this enough to ship code.

If you've been waiting for the right time to try OGX, this is it.

[Get started](https://ogx-ai.github.io/docs/getting_started/quickstart) | [Documentation](https://ogx-ai.github.io/docs) | [GitHub](https://github.com/ogx-ai/ogx) | [Discord](https://discord.gg/bUYRqEvK6)

--- The OGX Team

---

### Blog 2026 05 19 Codex Cli Integration (`docs/blog/2026-05-19-codex-cli-integration.md`)

---
slug: codex-cli-integration
title: "Use Codex CLI with Any Model Through OGX"
authors: [leseb, franciscojavierarceo]
tags: [codex, openai, cli, integration, tutorial]
date: 2026-05-19
---

OpenAI's [Codex CLI](https://github.com/openai/codex) is a terminal-native coding agent. It reads your codebase, proposes changes, runs commands, and iterates, all from your shell. The problem: it only talks to OpenAI's API.

OGX fixes that. By placing OGX between Codex and your inference provider, you get Codex's coding workflows with any model OGX supports: Llama via Ollama, Claude via Bedrock, Mistral via vLLM, or OpenAI itself with conversation compaction on top.

This post walks through setup, configuration, and what to expect from this alpha integration.



## Why run Codex through OGX

Codex CLI is opinionated about its API surface. It speaks the OpenAI Responses API and expects a specific wire format. That's fine if you're paying OpenAI directly, but limiting if you want to:

- **Use open models** running on your own hardware via Ollama or vLLM
- **Route through a corporate proxy** that standardizes API access
- **Get conversation compaction** so long coding sessions don't blow past context limits
- **Switch models without reconfiguring Codex** by changing the OGX provider instead

OGX acts as a proxy that Codex already knows how to talk to. No patches to Codex, no forks. Just a config change.

## How the proxy chain works

The architecture is straightforward:



Codex sends Responses API requests to OGX. OGX routes them to whatever inference provider you've configured, translating formats where needed. Codex doesn't know or care what's behind OGX.

This means tool execution (shell commands, file reads/writes, code generation) still happens locally in Codex. OGX only handles the inference routing.

## Setup

Three steps. Assumes you have OGX and Codex CLI already installed.

### 1. Start OGX

```bash
export OPENAI_API_KEY="your-key-here"
ogx run starter
```

For Ollama instead of OpenAI:

```bash
OLLAMA_URL=http://localhost:11434/v1 ogx run starter
```

### 2. Configure Codex CLI

Add the following to `~/.codex/config.toml`:

```toml
model = "openai/gpt-4o"
model_provider = "ogx"

[model_providers.ogx]
name = "OpenAI"
base_url = "http://localhost:8321/v1"
wire_api = "responses"
supports_websockets = false
```

If you're using Ollama, change the model line:

```toml
model = "ollama/llama3.2:3b"
```

### 3. Test it

```bash
codex "Write a hello world function in Python"
```

If you see Codex generate code and propose changes, the proxy is working.

## Model compatibility

Choose models that are exposed by your OGX server and compatible with the Responses API:

- `openai/gpt-4o`
- `openai/gpt-4o-mini`
- `openai/gpt-5.4`
- `anthropic/claude-3-5-sonnet-20241022`
- `ollama/llama3.2:3b`

The model ID format depends on which inference provider is backing your OGX server. The prefix (e.g., `openai/`, `ollama/`) tells OGX where to route the request.

Since this setup uses `wire_api = "responses"`, ensure the selected model works with OGX's Responses path.

## What works, what doesn't

This integration is alpha. Here's the honest status.

**Works well:**

- Basic code generation and editing workflows
- Shell command execution and file operations
- Multi-turn conversations within a session
- Conversation compaction for long sessions
- Streaming responses

**Not yet supported:**

- **Memory persistence**: conversation history doesn't survive between Codex sessions. Each `codex` invocation starts fresh.
- **Error surfacing**: some provider-specific errors get swallowed by the proxy layer. If Codex hangs or returns empty, check OGX server logs.
- **Latency**: the extra network hop adds overhead. For local models (Ollama), this is negligible. For remote providers, it's a few hundred milliseconds on top of inference time.

## Troubleshooting

**"Model not found" errors:** check that the model ID includes the provider prefix. `gpt-4o` won't work, `openai/gpt-4o` will.

**Request compression errors:** Codex uses zstd compression by default. Make sure your OGX build supports request decompression. Recent versions do.

**Tool execution failures:** these happen in Codex, not OGX. Check that Codex has proper permissions for the operations it's trying to perform. OGX only handles inference.

**Empty or truncated responses:** check OGX server logs (`ogx` outputs to stderr by default). Provider-specific rate limits or token limits are the usual cause.

## What's next

We're working on closing the gaps in this integration:

- **Memory API integration** for persistent conversation storage across Codex sessions
- **Better error propagation** so provider failures surface clearly in the Codex UI
- **Performance optimizations** to reduce proxy overhead

For more details on OGX's provider architecture, see the [Providers Overview](https://ogx-ai.github.io/docs/providers). For Codex CLI documentation, visit the [Codex GitHub repository](https://github.com/openai/codex).

---

### Blog 2026 05 26 Rag Benchmarks (`docs/blog/2026-05-26-rag-benchmarks.md`)

---
slug: rag-benchmarks
title: "OGX RAG Benchmarks: Open-Source Retrieval That Outperforms OpenAI"
authors: [franciscojavierarceo]
tags: [benchmarks, rag, vector-stores, retrieval, openai-compatibility]
date: 2026-05-26
---

We benchmarked OGX's RAG pipeline against OpenAI's file search across four BEIR retrieval datasets, MultiHOP RAG, and Doc2Dial. The results: **OGX hybrid search beats OpenAI on 3 of 4 BEIR datasets**, with up to 29.6% higher nDCG@10 on argument retrieval. With **contextual chunking** (gpt-4.1-mini), OGX now wins on all 4 datasets — closing the fiqa gap with a +65% improvement. Pair it with Gemma 31B and you get end-to-end RAG that exceeds GPT-4.1 by 81% on multi-hop reasoning, all running on your own infrastructure.

This isn't a synthetic demo. These are standard academic benchmarks, measured end-to-end through the same OpenAI-compatible APIs you'd use in production.



## Why We Built This Benchmark Suite

RAG quality is hard to evaluate. Most teams ship a retrieval pipeline, eyeball a few queries, and hope for the best. We wanted something more rigorous: a reproducible benchmark suite that tests OGX's full API stack (Files, Vector Stores, Search, and Responses) against OpenAI under identical conditions.

The [benchmark suite](https://ogx-ai.github.io/docs/building_applications/rag_benchmarks) evaluates two dimensions:

1. **Retrieval quality** (BEIR) -- can the system find the right documents?
2. **End-to-end RAG** (MultiHOP, Doc2Dial) -- can it retrieve _and_ generate correct answers?

Every test runs through the same OpenAI-compatible API surface, so the comparison is apples-to-apples.

## The Setup

**OGX configuration:**

| Component | Choice |
|-----------|--------|
| Embedding model | `nomic-ai/nomic-embed-text-v1.5` (sentence-transformers) |
| Reranker | `Qwen/Qwen3-Reranker-0.6B` (transformers) |
| Vector database | Milvus (standalone) |
| Chunk size | 512 tokens |
| Chunk overlap | 128 tokens |
| Hybrid search | RRF fusion (impact factor 60.0) + reranker |

**Search modes compared:**

- **OpenAI** -- OpenAI's hosted file search (black box)
- **OGX Vector** -- pure semantic search with Nomic embeddings
- **OGX Hybrid** -- semantic + keyword search, fused with RRF and reranked
- **OGX Hybrid + Contextual** -- hybrid search with contextual chunking (gpt-4.1-mini prepends document-level context to each chunk before embedding)

For end-to-end RAG, we also tested **Gemma 31B** (`google/gemma-4-31B-it` via vLLM) as an alternative to GPT-4.1.

## Retrieval Results: BEIR

BEIR is the standard benchmark for information retrieval. We evaluated on four diverse datasets spanning biomedical literature, scientific fact-checking, argument mining, and financial QA.

### nDCG@10

| Dataset | OpenAI | OGX Vector | OGX Hybrid | OGX Hybrid + Contextual | Best Delta vs OpenAI |
|---------|--------|------------|------------|-------------------------|----------------------|
| nfcorpus | 0.3156 | 0.3106 | **0.3350** | 0.3316 | **+6.1%** |
| scifact | **0.7165** | 0.6943 | 0.7137 | 0.7086 | -0.4% |
| arguana | 0.2960 | 0.3765 | 0.3835 | **0.3936** | **+33.0%** |
| fiqa | 0.2862 | 0.2399 | 0.2170 | **0.3586** | **+25.3%** |

### Recall@10

| Dataset | OpenAI | OGX Vector | OGX Hybrid | OGX Hybrid + Contextual | Best Delta vs OpenAI |
|---------|--------|------------|------------|-------------------------|----------------------|
| nfcorpus | 0.1469 | 0.1482 | **0.1646** | **0.1653** | **+12.5%** |
| scifact | 0.8067 | **0.8369** | 0.8362 | 0.8284 | **+3.7%** |
| arguana | 0.6764 | 0.7610 | 0.7781 | **0.7902** | **+16.8%** |
| fiqa | 0.3117 | 0.2843 | 0.2681 | **0.4358** | **+39.8%** |

With contextual chunking, OGX now wins on **all 4 datasets** in both nDCG@10 and Recall@10. The fiqa result is the standout: contextual chunking transforms OGX from 24% behind OpenAI to 25% ahead, a +65% improvement over standard hybrid. On arguana, contextual chunking pushes the lead from 29.6% to 33.0%.

## End-to-End RAG: MultiHOP and Doc2Dial

Retrieval is only half the story. End-to-end RAG tests whether the system can retrieve relevant context _and_ produce correct answers. We used GPT-4.1 as the generation model for both OpenAI and OGX pipelines, plus Gemma 31B as an open-source alternative.

### MultiHOP RAG (F1 Score)

MultiHOP tests multi-hop reasoning over 609 news articles with 2,556 queries that require synthesizing information across documents.

| Configuration | F1 | ROUGE-L | vs OpenAI |
|--------------|-----|---------|-----------|
| OpenAI | 0.0114 | 0.0116 | -- |
| OGX Vector + GPT-4.1 | 0.0141 | 0.0147 | +23.7% |
| OGX Hybrid + GPT-4.1 | 0.0141 | 0.0147 | +23.7% |
| OGX Hybrid + Contextual + GPT-4.1 | 0.0136 | 0.0134 | +19.3% |
| OGX Hybrid + Gemma 31B | **0.0207** | **0.0203** | **+81.6%** |

The headline number: **OGX with Gemma 31B scores 81.6% higher F1 than OpenAI with GPT-4.1 on multi-hop reasoning.** Even with GPT-4.1 on both sides, OGX's retrieval pipeline delivers 23.7% better end-to-end accuracy. Contextual chunking delivers strong retrieval metrics (nDCG@10 = 0.62, Recall@10 = 0.70), confirming the retrieval layer works well even when generation scores remain low.

### Doc2Dial (F1 Score)

Doc2Dial evaluates document-grounded dialogue: 488 documents, 200 conversations, 1,203 turns.

| Configuration | F1 | ROUGE-L |
|--------------|-----|---------|
| OpenAI | **0.1337** | **0.1136** |
| OGX Vector + GPT-4.1 | 0.0962 | 0.0790 |
| OGX Hybrid + GPT-4.1 | 0.0966 | 0.0794 |
| OGX Hybrid + Contextual + GPT-4.1 | 0.1101 | 0.0902 |
| OGX Hybrid + Gemma 31B | 0.0634 | 0.0513 |

OpenAI still leads, but contextual chunking narrows the gap from 39% to 18% on F1 (0.1101 vs 0.1337). Doc2Dial's conversational format benefits from OpenAI's retrieval handling of conversational context, but contextual chunking helps OGX by providing better chunk-level context for dialogue grounding. Gemma 31B's lower score is partly explained by its verbosity (~2,500 characters average vs ~95 character ground truths), which penalizes token-level F1 even when the answer content is correct. Notably, Gemma produced **zero empty responses** across all 1,203 queries.

## What This Means

Three takeaways from these benchmarks:

**1. Hybrid search + contextual chunking is the strongest configuration.** With contextual chunking, OGX now wins on all 4 BEIR datasets — including fiqa, where standard hybrid search lagged behind OpenAI. The +65% improvement on fiqa shows that domain-specific text benefits enormously from LLM-generated chunk context.

**2. Open-source models can win at end-to-end RAG.** Gemma 31B with OGX retrieval outperformed GPT-4.1 with OpenAI retrieval on multi-hop reasoning by a wide margin. The retrieval pipeline matters as much as the generation model.

**3. The configurability pays off.** OpenAI still leads on conversational grounding (Doc2Dial), but contextual chunking cuts the gap from 39% to 18%. OGX leads on biomedical, scientific, argumentative, and financial retrieval, plus multi-hop reasoning. The ability to tune chunking strategy, embedding model, and search mode per-domain is a concrete advantage.

## Reproduce It Yourself

The full benchmark suite is open source and reproducible. See the [RAG Benchmarks documentation](https://ogx-ai.github.io/docs/building_applications/rag_benchmarks) for setup instructions, dataset details, and methodology.

All benchmarks run through the standard OpenAI-compatible API, so you can swap in your own embedding models, rerankers, or vector databases and measure the impact directly.

## What's Next

We're expanding the benchmark suite with additional datasets and retrieval configurations. Areas we're investigating:

- **Embedding model comparisons** -- testing newer embedding models against Nomic
- **Conversational retrieval** -- improving Doc2Dial performance with conversation-aware search
- **Larger-scale benchmarks** -- datasets with 100K+ documents to test scaling behavior

**Update (July 2026):** We've completed contextual chunking benchmarks across all 6 datasets. Contextual chunking with gpt-4.1-mini closes the fiqa gap entirely (+65% nDCG@10) and narrows the Doc2Dial gap from 39% to 18%. Results have been added to the tables above.

If you're running RAG workloads in production and want to see how OGX compares on your data, [get started with OGX](https://ogx-ai.github.io/docs/getting_started/) or join the conversation on [GitHub](https://github.com/ogx-ai/ogx).

---

### Blog 2026 06 02 Bedrock Aws Auth (`docs/blog/2026-06-02-bedrock-aws-auth.md`)

---
slug: ogx-bedrock-aws-auth
title: "Use Amazon Bedrock with OGX Without Managing Bearer Tokens"
authors: [skamenan7]
tags: [ogx, aws, bedrock, sigv4, sts]
date: 2026-06-02
---

OGX now signs Bedrock requests with standard AWS SigV4, so the server uses the same credential chain your platform already runs. No bearer tokens to manage, no custom auth plumbing in your application code.

If your team uses IAM roles, IRSA, or STS for Bedrock access, this means OGX fits into your existing AWS identity model without extra moving parts. Apps talk to one OpenAI-compatible API while OGX handles the provider-specific auth behind the scenes.

For the implementation details, see [issue #4730](https://github.com/ogx-ai/ogx/issues/4730) and [PR #5388](https://github.com/ogx-ai/ogx/pull/5388).



## Why this helps teams adopt OGX

If you are evaluating OGX for production use, this change makes Bedrock easier to fit into an existing AWS environment:

- You can keep using existing OpenAI-compatible clients and agent frameworks.
- You can use standard AWS identity flows, including IAM roles, IRSA, web identity, AWS profiles, and short-lived credentials.
- You do not have to teach every app or service how Bedrock-specific auth works.
- You can keep OGX as the abstraction layer, so switching between Bedrock and other providers stays an infrastructure choice instead of an application rewrite.

The practical effect is less custom auth plumbing at the application layer. Teams can use Bedrock through OGX without giving up the AWS identity flows they already operate.

## What shipped

The core change is a SigV4 path for the Bedrock inference adapter. When `aws_bedrock_bearer_token` is absent, OGX now signs Bedrock requests with AWS SigV4 instead of assuming every request will carry a precomputed bearer token.

That shipped with a few important pieces:

- SigV4 request signing for the Bedrock OpenAI-compatible runtime.
- STS web identity support through `aws_role_arn` and `aws_web_identity_token_file`.
- Automatic refresh of temporary credentials.
- Shared Bedrock config updates so the AWS auth story is consistent across the Bedrock provider code.
- Compatibility with existing bearer-token mode, so this is additive rather than breaking.

For users, the result is simple: if OGX has access to normal AWS credentials, it can talk to Bedrock without requiring a separate token-management workflow.

## How it fits together

From the application side, the client shape stays the same: point a standard client at OGX and let OGX handle the provider details.

```python
import requests
from openai import OpenAI

base_url = "http://localhost:8321"
model_id = requests.get(f"{base_url}/v1/models", timeout=10).json()["data"][0]["id"]

client = OpenAI(base_url=f"{base_url}/v1", api_key="ogx")

response = client.chat.completions.create(
    model=model_id,
    messages=[{"role": "user", "content": "Explain why OGX is useful"}],
)
```

## Try it now

If you already have AWS credentials available through a profile, IAM role, IRSA, or web identity, this is a short path to a working Bedrock request through OGX.

### 1. Export your AWS environment

```bash
export AWS_DEFAULT_REGION=us-west-2

# Pick the option that matches your environment:
# export AWS_PROFILE=default
# export AWS_ROLE_ARN=arn:aws:iam::<account-id>:role/<role-name>
# For EKS IRSA:
# export AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token
```

### 2. Write a minimal `config.yaml`

```bash
cat > config.yaml <<'EOF'
version: 2
distro_name: bedrock-sigv4-demo
apis:
  - inference
  - models
providers:
  inference:
    - provider_id: bedrock-inference
      provider_type: remote::bedrock
      config:
        # aws_bedrock_bearer_token intentionally omitted so OGX uses the AWS credential chain
        region_name: ${env.AWS_DEFAULT_REGION:=us-west-2}
        aws_role_arn: ${env.AWS_ROLE_ARN:=}
        aws_web_identity_token_file: ${env.AWS_WEB_IDENTITY_TOKEN_FILE:=}
        aws_role_session_name: ${env.AWS_ROLE_SESSION_NAME:=ogx-bedrock-demo}
        session_ttl: ${env.AWS_SESSION_TTL:=3600}

storage:
  backends:
    kv_default:
      type: kv_sqlite
      db_path: ./.ogx/kvstore.db
    sql_default:
      type: sql_sqlite
      db_path: ./.ogx/sql_store.db
  stores:
    metadata:
      namespace: registry
      backend: kv_default
    inference:
      table_name: inference_store
      backend: sql_default
      max_write_queue_size: 10000
      num_writers: 4
    prompts:
      namespace: prompts
      backend: kv_default

registered_resources:
  models:
    - metadata: {}
      model_id: openai.gpt-oss-20b-1:0
      provider_id: bedrock-inference
      provider_model_id: openai.gpt-oss-20b-1:0
      model_type: llm
EOF
```

### 3. Start OGX

```bash
uv run ogx run --port 8321 ./config.yaml
```

Leave that terminal running. In a second terminal, use the steps below.

### 4. Verify the model is available

```bash
MODEL_ID=$(curl -s http://localhost:8321/v1/models | jq -r '.data[0].id // empty')
test -n "$MODEL_ID" && echo "Using model: $MODEL_ID"
```

If you want to inspect the full model list:

```bash
curl -s http://localhost:8321/v1/models | jq
```

### 5. Send your first request with `curl`

```bash
curl -s -X POST "http://localhost:8321/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"$MODEL_ID\",
    \"messages\": [{\"role\": \"user\", \"content\": \"Which planet do humans live on?\"}],
    \"stream\": false
  }" | jq -r '.choices[0].message.content'
```

### 6. Send the same request from the OpenAI Python client

```bash
uv run python - <<'PY'
import requests
from openai import OpenAI

base_url = "http://localhost:8321"
model_id = requests.get(f"{base_url}/v1/models", timeout=10).json()["data"][0]["id"]

client = OpenAI(base_url=f"{base_url}/v1", api_key="ogx")

response = client.chat.completions.create(
    model=model_id,
    messages=[{"role": "user", "content": "Which planet do humans live on?"}],
    stream=False,
)

print(response.choices[0].message.content)
PY
```

If you are only doing a quick local spike and already have a pre-signed Bedrock bearer token, that path still works. For long-running deployments, leave bearer auth unset and let OGX use the standard AWS identity flow instead.

If you do use a bearer token, make sure it was generated for the same AWS Region that OGX is using. A token scoped to `us-east-2` will be rejected by a Bedrock endpoint configured for `us-west-2`, and vice versa.

There are two common paths here: direct SigV4-backed inference for `chat/completions`, and a Bedrock-backed `Responses` path for higher-level workflows such as tool calling. The steps above focus on the shorter `chat/completions` path.

That path has been exercised end to end through the standard OGX surface: model resolution from `/v1/models`, non-streaming and streaming `chat/completions`, fallback to SigV4 when empty bearer overrides are supplied, successful bearer-token overrides when explicitly provided, rejection of invalid bearer overrides, concurrent request isolation, and repeated request smoke checks. For someone evaluating OGX, that is the important part: the AWS-native path works through the same API shape your applications already use.

## Migration

If your config already uses `api_key` or `aws_bearer_token_bedrock`, it still works. No changes required. OGX accepts both the old and new field names through Pydantic aliases.

For new deployments, use the canonical name `aws_bedrock_bearer_token` in your config and `AWS_BEDROCK_BEARER_TOKEN` as the environment variable. Per-request bearer overrides via the `x-ogx-provider-data` header also accept both old and new field names.

---

### Blog 2026 06 09 Claude Code Integration (`docs/blog/2026-06-09-claude-code-integration.md`)

---
slug: claude-code-integration
title: "Using Claude Code with Any Model via OGX"
authors: [leseb, cdoern]
tags: [claude-code, anthropic, integration, tutorial, vllm, ollama, openai]
date: 2026-06-09
---

Claude Code is one of the best coding assistants available. But what if you want to use it with GPT-4o, Qwen, Llama, or a model running on your own hardware? OGX makes that possible. A single command connects Claude Code to your OGX server, auto-discovers your models, and maps them to Claude's haiku/sonnet/opus tiers.

This post walks through the setup, explains how the translation works under the hood, and shows how to configure multi-provider routing so different Claude Code model tiers hit different backends.



## The idea

Claude Code talks to the Anthropic Messages API (`/v1/messages`). OGX implements that API. When Claude Code sends a request, OGX receives it, translates the format if needed, and forwards it to whatever inference provider you've configured — OpenAI, vLLM, Ollama, Fireworks, Groq, Bedrock, or any of the other [supported providers](https://ogx-ai.github.io/docs/providers).



The translation layer handles message format conversion, tool call transformations, streaming event reformatting, and extended thinking (including signature deltas and redacted thinking blocks). For providers that already support the Messages API natively (Ollama and vLLM with compatible models), OGX passes requests through directly — no translation overhead.

## Quick start

Two commands. Two minutes.

### 1. Start OGX

Pick your provider and start the server:

```bash
# With OpenAI
export OPENAI_API_KEY="your-key-here"
ogx run starter

# With vLLM
export VLLM_URL="http://localhost:8000/v1"
ogx run starter

# With Ollama
export OLLAMA_URL="http://localhost:11434/v1"
ogx run starter
```

### 2. Connect Claude Code

```bash
ogx connect claude
```

That's it. The command queries your OGX server for available models, maps them to Claude's haiku/sonnet/opus tiers, sets the right environment variables (including unsetting any Vertex/Bedrock variables that would bypass OGX), and launches Claude Code.

### What `ogx connect claude` does

```text
ogx connect claude
       |
       v
  GET /v1/models (discover available models)
       |
       v
  Map models to Claude tiers (haiku/sonnet/opus)
       |
       v
  Launch claude with ANTHROPIC_BASE_URL + tier env vars
```

No manual environment variable setup. No remembering which model names map to which tiers. No Vertex/Bedrock conflicts.

## Model configuration

### Default behavior

With no flags, `ogx connect claude` maps all three Claude tiers to the first available LLM model on your OGX server.

### One model for all tiers

```bash
ogx connect claude --model openai/gpt-4o
```

### Different models per tier

This is the real power — route fast tasks to cheap local models and complex reasoning to cloud APIs:

```bash
ogx connect claude \
  --haiku-model openai/gpt-4o-mini \
  --sonnet-model openai/gpt-4o \
  --opus-model openai/o1
```

### Shell integration with `--print-env`

Instead of launching Claude Code, print the environment variables for manual use:

```bash
eval "$(ogx connect claude --print-env --model openai/gpt-4o)"
claude "Hello world"
```

### Forwarding arguments to Claude Code

Anything after `--` is passed through to `claude`:

```bash
ogx connect claude -- -p "Write a hello world function"
```

## Provider setup examples

### OpenAI

```bash
# Terminal 1
export OPENAI_API_KEY="sk-..."
ogx run starter

# Terminal 2
ogx connect claude --model openai/gpt-4o
```

### vLLM with Qwen

```bash
# Start vLLM
vllm serve Qwen/Qwen3-8B --api-key fake

# Terminal 1
export VLLM_URL="http://localhost:8000/v1"
ogx run starter

# Terminal 2
ogx connect claude --model vllm/Qwen/Qwen3-8B
```

### Ollama with Llama

```bash
ollama serve
ollama pull llama3.3:70b

# Terminal 1
export OLLAMA_URL="http://localhost:11434/v1"
ogx run starter

# Terminal 2
ogx connect claude --model ollama/llama3.3:70b
```

### Multiple providers with per-tier routing

```bash
# Terminal 1
export VLLM_URL="http://localhost:8000/v1"
export OPENAI_API_KEY="sk-..."
ogx run starter

# Terminal 2
ogx connect claude \
  --haiku-model vllm/Qwen/Qwen3-8B \
  --sonnet-model openai/gpt-4o \
  --opus-model openai/o1
```

## What's supported

All core Claude Code features work through OGX:

- **Multi-turn conversations** with system messages and streaming
- **Tool use** — file operations, shell commands, code execution (these run in Claude Code's runtime, not OGX)
- **Extended thinking** — full support including signature deltas and redacted thinking blocks in passthrough mode; clear error when attempting thinking in translation mode
- **Token counting** via `/v1/messages/count_tokens`
- **Prompt caching** — `cache_control` breakpoints from the Anthropic SDK are forwarded correctly in passthrough mode
- **Any inference provider** — OpenAI, vLLM, Ollama, Fireworks, Together, Groq, Bedrock, etc.

Provider capabilities differ:

| Provider | Native Messages API | Thinking Support | Prompt Caching |
|----------|-------------------|------------------|----------------|
| OpenAI | ❌ (translated) | ⚠️ (via reasoning) | ❌ |
| vLLM | ✅ | ❌ | ❌ |
| Ollama | ✅ | ❌ | ❌ |
| Bedrock, Fireworks, Groq, Together | ❌ (translated) | ❌ | ❌ |

## Advanced: custom model mappings

For more control over how Claude model names map to providers, register models explicitly via the API:

```bash
curl http://localhost:8321/v1/models \
  -H "Content-Type: application/json" \
  -d '{
    "model_id": "claude-haiku-4-5-20251001",
    "provider_id": "vllm",
    "provider_model_id": "Qwen/Qwen3-8B",
    "model_type": "llm"
  }'
```

Or declaratively in `config.yaml`:

```yaml
registered_resources:
  models:
  - model_id: claude-haiku-4-5-20251001
    provider_id: vllm
    provider_model_id: Qwen/Qwen3-8B
    model_type: llm
```

## Claude Agent SDK

If you're building custom agents with the Claude Agent SDK, OGX works as a drop-in backend:

```python
from claude_agent_sdk import Agent

agent = Agent(
    base_url="http://localhost:8321",
    api_key="fake",
    model="vllm/Qwen/Qwen3-8B",
)

response = agent.send("Write a function to parse CSV files")
```

## Manual setup (without `ogx connect claude`)

If you prefer to configure environment variables yourself:

```bash
export ANTHROPIC_BASE_URL="http://localhost:8321"
export ANTHROPIC_AUTH_TOKEN="ogx"

# Map Claude model tiers to your backend models
export ANTHROPIC_DEFAULT_HAIKU_MODEL="openai/gpt-4o-mini"
export ANTHROPIC_DEFAULT_SONNET_MODEL="openai/gpt-4o"
export ANTHROPIC_DEFAULT_OPUS_MODEL="openai/o1"

# Unset any Vertex/Bedrock variables
unset CLAUDE_CODE_USE_VERTEX
unset ANTHROPIC_VERTEX_PROJECT_ID
unset CLAUDE_CODE_USE_BEDROCK

claude "Write a hello world function in Python"
```

## Troubleshooting

**`max_tokens` errors with OpenAI models** — Claude Code requests token limits based on Claude model specs, which may exceed what the backend model supports. Use a model with higher token limits, or use per-tier flags to route different workloads appropriately.

**"Failed to connect to OGX server"** — The OGX server isn't running or isn't reachable. Start it with `ogx run starter`.

**"Failed to find any LLM models"** — The server is running but has no LLM models registered. Check your distribution config and ensure at least one inference provider is configured.

**Claude Code ignores `ANTHROPIC_BASE_URL` (manual setup only)** — If `CLAUDE_CODE_USE_VERTEX=1` or similar is set, Claude Code bypasses `ANTHROPIC_BASE_URL`. The `ogx connect claude` command handles this automatically. For manual setup, unset those variables first.

**Slow cloud provider responses** — Expected. Claude Code → OGX → provider adds a network hop. Use local providers (vLLM, Ollama) for lower latency. The format translation itself adds only ~5-20ms.

**Tool use not working** — Tool execution happens in Claude Code's runtime, not OGX. Make sure Claude Code has the right permissions and your model supports tool use.

## What's next

The [full documentation](https://ogx-ai.github.io/docs/building_applications/claude_code_integration) covers the complete CLI reference, performance tuning, and provider-specific configuration. If you run into issues or want to improve the integration, [open an issue](https://github.com/ogx-ai/ogx/issues) or join us on [Discord](https://discord.gg/ZAFjsrcw).

---

### Blog 2026 06 16 Claude Code Blog (`docs/blog/2026-06-16-claude-code-blog.md`)

---
slug: claude-code-blog
title: "OGX ❤️ Claude Code"
authors: [nathan-weinberg]
tags: []
date: 2026-06-16
---

[Claude Code](https://claude.com/product/claude-code) is an AI coding tool developed and maintained by Anthropic. It has become an industry leader for AI coding assistance and allows users to create plans, manage agents, develop their own custom skills, and more.

Today we are happy to announce `ogx connect` support for Claude Code, allowing OGX users to launch Claude Code directly and access models on their OGX server. Our configuration allows the use of a single model for all tasks as well as custom mappings of up to three models for differing tasks.

Using OGX as your backend for Claude Code can provide some strong advantages over different backend options:

- Control your budget by offering a mixture of different models from different sources, rather than relying on a single backend provider
- Take advantage of Claude Code's mapping of models to seamlessly switch between self-hosted and SaaS options with no server interactions required
- Ensure redundancy by never being reliant on one SaaS backend, always keeping Claude Code running for users of your OGX server

In this blog I am going to share how to start running Claude Code using models on an OGX server, using a remote server that has both self-hosted and SaaS models enabled.

The blog assumes you already have the OGX server up and running on a remote host - see our [Getting Started guide](https://ogx-ai.github.io/docs/getting_started/quickstart) to learn more.

## Download Claude Code

Our first step here is to actually download and install Claude Code. You can see all the downloading options from [the Claude Code website](https://claude.com/product/claude-code) but generally the below `curl` command is suifficient in most cases.

```bash
curl -fsSL https://claude.ai/install.sh | bash
```

## Use Claude Code with OGX

As mentioned before, this blog assumes an OGX server is already running at `myremoteserver.com:8321` - in this case, we are also making the following assumptions:

- The `remote::vllm` provider is enabled, serving the `Qwen/Qwen3-8B` model
- The `remote::gemini` provider is enabled, with the `gemini-2.5-pro` model available
- The `remote::openai` provider is enabled, with the `gpt-4o` model available
- No authentication has been added

You can verify what models your OGX server has available with `curl http://myremoteserver.com:8321/v1/models`

Now comes the easy part - run this simple command below to start up Claude Code with your specific models:

```bash
ogx connect claude \
  --haiku-model vllm/Qwen/Qwen3-8B \
  --sonnet-model gemini/models/gemini-2.5-pro \
  --opus-model openai/gpt-4o \
  --url http://myremoteserver.com:8321/v1
```

You should be greeted by a Claude Code TUI that looks something like this:



Running `/model` should show the models you've selected as they were configured:

---

### Blog 2026 06 23 Guardrails Responses Api (`docs/blog/2026-06-23-guardrails-responses-api.md`)

---
slug: guardrails-responses-api
title: "Under the Hood: How OGX Enforces Guardrails Inside the Agentic Loop"
authors:
  - leseb
tags: [responses-api, guardrails, safety, streaming, agents]
date: 2026-06-23
---

AI agents that call tools, search documents, and reason over multiple turns are powerful, but they also need boundaries. A model that can execute a web search or query your internal knowledge base should not be free to produce harmful content along the way.

OGX implements guardrails as a first-class feature of the Responses API. Unlike bolt-on moderation that checks content after the fact, OGX validates content at two critical points inside the agentic loop: before inference starts and while user-visible text and reasoning output streams. This post explains exactly how that works, why the design choices matter, and how to use it in practice.



## The problem with post-hoc moderation

Most moderation systems work outside the generation pipeline. You send a prompt to the model, get a response, then send that response to a moderation endpoint. If the content is flagged, you discard it and show an error.

This approach has two problems:

1. **Wasted compute.** The model generates the full response before you discover it violates a policy. For long, multi-turn agentic responses with tool calls, this can mean minutes of wasted work.
2. **Latency gap during streaming.** If you are streaming tokens to the user, you either block the entire stream until moderation completes (defeating the purpose of streaming) or you show tokens before they are validated (defeating the purpose of moderation).

OGX solves both problems by embedding guardrail checks directly inside the response orchestration loop.

## How to use guardrails

From the client side, guardrails are a single boolean on the Responses API:

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8321/v1", api_key="unused")

response = client.responses.create(
    model="openai/gpt-4o-mini",
    input="Summarize this text.",
    extra_body={"guardrails": True},
)
print(response.output_text)
```

Setting `guardrails` to `True` tells the server to run request input plus generated text and reasoning content through the configured moderation endpoint. If the content is flagged, or if moderation cannot be completed safely, the response is replaced with a refusal. No shield IDs, no model lists, no moderation credentials on the client side.

The same parameter works with streaming, tool calls, MCP, and multi-turn conversations. No changes to your orchestration logic are needed.

### Why a boolean?

Earlier versions of OGX required clients to pass a list of shield identifiers (e.g., `"guardrails": ["llama-guard", "content-filter"]`), and the server would resolve each ID to a registered provider, manage routing tables, and coordinate multiple safety backends. This created real operational complexity: six safety providers with different auth, configuration, and edge cases, all for a feature that most deployments use as a simple yes/no gate.

The new design replaces all of that with server-side moderation configuration and a boolean on the client. The platform administrator picks the moderation service once; application developers just flip the switch.

## Server configuration

Guardrails require a `moderation_endpoint` to be configured on the builtin responses provider. This is the URL of any OpenAI-compatible `/v1/moderations` endpoint. If the endpoint requires authentication, configure `moderation_headers` beside it.

```yaml
providers:
  responses:
    - provider_id: builtin
      provider_type: inline::builtin
      config:
        moderation_endpoint: "https://api.openai.com/v1/moderations"
        moderation_headers:
          Authorization: "Bearer ${env.OPENAI_API_KEY}"
```

You can point this at OpenAI's moderation API, an OpenAI-compatible gateway in front of a hosted content safety service, a self-hosted moderation model, or any service that accepts `POST {"input": "text"}` and returns `{"results": [{"flagged": bool, "categories": {...}}]}`. The server makes a direct HTTP call — no proxy layer, no routing table, no provider abstraction in between.

`moderation_headers` are server-side only. They are never exposed to clients, and they are treated as sensitive configuration when OGX redacts config output. This keeps moderation credentials on the platform side and out of application requests.

If a client sends `guardrails: True` but no `moderation_endpoint` is configured, the server returns an error immediately rather than silently skipping validation:

```python
if enable_guardrails and not self.moderation_endpoint:
    raise ServiceNotEnabledError(
        "moderation_endpoint",
        provider_specific_message=(
            "Guardrails require a moderation endpoint to be configured "
            "on the server. Contact your platform administrator to set "
            "'moderation_endpoint' on the responses provider, or remove "
            "the 'guardrails' parameter from your request."
        ),
    )
```

## The agentic loop

To understand where guardrails fit, you need to understand how OGX orchestrates a Responses API call. The core of the implementation is the `StreamingResponseOrchestrator` class, which runs an iterative loop that interleaves inference, tool execution, and content validation.

Here is the high-level flow:

```text
1. Client sends request with input, tools, and guardrails: True
2. Server converts input to chat completion messages
3. INPUT GUARDRAIL CHECK ← validates all user messages
4. If violation → return refusal immediately
5. Enter agentic loop:
   a. Call inference (chat completion) with current messages
   b. Buffer generated text/reasoning chunks
      └── OUTPUT GUARDRAIL CHECK ← validates buffered content in batches
      └── If violation → replace stream with refusal
   c. Parse tool calls from model output
   d. Execute server-side tools (web search, file search, MCP)
   e. Append tool results to message history
   f. If more tool calls needed → go to (a)
   g. If only client-side function calls → return to client
6. Emit final response (completed / incomplete / failed)
```

The loop continues until one of these conditions is met:

- The model produces a final text response with no tool calls
- The maximum iteration count is reached (default: 10)
- Only client-side function calls remain (the client needs to execute them)
- A guardrail violation is detected
- The `max_output_tokens` budget is exhausted

Each iteration through the loop is a full inference call. The model sees the accumulated conversation history including previous tool results, so it can reason about what it has learned and decide what to do next.

## Checkpoint 1: input validation

Before the agentic loop begins, OGX checks the user's input against the moderation endpoint:

```python
if self.enable_guardrails:
    combined_text = interleaved_content_as_str(
        [msg.content for msg in self.ctx.messages]
    )
    input_violation_message = await run_guardrails(
        self.moderation_endpoint,
        combined_text,
        headers=self.moderation_headers,
    )
    if input_violation_message:
        yield await self._create_refusal_response(input_violation_message)
        return
```

This flattens all input messages into a single text string and sends it to the moderation endpoint. If the content is flagged, the entire response is short-circuited: no inference call happens, no tokens are generated, no tools are executed. The client receives a `response.completed` event containing a refusal content part instead of the model's output.

This matters because it prevents the model from ever seeing harmful input. Without input validation, a jailbreak prompt could manipulate the model into producing harmful tool calls or responses that might pass output validation in isolation.

## Checkpoint 2: batched streaming validation

Output validation is more nuanced. During streaming, the model generates tokens one at a time. Calling the moderation endpoint for every token would be prohibitively slow. But waiting for the entire response would defeat the purpose of streaming.

OGX takes a middle path: **batched chunk validation**. Here is how it works:

```text
For each streaming chunk from the inference provider:
  1. Accumulate text and reasoning content deltas
  2. Buffer the streaming event (don't emit to client yet)
  3. Track characters since last check

  When characters >= 200:
    a. Send accumulated text to moderation endpoint
    b. If violation:
       - Discard all buffered events
       - Emit refusal response
       - Stop processing the stream
    c. If clean:
       - Emit all buffered events to client
       - Reset character counter

  After stream ends:
    Final guardrail check on any remaining buffered content
```

The 200-character batch size is a deliberate tradeoff. Smaller batches catch violations sooner but increase moderation API calls. Larger batches reduce overhead but delay detection. 200 characters is roughly a sentence, which gives the moderation model enough context to make accurate judgments while keeping latency acceptable.

Here is the core of the batched validation logic:

```python
_GUARDRAIL_BATCH_CHARS = 200

# Inside _process_streaming_chunks:
# Reasoning characters count toward the batch threshold alongside text content.
guardrail_check_due = chars_since_last_check >= _GUARDRAIL_BATCH_CHARS

if self.enable_guardrails and guardrail_check_due:
    accumulated_text = "".join(chat_response_content + reasoning_text_accumulated)
    violation_message = await run_guardrails(
        self.moderation_endpoint,
        accumulated_text,
        headers=self.moderation_headers,
    )
    if violation_message:
        pending_guardrail_events.clear()
        yield await self._create_refusal_response(violation_message)
        self.violation_detected = True
        return
    for event in pending_guardrail_events:
        yield event
    pending_guardrail_events.clear()
    chars_since_last_check = 0
```

A key detail: each validation call sends the **entire accumulated text so far** — including both text content and reasoning content — not just the new batch. This gives the moderation model full context for content whose risk depends on previous sentences.

### What happens when reasoning is present

Some models produce reasoning content (chain-of-thought) alongside their text output. Reasoning events are user-visible in the Responses stream, so they must pass through guardrail validation just like text content.

When guardrails are enabled, reasoning events are buffered alongside text events and included in the accumulated text sent to the moderation endpoint. Reasoning characters count toward the 200-character batch threshold, so reasoning-only responses still trigger timely moderation checks. No reasoning content reaches the client until it has been validated.

### The final flush

After the inference stream ends, there may be buffered events that have not reached the 200-character threshold. OGX runs one final guardrail check on this remaining content before emitting it:

```python
if self.enable_guardrails and pending_guardrail_events:
    accumulated_text = "".join(chat_response_content + reasoning_text_accumulated)
    violation_message = await run_guardrails(
        self.moderation_endpoint,
        accumulated_text,
        headers=self.moderation_headers,
    )
    if violation_message:
        pending_guardrail_events.clear()
        yield await self._create_refusal_response(violation_message)
        self.violation_detected = True
        return
    for event in pending_guardrail_events:
        yield event
```

This ensures the final buffered text and reasoning events are validated before they reach the client, regardless of how the stream ends.

## The moderation call

The `run_guardrails` function is intentionally simple. It makes a single HTTP POST to the configured endpoint using the OpenAI moderation format:

```
/* Detailed source-code truncated for AI context efficiency. */
```

A key detail: this function **fails closed**. If the moderation service is unreachable, returns an error, or returns a malformed response, the function returns a blocking message rather than `None`. Content is never allowed through when the moderation check cannot be performed. Only a clean, parseable response with `"flagged": false` returns `None`.

No provider abstraction, no routing table, no shield resolution. One HTTP call, one JSON response. The moderation endpoint is expected to return the [OpenAI moderation response format](https://platform.openai.com/docs/api-reference/moderations/object): a `results` array where each element has `flagged` (boolean) and `categories` (dict of category names to booleans). The optional `headers` parameter lets the server pass authentication credentials configured via `moderation_headers` in the provider config.

This simplicity is a feature. The previous implementation required registering safety providers, managing shield routing tables, resolving guardrail IDs to model IDs, and coordinating multiple backends through an internal Safety API. All of that infrastructure existed to support a `/v1/moderations` proxy endpoint that clients could call directly — but the only place where server-side moderation actually adds value is inside the agentic loop, where the orchestrator needs to check content mid-generation. That is exactly what `run_guardrails` does.

## The refusal response

When a guardrail violation is detected at either checkpoint, OGX constructs a complete `response.completed` event with a refusal content part:

```python
async def _create_refusal_response(self, violation_message: str):
    refusal_content = OpenAIResponseContentPartRefusal(refusal=violation_message)
    refusal_response = OpenAIResponseObject(
        id=self.response_id,
        status="completed",
        output=[
            OpenAIResponseMessage(
                role="assistant",
                content=[refusal_content],
            )
        ],
        # ... other fields preserved
    )
    return OpenAIResponseObjectStreamResponseCompleted(response=refusal_response)
```

The refusal is a proper Responses API object. Clients that handle the `refusal` content type can display an appropriate message. The violation message includes which categories were flagged, so applications can take context-appropriate action.

## Guardrails and the multi-turn tool loop

Guardrails interact with the agentic loop in an important way: they check generated text and reasoning content, not raw tool results or tool-call arguments. Here is why.

Server-side tools (web search, file search, MCP) are executed by the server in a controlled environment. Their results are structured data that gets injected into the conversation history for the next inference call. The model then reasons about those results and produces text output, which is where guardrails apply.

This design means:

- A web search result containing harmful content will not trigger a guardrail violation on its own
- But if the model incorporates that harmful content into text or reasoning output, that output goes through moderation
- Tool calls themselves are not blocked by guardrails; tool authorization remains a separate control from content moderation

When a violation is detected mid-loop, the `violation_detected` flag stops all further processing:

```python
async for stream_event_or_result in self._process_streaming_chunks(
    completion_result, output_messages
):
    if isinstance(stream_event_or_result, ChatCompletionResult):
        completion_result_data = stream_event_or_result
    else:
        yield stream_event_or_result

# If violation detected, skip the rest of processing
if self.violation_detected:
    return
```

No further inference iterations are made, no more tools are executed, and no more buffered text or reasoning events are emitted.

## Design principles

Several principles guided this implementation:

**Fail closed, not open.** If guardrails are requested and no moderation endpoint is configured, the request fails rather than proceeding without validation.

**No unvalidated buffered content.** Text and reasoning events are held until the current guardrail batch passes. When a violation is detected during streaming, the current buffer is discarded, a refusal is emitted, and generation stops.

**Validation with context.** Each output guardrail check sends the full accumulated text, not just the latest batch. This helps catch content whose risk only becomes clear when multiple chunks are read together.

**Minimal latency impact.** Input validation adds one moderation call before inference. Output validation adds roughly one call per 200 characters of text and reasoning output, plus a final check for any remaining buffered content.

**Guardrails are opt-in.** When `guardrails` is not set, no moderation checks are performed, and streaming events flow directly to the client.

**Configuration belongs on the server.** The choice of moderation service is an infrastructure decision, not an application decision. Platform administrators set `moderation_endpoint` once; application developers just pass `guardrails: True`.

## What was removed and why

The previous guardrails implementation was built on top of a full Safety API subsystem: protocol definitions, routing tables, a shield registry, seven safety providers (Llama Guard, Prompt Guard, Code Scanner, Bedrock, NVIDIA, SambaNova, Passthrough), and a standalone `/v1/moderations` proxy endpoint.

All of that has been removed. The standalone `/v1/moderations` endpoint added a network hop for zero value — clients already know how to call moderation services directly. The provider abstraction existed to support that proxy, but the only server-side value is guardrails during generation, where the orchestrator needs to run moderation checks mid-stream. That is now a direct HTTP call from the responses provider.

The result is less code, fewer moving parts, and a clearer contract: one endpoint, optional server-side headers, one HTTP call per check, and one boolean flag on the request.

## Try it

If you are running OGX, you can add guardrails to any existing Responses API call:

```python
response = client.responses.create(
    model="openai/gpt-4o-mini",
    input="Your prompt here",
    tools=[{"type": "web_search_preview"}],
    extra_body={"guardrails": True},
)
```

Guardrails work inside the same Responses API loop that handles streaming, tool calling, MCP, file search, multi-turn conversations, and reasoning models. Text and reasoning content pass through the same moderation path regardless of which features the response uses.

For more details on the implementation, see the source in [`streaming.py`](https://github.com/ogx-ai/ogx/blob/main/src/ogx/providers/inline/responses/builtin/responses/streaming.py) and [`utils.py`](https://github.com/ogx-ai/ogx/blob/main/src/ogx/providers/inline/responses/builtin/responses/utils.py).

---

### Blog 2026 06 30 Codex Ogx Cli (`docs/blog/2026-06-30-codex-ogx-cli.md`)

---
slug: ogx-codex-cli
title: "Connect Codex CLI to Local and Hosted Models with OGX"
authors: [skamenan7]
tags: [ogx, codex, responses-api, vllm, ollama, agents]
date: 2026-06-30
---

Codex CLI brings an agent into the terminal, but teams often want that agent to use more than one model source. OGX gives Codex one OpenAI-compatible connection to local models, hosted models, and secured deployments.

With `ogx connect codex`, you can launch Codex against the models exposed by a running OGX server without hand-editing your normal Codex configuration. OGX discovers the available models, writes a temporary Codex session home, forwards auth and provider data when needed, and starts Codex with a session that points at OGX.

This post walks through the command, the generated Codex profile, and a local-first path with Ollama and vLLM. The result is a small but useful workflow: Codex gets a familiar Responses API endpoint, and teams keep model access, auth, and provider choice in OGX instead of hard-coding those details into every developer tool.



## Why this is useful

Launching Codex is easy. The harder part starts when you want the same tool to work across different model backends: a local Ollama model, a vLLM server, a hosted OpenAI model, or an internal deployment with its own auth rules. Each one has a different endpoint, model name, and credential story. With OGX, Codex points at one OpenAI-compatible endpoint while OGX smoothly takes care of the backend work: finding models, routing requests, forwarding auth, and adapting provider-specific details.

OGX gives those tools a common front door:

- Codex talks to an OpenAI-compatible `/v1/responses` API.
- OGX exposes the models already registered in the running server.
- The provider behind each model can change without rewriting the Codex workflow.
- Auth and provider data can be forwarded through OGX instead of stored in a long-lived local Codex config.
- The generated Codex session home is temporary, so your existing `~/.codex/config.toml` stays untouched.

That makes OGX a good fit for agentic development across laptops, shared dev servers, and production-like environments. It is not just a proxy. It is a control plane for model access, auth shape, provider routing, and day-to-day debugging.

Codex uses OGX through the Responses API, but the provider setup is useful beyond Codex. Once a model provider such as vLLM, Ollama, or OpenAI is registered in OGX, other OpenAI-compatible clients can use the same model access layer through chat completions or completions when those endpoints are enabled. That includes Python scripts using the OpenAI SDK, notebooks, OpenCode, LiteLLM or LangChain-style apps, and internal tools that already speak OpenAI-compatible APIs. Teams can configure routing and auth once in OGX, then re-use that setup from Codex and from simpler inference clients.

## What the command does

The command is intentionally small:

```bash
ogx connect codex
```

Behind that command, OGX does the mechanical work that is easy to get wrong by hand:

1. Queries `GET /v1/models` on the running OGX server.
2. Filters out embedding models.
3. Selects the requested model, or the first available LLM model.
4. Creates a temporary `CODEX_HOME`.
5. Writes `ogx.config.toml` and `ogx-model-catalog.json`.
6. Launches `codex -p ogx`, forwarding anything after `--` to the codex command (for example `exec <prompt>` for a non-interactive run).

The generated profile uses the Responses wire API:

```toml
model_provider = "ogx"

[features]
multi_agent = false

[model_providers.ogx]
wire_api = "responses"
```

The `multi_agent` flag is disabled because current OGX Responses models do not accept the Codex `namespace` tool shape. That keeps the default connector path focused on the request shape OGX can handle today.

The flow looks like this:

```text
Codex CLI
  |
  | generated OGX profile
  v
OGX /v1/responses
  |
  | provider routing
  v
OpenAI, vLLM, Ollama, Bedrock, or another OGX-backed model provider
```

The important part is the boundary: Codex only needs to know about the OGX profile. OGX owns the provider mapping.

## Try it with a running OGX server

Start an OGX server that exposes at least one LLM model. The starter distribution enables providers from environment variables, so you can begin with a local provider instead of an OpenAI key.

Start Ollama in one terminal:

```bash
ollama serve
```

Then pull a model and start OGX in another terminal:

```bash
ollama pull llama3.2:3b
export OLLAMA_URL="http://localhost:11434/v1"
uv run ogx run starter
```

If you do want to use an OpenAI-backed model instead, set `OPENAI_API_KEY` before starting the same starter distribution.

Then launch Codex in another terminal:

```bash
uv run ogx connect codex
```

If you want a specific model from the OGX model list:

```bash
uv run ogx connect codex \
  --model ollama/llama3.2:3b
```

For a quick non-interactive run, forward the codex `exec` subcommand after `--`:

```bash
uv run ogx connect codex \
  --model ollama/llama3.2:3b \
  -- exec "Explain in one sentence why OGX is useful with Codex CLI."
```

This is useful when you want a quick answer before opening an interactive Codex session. Codex sends the prompt through OGX, OGX routes it to the selected model, and the final answer comes back through the same Responses API path.

## Auth and provider data

The same setup works when OGX is running behind an authenticated endpoint. Codex still talks to one OGX URL, while OGX enforces the same access policy, provider routing, and credential handling that other clients use.

That matters in shared environments. A team can let Codex use approved models without putting long-lived provider secrets in `~/.codex/config.toml`, and without teaching Codex every backend-specific auth shape. If the OGX server requires bearer auth, set `OGX_API_KEY`. If a provider path needs request-scoped data, such as a passthrough provider token, set `OGX_PROVIDER_DATA`.

```bash
export OGX_API_KEY="your-ogx-access-token"
export OGX_PROVIDER_DATA='{"passthrough_api_key":"provider-token"}'

uv run ogx connect codex \
  --url https://ogx.example.com/v1
```

When `OGX_API_KEY` is set, Codex uses it to authenticate to OGX. When `OGX_PROVIDER_DATA` is set, OGX receives that JSON on each request and can use it for provider-specific needs such as passthrough credentials, tenant context, or other request-scoped routing data.

Codex does not need to know what the backend provider expects. It only points at OGX for the current session; OGX decides how that request is authorized and how provider-specific data is applied before the request reaches the model.

## Try it with a vLLM-backed OGX server

vLLM is useful when you want Codex to use an open model served from your own environment. It exposes an OpenAI-compatible server that OGX can register as `remote::vllm`, so the same Codex workflow can run against a vLLM-backed model instead of a hosted provider.

Start a vLLM OpenAI-compatible server:

```bash
export VLLM_API_TOKEN="fake"

vllm serve Qwen/Qwen3-8B \
  --api-key "$VLLM_API_TOKEN"
```

Then start OGX with the stock starter distribution pointed at that vLLM server in another terminal:

```bash
export VLLM_URL="http://localhost:8000/v1"
export VLLM_API_TOKEN="fake"

uv run ogx run starter
```

The starter distribution enables the vLLM provider when `VLLM_URL` is set. The relevant provider configuration is:

```yaml
providers:
  inference:
  - provider_id: ${env.VLLM_URL:+vllm}
    provider_type: remote::vllm
    config:
      base_url: ${env.VLLM_URL:=}
      max_tokens: ${env.VLLM_MAX_TOKENS:=4096}
      api_token: ${env.VLLM_API_TOKEN:=fake}
      network:
        tls:
          verify: ${env.VLLM_TLS_VERIFY:=true}
```

Now connect Codex through OGX:

```bash
uv run ogx connect codex \
  --model vllm/Qwen/Qwen3-8B \
  -- exec "Explain in one sentence how this Codex request is reaching the vLLM model."
```

That is the main point: Codex still uses the same OGX command, while OGX changes the provider behind the model ID. Ollama is a good first local path for basic text flows. vLLM is useful when you want an OpenAI-compatible server for open models. Provider and model compatibility still matter, but those details stay behind the OGX boundary instead of becoming permanent Codex configuration.

## Summary

`ogx connect codex` makes Codex feel like a first-class OGX client:

- It discovers models from the running OGX server.
- It generates a temporary Codex profile and model catalog.
- It keeps your normal Codex config untouched.
- It supports bearer auth and provider-data forwarding.
- It works for interactive Codex sessions and quick non-interactive runs.
- It works with local providers such as Ollama and vLLM as well as hosted providers.
- It keeps current alpha limits explicit, including no persistent Codex memory and disabled Codex multi-agent tools.

The practical takeaway: OGX gives teams one place to manage model access while still letting developer tools like Codex move fast. If you can start OGX and see your model in `/v1/models`, you have a clear path to using that model from Codex and debugging each layer with concrete evidence.

---

### Blog 2026 07 07 Python Sdk New Foundation (`docs/blog/2026-07-07-python-sdk-new-foundation.md`)

---
slug: python-sdk-new-foundation
title: "The OGX Python SDK Has a New Foundation"
authors: [aegeiger, ogx-team]
tags: [announcement, python, sdk, migration]
date: 2026-07-01
---

Starting with `ogx_client` 1.1.4, the Python SDK is built on a new code generation backend. The package name and API surface stay the same — most codebases need only an import path change.



## What changed

The OGX Python SDK was previously generated by [Stainless](https://www.stainless.com/), an external SaaS code generation service. Starting with version 1.1.4, the SDK is generated by [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) from the same OpenAPI spec that defines the OGX server.

The package is still `ogx_client`. You still `pip install ogx_client`. The client classes, API methods, and keyword arguments are the same. What changed is what's underneath — and that matters for the project's long-term health.

## Why we made the switch

Three things drove the decision (see the [original discussion](https://github.com/ogx-ai/ogx/issues/4609) for the full context):

**Sovereignty.** Relying on an external managed service to generate our SDK meant we couldn't ship fixes on our own schedule. We needed the pipeline in our hands. This became urgent when Anthropic acquired Stainless and discontinued the service — but the migration was already underway before that happened, motivated by the same concern.

**Local development.** With Stainless, generating an SDK required pushing code to GitHub and waiting for the external service to process it. Developers couldn't test SDK changes locally. With OpenAPI Generator, a developer can modify the API, regenerate the client, and run tests — all before opening a PR. API and client changes now ship together in a single commit.

**Multi-language coverage.** OGX targets Python, TypeScript, Java, and Go. OpenAPI Generator supports all of them with a single, adjustable template system. We maintain custom templates to preserve the SDK's look and feel, but the generation pipeline is unified across languages.

## What it means for you

For most codebases, migrating is a search-and-replace.

### What's different at a glance

- **Import paths**: `ogx_client.types` is now `ogx_client.models`, with a flat namespace (no more `types.shared`, `types.chat`, etc.)
- **Type names**: some types were renamed -- `OpenAI` prefix and `Object` suffix added to align with the OpenAPI spec
- **Pagination**: auto-paginating iterators are gone; list endpoints return one page at a time
- **Removed client features**: `client.copy()`, `client.with_raw_response`, `client.with_streaming_response`, and `file_from_path` are no longer available
- **Exception attributes**: `e.status_code` is now `e.status`; `e.response` is no longer available (use `e.headers`, `e.body` directly)
- **Python 3.12+** and **Pydantic 2.x** are now required

The main change is the import path for types:

```python
# Before (<= 1.1.3)
from ogx_client.types import ResponseObject

# After (>= 1.1.4)
from ogx_client.models import OpenAIResponseObject
```

Some type names also changed — resource types gained an `OpenAI` prefix or `Object` suffix to align with the OpenAPI spec naming. The actual fields on these types are identical.

### Quick checklist

- Upgrade Python to 3.12+ and Pydantic to 2.x (if not already)
- Upgrade `ogx_client` to >= 1.1.4
- Replace `from ogx_client.types` with `from ogx_client.models` in all imports
- Update type names per the mapping tables in the migration guide

### Full migration guide

For the complete reference — including all type name mappings, pagination changes, removed client features, and exception attribute differences — see [Migrating to ogx_client 1.1.4: The Complete Reference](/docs/references/python_sdk_reference/migration).

---

### Blog 2026 07 14 Multi Tenant Capabilities (`docs/blog/2026-07-14-multi-tenant-capabilities.md`)

---
slug: ogx-multi-tenant-capabilities
title: "Multi-Tenant AI Infrastructure with OGX: Tenant Isolation, ABAC, and Defense in Depth"
authors: [leseb]
tags: [ogx, multi-tenancy, access-control, security, enterprise]
date: 2026-07-14
---

Most AI gateway projects solve for single-user or single-team setups. Point your SDK at the server, get completions back. That works until your platform team needs to serve multiple tenants from the same OGX instance without them seeing each other's models, vector stores, conversations, or RAG data.

OGX ships two independent isolation layers: a hard **tenant partition key** enforced at the storage layer, and **Attribute-Based Access Control (ABAC)** for fine-grained permissions within a tenant. This post covers how they work, how to configure them, and how they compose.



## The problem: shared infrastructure, isolated data

When multiple teams or customers share an OGX deployment, two things need to be true:

1. **Tenant A cannot see Tenant B's data** — conversations, responses, files, vector store contents. Period. No policy misconfiguration should be able to override this.
2. **Within a tenant, users should only see what they are authorized to see** — Alice's conversations are not Bob's, even if they share a tenant.

These are different problems. The first is a hard isolation boundary. The second is access control. OGX addresses them with separate mechanisms so that a bug or misconfiguration in one does not compromise the other.

## Tenant isolation: the hard partition

The primary isolation boundary in OGX is `tenant_id` — a non-bypassable partition key applied to every row in the storage layer. When tenancy is enabled, the `AuthorizedSqlStore` automatically:

- Adds a `tenant_id` column to every table.
- Stamps every write with the authenticated user's `tenant_id`.
- Applies `WHERE tenant_id = ?` to every read and mutation — before ABAC policy evaluation, before any application logic.
- In `multi` mode, if a request has no `tenant_id`, the query resolves to `WHERE 1=0` — default deny, see nothing.

This is not a policy rule. There is no ABAC condition that can override it. Tenant isolation operates below the access control layer.

### Tenancy modes

OGX supports three deployment modes:

| Mode | Behavior |
|------|----------|
| `disabled` (default) | No tenant column, no filtering. Single-user or single-team setups. |
| `single` | All records are stamped with a configured `default_tenant_id`. Useful for dedicated single-tenant deployments that want a migration path to `multi`. |
| `multi` | Every request must resolve a `tenant_id` from authentication. Requests without a tenant are rejected (401). Records are fully partitioned. |

### Tenant resolution from auth providers

Each authentication provider resolves `tenant_id` from its own source:

| Provider | Config field | Source |
|----------|-------------|--------|
| `oauth2_token` | `tenant_claim` | JWT claim (e.g., `tenant`, `org`, `tid`) |
| `kubernetes` | `tenant_claim` | Kubernetes user claim (resolved via `claims_mapping` path) |
| `custom` | `tenant_field` | Field in the auth endpoint JSON response |
| `upstream_header` | `tenant_header` | HTTP header set by the upstream gateway |

Tenant IDs are validated and normalized: lowercase, alphanumeric with hyphens and underscores, max 128 characters.

### Example: single-tenant deployment

A dedicated deployment where all data belongs to one tenant. No auth required — useful for development or single-customer deployments:

```yaml
server:
  port: 8321
  tenancy:
    mode: "single"
    default_tenant_id: "acme-corp"
```

All records are automatically stamped with `tenant_id: "acme-corp"`. This creates a clean migration path — when you later move to `multi` mode, existing data is already tagged.

### Example: multi-tenant with OAuth2/OIDC

Extract the tenant from a JWT claim:

```yaml
server:
  port: 8321
  tenancy:
    mode: "multi"
  auth:
    provider_config:
      type: oauth2_token
      tenant_claim: "tenant"
      jwks:
        uri: https://auth.example.com/.well-known/jwks.json
      issuer: https://auth.example.com
      audience: ogx
```

A decoded token with `{"sub": "alice", "tenant": "acme-corp", ...}` resolves `tenant_id: "acme-corp"`. Any claim name works — set `tenant_claim` to match your IdP's token structure.

### Example: multi-tenant with upstream gateway

The most common production pattern. An upstream gateway (Authorino, Istio, or a reverse proxy) handles authentication and injects identity headers:

```yaml
server:
  port: 8321
  tenancy:
    mode: "multi"
  auth:
    provider_config:
      type: upstream_header
      principal_header: "x-auth-user-id"
      tenant_header: "x-tenant-id"
      attributes_header: "x-auth-attributes"
```

The gateway sets `x-tenant-id` on every request. If the header is missing, OGX rejects with a 401.

## Authentication: bring your identity provider

OGX does not invent its own auth system. It integrates with what you already run:

- **OAuth2/OIDC (JWT)**: Validates tokens via JWKS or RFC 7662 introspection. Maps claims to tenant identity and access attributes. Works with Keycloak, Auth0, Okta, or any OIDC provider.
- **Kubernetes**: Validates service account tokens against the cluster API server. Extracts username, groups, and tenant from Kubernetes user info.
- **GitHub**: Validates personal access tokens or OAuth tokens directly against the GitHub API. Pulls login, user ID, and org memberships.
- **Custom endpoint**: POST your bearer token to any HTTP endpoint. The endpoint returns a principal, attributes, and optionally a tenant ID.
- **Upstream headers**: Trust headers injected by a gateway (Authorino, Istio, Envoy). No outbound validation calls.

The key output of authentication is a **User** object with a principal (identity), an optional `tenant_id`, and **access attributes** across four categories: `roles`, `teams`, `projects`, and `namespaces`. The `tenant_id` drives partition isolation. The attributes drive ABAC policy evaluation within that partition.

## Attribute-Based Access Control

ABAC governs what individual users can do **within their tenant**. It is the second isolation layer — it operates on the data that tenant isolation has already scoped.

OGX implements ABAC with a policy language inspired by [Cedar](https://www.cedarpolicy.com/). Policies are ordered lists of rules. The first matching rule wins.

Each rule has:

- A **scope**: `permit` or `forbid`, with the actions it covers (`create`, `read`, `update`, `delete`).
- A **resource pattern**: exact match (`model::llama-3`), wildcard (`vector_store::*`), or regex.
- A **condition**: natural-language-style predicates evaluated against the user and resource.

### Supported conditions

| Condition | Meaning |
|-----------|---------|
| `user is owner` | The authenticated user created the resource |
| `user is not owner` | Someone else created the resource |
| `user in owners teams` | User shares at least one team with the resource creator |
| `user not in owners teams` | User shares no teams with the resource creator |
| `user with admin in roles` | User has the value `admin` in their `roles` attribute |
| `user with admin not in roles` | User does not have `admin` in `roles` |
| `resource is unowned` | The resource has no owner (public) |

Conditions compose with `when` (permit if condition holds) and `unless` (permit unless condition holds).

Owner-based conditions (`user is owner`, `user in owners teams`, etc.) automatically deny cross-tenant access even if attribute values happen to match. Two users with `roles: ["admin"]` in different tenants cannot see each other's resources through an `admin`-based policy.

### Example: owner-only records within a tenant

```yaml
server:
  auth:
    access_policy:
      - permit:
          actions: [read]
          resource: "model::*"
        when: "resource is unowned"
        description: "all authenticated users can use globally registered models"
      - permit:
          actions: [create]
          resource: "sql_record::*"
        description: "any authenticated user can create records"
      - permit:
          actions: [read, update, delete]
          resource: "sql_record::*"
        when: "user is owner"
        description: "users can only access records they created"
```

With tenant isolation handling the cross-tenant boundary, ABAC focuses on within-tenant sharing. The `create` rule is unconditional because the ABAC check runs before ownership is assigned.

### Default policy

If you configure authentication but do not specify a custom `access_policy`, OGX applies a sensible default: users can access their own resources and resources created by users who share at least one attribute value in any category. This means team members naturally see each other's work without explicit rules.

## Route-level access control

Before resource-level ABAC evaluates, OGX supports **route policies** that control which API endpoints a user can reach at all:

```yaml
server:
  auth:
    route_policy:
      - permit:
          paths: "/v1/chat/completions"
        when: "user with developer in roles"
        description: "developers can access chat completions"
      - permit:
          paths: "/v1/files*"
        when: "user with data_engineer in roles"
        description: "data engineers can manage files"
```

Route patterns support exact paths, prefix wildcards (`/v1/files*`), and regex. This gives platform teams infrastructure-level gatekeeping before any resource checks run.

## Vector search isolation

Two tenants might store documents about the same topic. A naive vector search returns the most similar chunks regardless of who owns them. Tenant A asks "What is our revenue forecast?" and gets Tenant B's financials.

OGX addresses this at multiple levels:

### Tenant-partitioned storage

With tenancy enabled, vector store data is partitioned by `tenant_id` at the storage layer — the same `WHERE tenant_id = ?` filter that protects conversations and responses also applies to vector store queries. Tenants cannot see each other's chunks regardless of semantic similarity.

### ABAC on vector store resources

Vector store resources are subject to the same ABAC policies as every other resource. The routing table enforces access before any search runs.

### Per-tenant vector store indexes

For physical isolation, create separate vector stores per tenant. Each tenant's data lives in its own index, scoped by both tenant partition and ownership.

## Fair scheduling across tenants

When multiple tenants share an inference backend, one tenant's burst of requests should not starve the others. OGX's vLLM provider supports this natively: the `fairness_header_attribute` config option maps an authenticated user's ABAC attribute (e.g., `namespaces` or `teams`) to the `x-gateway-inference-fairness-id` header on outgoing requests. vLLM uses this header to schedule requests fairly across tenants.

Because the fairness identifier comes from the auth-resolved user attributes — not from client-supplied headers — tenants cannot spoof their identity to game scheduling priority.

## Putting it together: a complete multi-tenant configuration

```yaml
server:
  port: 8321
  tenancy:
    mode: "multi"
  auth:
    provider_config:
      type: oauth2_token
      tenant_claim: "tenant"
      issuer: https://auth.example.com
      audience: ogx
      jwks:
        uri: https://auth.example.com/.well-known/jwks.json
      claims_mapping:
        groups: teams
        resource_access.ogx.roles: roles

    access_policy:
      - permit:
          actions: [read]
          resource: "model::*"
        when: "resource is unowned"
        description: "all authenticated users can use globally listed models"
      - permit:
          actions: [create]
          resource: "sql_record::*"
        description: "any authenticated user can create records"
      - permit:
          actions: [read, update, delete]
          resource: "sql_record::*"
        when: "user is owner"
        description: "users can only access their own records"

    route_policy:
      - permit:
          paths: "/v1/chat/completions"
        description: "all authenticated users can use chat"
      - permit:
          paths: "/v1/responses*"
        description: "all authenticated users can use responses"
      - permit:
          paths: "/v1/vector_stores*"
        when: "user with data_admin in roles"
        description: "only data admins manage vector stores"
```

From the application side, nothing changes. Clients still use the OpenAI SDK:

```python
from openai import OpenAI

client = OpenAI(base_url="http://ogx.internal:8321/v1", api_key="<tenant-jwt-token>")

response = client.chat.completions.create(
    model="llama-3-70b",
    messages=[{"role": "user", "content": "Summarize Q2 results"}],
)
```

The JWT carries the tenant identity. OGX validates it, extracts the `tenant_id` and attributes, and enforces isolation at every layer.

## Defense in depth

OGX's multi-tenant security is not a single gate. It is independent layers that each enforce without relying on the others:

1. **Tenant partition**: `WHERE tenant_id = ?` on every query. Non-bypassable. No policy rule can override it.
2. **Route-level**: Can this user reach this API endpoint at all?
3. **Resource-level**: Can this user access this specific model, vector store, or tool group?
4. **Record-level**: Can this user see this specific conversation or response within their tenant?

A misconfigured ABAC policy cannot leak data across tenants. A missing route policy cannot expose another tenant's records. The layers are independent.

## What this means for platform teams

If you are building a shared AI platform, OGX gives you:

- **One deployment, many tenants**: No need to run separate OGX instances per team or customer.
- **Hard isolation by default**: `tenant_id` partitioning is enforced at the storage layer, independent of access policies.
- **Standard identity integration**: Plug in your existing OIDC provider, Kubernetes auth, or service mesh. Tenant resolution is built into every auth provider.
- **Declarative policies**: Define within-tenant access rules in YAML, not application code.
- **No application changes**: Tenants use standard OpenAI-compatible clients. Isolation is infrastructure-level.
- **Migration path**: Start with `single` mode, move to `multi` when ready. Existing data is already tagged.

Multi-tenancy is not an add-on. It is built into OGX's storage engine, routing tables, and API middleware. For teams moving from single-tenant prototypes to shared production infrastructure, the path is configuration, not code.

---

To get started, check the [multi-tenancy configuration docs](../docs/distributions/configuration) and [PR #6126](https://github.com/ogx-ai/ogx/pull/6126) for the implementation details.

---

### Blog Authors.Yml (`docs/blog/authors.yml`)

ogx-team:
  name: OGX Team
  title: Core Team
  url: https://github.com/ogx-ai
  image_url: /img/ogx-logo.png

leseb:
  name: Sébastien Han
  title: OGX Core Team
  url: https://github.com/leseb
  image_url: https://github.com/leseb.png

raghotham:
  name: Raghotham Murthy
  title: OGX Core Team
  url: https://github.com/raghotham
  image_url: https://github.com/raghotham.png

jwm4:
  name: Bill Murdock
  url: https://github.com/jwm4
  image_url: https://github.com/jwm4.png

franciscojavierarceo:
  name: Francisco Javier Arceo
  title: OGX Core Team
  url: https://github.com/franciscojavierarceo
  image_url: https://github.com/franciscojavierarceo.png

cdoern:
  name: Charlie Doern
  title: OGX Core Team
  url: https://github.com/cdoern
  image_url: https://github.com/cdoern.png

nathan-weinberg:
  name: Nathan Weinberg
  url: https://github.com/nathan-weinberg
  image_url: https://github.com/nathan-weinberg.png

gyliu513:
  name: Guangya Liu
  url: https://github.com/gyliu513
  image_url: https://github.com/gyliu513.png

skamenan7:
  name: Sumanth Kamenani
  url: https://github.com/skamenan7
  image_url: https://github.com/skamenan7.png

aegeiger:
  name: E Geiger
  url: https://github.com/aegeiger
  image_url: https://github.com/aegeiger.png

---

### Releases GENERATE (`docs/releases/GENERATE.md`)

# Release Notes Generation with Claude Code

This document contains a self-contained prompt for generating release notes using [Claude Code](https://docs.anthropic.com/en/docs/claude-code). It produces two artifacts:

1. **Detailed release notes** in `docs/releases/RELEASE_NOTES_{VERSION}.md`
2. **Summary section** prepended to the top-level `RELEASE_NOTES.md`
3. **Pull request** with the changes

## Usage

Run from the repository root, providing the version range as a prefix:

```bash
(echo "OLD_VERSION=0.4.0 NEW_VERSION=0.5.0" && cat docs/releases/GENERATE.md) | claude -p -
```

Claude will resolve `{OLD_VERSION}` and `{NEW_VERSION}` throughout the prompt from these definitions.

## Prompt

Create release notes between version {OLD_VERSION} and {NEW_VERSION} for this project.

### Step 1: Analyze Changes

1. Find git tags for {OLD_VERSION} and {NEW_VERSION} (or HEAD if not yet tagged)
2. Get ALL commits between these versions
3. For commits marked with `!` in conventional commits (e.g., `feat!:`, `fix!:`), examine the actual diffs
4. Also check unmarked commits for breaking changes by reviewing the code changes themselves. Do your due diligence: look for non-compatible API schema changes, changes of default values, removed features, renamed config fields, changed method signatures, etc.

### Step 2: Classify Breaking Changes

Separate breaking changes into THREE categories:

**Hard Breaking Changes** (action required before upgrading):
Changes where the user HAS to update something or their code/config will fail. Only include truly hard breaks here, not things that are backwards compatible.

**Deprecated** (works with warnings, migrate before next major release):
Changes that include a backward compatibility layer with deprecation warnings.

**Behavior Changes** (no code changes required, but be aware):
Changes to default values or response formats where existing code still works but behaves differently.

### Step 3: Write Detailed Release Notes

Write the detailed release notes to `docs/releases/RELEASE_NOTES_{NEW_VERSION}.md` using this structure:

1. **Title**: `# OGX {NEW_VERSION} Release Notes`
2. **Release Date**: Use the date from the GitHub release tag, or today if not yet released
3. **One-paragraph summary** of the release highlights
4. **Breaking Changes** section with:
   - Summary tables for each category (Hard Breaking, Deprecated, Behavior Changes)
   - Each table has columns: Change | Migration/Note | PR link
   - A disclaimer that breaking changes are discussed in detail below
   - Detailed subsections for each breaking change with:
     - PR link and contributor full name with company (fetch from GitHub if needed)
     - Impact description (who is affected)
     - Before/After code examples where applicable
     - Migration instructions
5. **New Features** with subsections for major features, grouped logically
6. **New Providers** if any
7. **API/Architecture Changes** (e.g., migration patterns)
8. **Backward Compatibility Improvements**
9. **Bug Fixes** (one-liner list with PR links and contributor names)
10. **Documentation** updates
11. **Upgrade Guide** with:
    - "Before Upgrading" section for hard breaking changes (step-by-step with grep commands to find affected code)
    - "After Upgrading" section for deprecations

Formatting rules for the detailed notes:

- All PR references use a linked `#NNNN` pull request number.
- For each change, fetch the PR author's full name from GitHub. Include company affiliation in parentheses.
- Do NOT put author names in the summary overview tables, only in the detailed sections.
- Use code blocks with language hints for before/after examples.

### Step 4: Update Top-Level RELEASE_NOTES.md

Prepend a summary section to `RELEASE_NOTES.md`, inserting it directly below the HTML comment marker (`<!-- New releases go here ...`). Use this structure:

```markdown
## [{NEW_VERSION}](docs/releases/RELEASE_NOTES_{NEW_VERSION}.md) - {RELEASE_DATE}

{One-paragraph summary of the release.}

### Highlights

- **Feature 1** short description ([#NNNN](link))
- **Feature 2** short description ([#NNNN](link))
- ...

### Breaking Changes

| Change | Type | PR |
|--------|------|-----|
| Short description of change | Hard/Deprecated | [#NNNN](link) |
| ... | ... | ... |

See the [full release notes](docs/releases/RELEASE_NOTES_{NEW_VERSION}.md) for migration instructions and detailed upgrade guide.
```

Guidelines for the summary:

- Use ISO date format (`YYYY-MM-DD`) from the GitHub release
- List 5-10 of the most notable features in Highlights (not exhaustive)
- The Breaking Changes table lists all breaking and deprecated changes with their type (`Hard` or `Deprecated`), but without migration details
- Always prepend new releases (newest at the top)

### Step 5: Create Pull Request

1. Create a new branch `docs/release-notes-{NEW_VERSION}`
2. Commit both files with message: `docs: add release notes for version {NEW_VERSION}`
3. Push and create a PR against `main` with:
   - Title: `docs: add release notes for version {NEW_VERSION}`
   - Body summarizing what's included (number of breaking changes, features, bug fixes, etc.)

---

### Releases RELEASE NOTES 0.5 (`docs/releases/RELEASE_NOTES_0.5.md`)

# OGX 0.5 Release Notes

**Release Date:** February 2026

Release 0.5 brings significant improvements to API consistency, OpenAI conformance, provider capabilities, and a major architectural refactoring of all APIs to use FastAPI routers. This release also introduces the Connectors API for MCP server management and comprehensive network configuration for remote inference providers.

## Breaking Changes

### Summary

> **Note:** Each change is described in detail with migration instructions in the sections below.

**Hard Breaking Changes (action required before upgrading):**

| Change | Migration | PR |
|--------|-----------|-----|
| Post-Training API endpoints restructured | Update URLs: `/post-training/job/status?job_uuid=X` → `/post-training/jobs/{job_uuid}/status` | [#4606](https://github.com/ogx-ai/ogx/pull/4606) |
| Embeddings API rejects explicit `null` | Remove `dimensions: null` and `user: null` from requests (omit fields instead) | [#4644](https://github.com/ogx-ai/ogx/pull/4644) |
| Safety API provider interface changed | Update provider method signatures to accept `RunShieldRequest` object | [#4643](https://github.com/ogx-ai/ogx/pull/4643) |
| Meta-Reference GPU provider removed | Switch to `remote::vllm` or `remote::ollama` | [#4828](https://github.com/ogx-ai/ogx/pull/4828) |
| Scope-based endpoint authorization removed | Migrate to new YAML-based endpoint authorization | [#4734](https://github.com/ogx-ai/ogx/pull/4734) |

**Deprecated (works with warnings, migrate before next major release):**

| Change | Migration | PR |
|--------|-----------|-----|
| `image_name` → `distro_name` | Replace `image_name:` with `distro_name:` in config files | [#4396](https://github.com/ogx-ai/ogx/pull/4396) |
| Eval API calling convention | Use `RunEvalRequest` objects instead of keyword arguments | [#4425](https://github.com/ogx-ai/ogx/pull/4425) |
| vLLM `tls_verify` field | Move to `network.tls.verify` in provider config | [#4748](https://github.com/ogx-ai/ogx/pull/4748) |

**Behavior Changes (no code changes required, but be aware):**

| Change | Note | PR |
|--------|------|-----|
| `finish_reason` values now OpenAI-conformant | Check if code handles: `stop`, `length`, `tool_calls`, `content_filter` | [#4679](https://github.com/ogx-ai/ogx/pull/4679) |
| Vertex AI defaults to "global" region | Set explicit `region` in config if needed | [#4674](https://github.com/ogx-ai/ogx/pull/4674) |
| Usage token details now always present | No action needed (additive change) | [#4690](https://github.com/ogx-ai/ogx/pull/4690) |

---

### Hard Breaking Changes

These changes take effect immediately and require updates before upgrading.

#### 1. Post-Training API Endpoints Restructured ([#4606](https://github.com/ogx-ai/ogx/pull/4606))

*Contributed by Eoin Fennessy (Red Hat)*

**Impact:** API clients using post-training job endpoints

Post-training job endpoints now use path parameters instead of query parameters for `job_uuid`, following REST best practices:

| Before | After |
|--------|-------|
| `POST /post-training/job/cancel?job_uuid=X` | `POST /post-training/jobs/{job_uuid}/cancel` |
| `GET /post-training/job/status?job_uuid=X` | `GET /post-training/jobs/{job_uuid}/status` |
| `GET /post-training/job/artifacts?job_uuid=X` | `GET /post-training/jobs/{job_uuid}/artifacts` |

**Migration:** Update API calls to use the new URL paths with job UUID in the path.

---

#### 2. Embeddings API Changes for OpenAI Conformance ([#4644](https://github.com/ogx-ai/ogx/pull/4644))

*Contributed by Eoin Fennessy (Red Hat)*

**Impact:** API clients using `/embeddings` endpoint

Several changes to achieve full OpenAI API conformance:

- **`dimensions` and `user` fields now reject explicit `null`**: Previously accepted `dimensions: null`, now returns validation error
- **`encoding_format` is now an enum**: Only `"float"` or `"base64"` allowed

**Before (accepted):**

```python
request = {"model": "test", "input": "hello", "dimensions": None}
```

**After (ValidationError):**

```python
# Must omit the field entirely, not set to null
request = {"model": "test", "input": "hello"}
```

---

#### 3. Safety API Provider Interface Changes ([#4643](https://github.com/ogx-ai/ogx/pull/4643))

*Contributed by Roy Belio (Red Hat)*

**Impact:** Custom safety provider implementations

The Safety API has been migrated to FastAPI routers. Safety providers now receive request objects instead of individual parameters:

**Before:**

```python
async def run_shield(
    self, shield_id: str, messages: list, params: dict
) -> RunShieldResponse: ...
```

**After:**

```python
async def run_shield(self, request: RunShieldRequest) -> RunShieldResponse: ...
```

The `params` field has been removed from `RunShieldRequest` as it was unused.

---

#### 4. Meta-Reference GPU Inference Provider Removed ([#4828](https://github.com/ogx-ai/ogx/pull/4828))

*Contributed by Matthew Farrellee*

**Impact:** Users of the `inline::meta-reference` inference provider

The inline meta-reference GPU inference implementation has been removed. Use `vllm`, `ollama`, or other maintained providers instead.

**Migration:** Switch to `remote::vllm`, `remote::ollama`, or another supported inference provider.

---

#### 5. Scope-Based Endpoint Authorization Removed ([#4734](https://github.com/ogx-ai/ogx/pull/4734))

*Contributed by Derek Higgins (Red Hat)*

**Impact:** Users who configured `required_scope` in custom endpoints

The scope-based authorization feature has been removed. Use the new endpoint authorization with YAML config ([#4448](https://github.com/ogx-ai/ogx/pull/4448)) instead.

---

### Deprecated (With Migration Period)

These changes include backward compatibility. The old behavior continues to work but emits deprecation warnings. Plan to migrate before the next major release.

#### 1. Configuration: `image_name` Renamed to `distro_name` ([#4396](https://github.com/ogx-ai/ogx/pull/4396))

*Contributed by Charlie Doern (Red Hat)*

**Impact:** All existing configuration files (`run.yaml`, `config.yaml`)

The `image_name` field in `StackConfig` has been renamed to `distro_name` to better reflect its purpose.

**Before:**

```yaml
version: 2
image_name: my-stack
```

**After:**

```yaml
version: 2
distro_name: my-stack
```

**Status:** Old `image_name` continues to work and is automatically migrated with a deprecation warning.

---

#### 2. Eval API Provider Interface Changes ([#4425](https://github.com/ogx-ai/ogx/pull/4425), [#4683](https://github.com/ogx-ai/ogx/pull/4683))

*Contributed by Roy Belio (Red Hat), Sai Chandra Pandraju (Red Hat)*

**Impact:** Custom eval provider implementations, direct Eval API callers

The Eval API now uses request objects. Old-style parameter calling is deprecated but supported:

**New style (preferred):**

```python
await eval.run_eval(RunEvalRequest(benchmark_id="...", benchmark_config=...))
```

**Old style (deprecated):**

```python
await eval.run_eval(
    benchmark_id="...", benchmark_config=...
)  # emits DeprecationWarning
```

**Status:** Old calling convention works but emits `DeprecationWarning`. Backward compatibility layer added in [#4683](https://github.com/ogx-ai/ogx/pull/4683).

---

#### 3. vLLM `tls_verify` Configuration Deprecated ([#4748](https://github.com/ogx-ai/ogx/pull/4748))

*Contributed by Sébastien Han (Red Hat)*

**Impact:** vLLM provider users with TLS configuration

The `tls_verify` field is deprecated in favor of the new `network.tls.verify` configuration:

**Before:**

```yaml
providers:
  inference:
    - provider_type: remote::vllm
      config:
        url: https://vllm-server
        tls_verify: /path/to/ca.crt
```

**After:**

```yaml
providers:
  inference:
    - provider_type: remote::vllm
      config:
        url: https://vllm-server
        network:
          tls:
            verify: /path/to/ca.crt
```

**Status:** Old `tls_verify` is automatically migrated with a deprecation warning.

---

### Behavior Changes

These are changes to default values or response formats. Existing code should continue to work, but behavior may differ.

#### 1. `finish_reason` Values Changed for OpenAI Conformance ([#4679](https://github.com/ogx-ai/ogx/pull/4679))

*Contributed by Sébastien Han (Red Hat)*

The `finish_reason` field in inference responses now conforms to the OpenAI specification. If your code explicitly checks for specific `finish_reason` values, verify it handles the standard values: `stop`, `length`, `tool_calls`, `content_filter`, `function_call`.

#### 2. Vertex AI Default Region Changed ([#4674](https://github.com/ogx-ai/ogx/pull/4674))

*Contributed by Ken Dreyer (Red Hat)*

The Vertex AI provider now defaults to the "global" OpenAI API endpoint instead of a specific GCP region. If you relied on the previous default region, explicitly configure it in your provider settings.

#### 3. Usage Token Details Now Always Present ([#4690](https://github.com/ogx-ai/ogx/pull/4690))

*Contributed by Matthew Farrellee*

The `input_tokens_details` and `output_tokens_details` fields in the `Usage` object are now always present (previously optional). This is backwards compatible for consumers.

---

## New Features

### Connectors API ([#4263](https://github.com/ogx-ai/ogx/pull/4263), [#4402](https://github.com/ogx-ai/ogx/pull/4402), [#4760](https://github.com/ogx-ai/ogx/pull/4760))

*Contributed by Jaideep Rao (Red Hat)*

New API for managing MCP (Model Context Protocol) server connections via static configuration:

```yaml
connectors:
  - connector_id: kubernetes
    url: "http://localhost:8080/mcp"
    connector_type: mcp
```

API endpoints:

- `GET /v1alpha/connectors` - List all connectors
- `GET /v1alpha/connectors/{connector_id}` - Get connector details
- `GET /v1alpha/connectors/{connector_id}/tools/{tool_name}` - Get tool info

### Comprehensive Network Configuration ([#4748](https://github.com/ogx-ai/ogx/pull/4748))

*Contributed by Sébastien Han (Red Hat)*

All remote inference providers now support unified network configuration for TLS (including mTLS), proxy servers, timeouts, and custom headers:

```yaml
providers:
  inference:
    - provider_type: remote::openai
      config:
        network:
          tls:
            verify: true
            ca_cert: /path/to/ca.crt
            client_cert: /path/to/client.crt
            client_key: /path/to/client.key
          proxy:
            url: http://proxy:8080
          timeout:
            connect: 10.0
            read: 60.0
          headers:
            X-Custom-Header: value
```

### Endpoint Authorization with YAML Config ([#4448](https://github.com/ogx-ai/ogx/pull/4448))

*Contributed by Derek Higgins (Red Hat)*

Infrastructure-level access control for API endpoints:

```yaml
server:
  auth:
    endpoint_policy:
      - path: "/v1/files*"
        conditions:
          - role: admin
      - path: "/v1/health"
        allow: true
```

### Rerankers Support ([#4456](https://github.com/ogx-ai/ogx/pull/4456))

*Contributed by Varsha (Red Hat)*

Vector stores now support reranking for hybrid search:

```python
results = await client.vector_stores.search(
    vector_store_id="vs_123",
    query="search query",
    search_type="hybrid",
    reranker_type="reciprocal_rank_fusion",
    reranker_params={"k": 60},
)
```

### Response API Enhancements

- **`reasoning.effort` parameter** ([#4633](https://github.com/ogx-ai/ogx/pull/4633)) - *Nehanth Narendrula*: Control reasoning token usage

  ```python
  response = client.responses.create(
      model="openai/gpt-5",
      reasoning={"effort": "high"},
      input=[{"role": "user", "content": "Complex problem..."}],
  )
  ```

- **`max_output_tokens`** ([#4592](https://github.com/ogx-ai/ogx/pull/4592)) - *Guangya Liu*: Limit response length

- **`parallel_tool_calls`** ([#4608](https://github.com/ogx-ai/ogx/pull/4608)) - *Shabana Baig (Red Hat)*: Enable parallel tool execution

- **`safety_identifier`** ([#4793](https://github.com/ogx-ai/ogx/pull/4793)) - *Guangya Liu*: Custom safety monitoring tracking

### New Providers

- **Elasticsearch Vector IO** ([#4007](https://github.com/ogx-ai/ogx/pull/4007)) - *Enrico Zimuel (Elastic)*: Use Elasticsearch as a vector store backend
- **OCI 26ai Vector Support** ([#4411](https://github.com/ogx-ai/ogx/pull/4411)) - *Robert Riley (Oracle)*: Oracle Cloud Infrastructure 26ai as vector store

### PGVector Improvements

*All PGVector improvements contributed by Ian Miller (Red Hat)*

- **HNSW indexes** ([#4696](https://github.com/ogx-ai/ogx/pull/4696)): Better vector search performance
- **IVFFlat indexes** ([#4772](https://github.com/ogx-ai/ogx/pull/4772)): Alternative indexing strategy
- **Configurable distance metrics** ([#4714](https://github.com/ogx-ai/ogx/pull/4714)): cosine, euclidean, inner_product
- **Embedding dimension validation** ([#4732](https://github.com/ogx-ai/ogx/pull/4732))
- **Automatic vector extension creation** ([#4660](https://github.com/ogx-ai/ogx/pull/4660))

### Library Client Improvements

- **Shutdown functionality** ([#4642](https://github.com/ogx-ai/ogx/pull/4642)) - *Sergey Yedrikov (Red Hat)*: Proper cleanup for `OGXAsLibraryClient` and `AsyncOGXAsLibraryClient`

  ```python
  async with AsyncOGXAsLibraryClient(config_path) as client:
      # Use client
      ...
  # Automatic cleanup on exit
  ```

### Safety API Improvements

- **`run_moderation` for all providers** ([#4662](https://github.com/ogx-ai/ogx/pull/4662)) - *Mac Misiura (Red Hat)*: OpenAI-compatible moderation API support across NVIDIA, Bedrock, SambaNova, and PromptGuard providers

### ARM64 Support

- **ARM64-based UBI starter image** ([#4474](https://github.com/ogx-ai/ogx/pull/4474)) - *Doug Edgar (Red Hat)*: Container images now available for ARM64 architecture

## API Migration to FastAPI Routers

All APIs have been migrated from the legacy `@webmethod` decorator pattern to FastAPI routers:

- Inference API ([#4755](https://github.com/ogx-ai/ogx/pull/4755)) - *Roy Belio (Red Hat)*
- Agents/Responses API ([#4376](https://github.com/ogx-ai/ogx/pull/4376)) - *Sumanth Kamenani*
- Safety API ([#4643](https://github.com/ogx-ai/ogx/pull/4643)) - *Roy Belio (Red Hat)*
- Eval API ([#4425](https://github.com/ogx-ai/ogx/pull/4425)) - *Roy Belio (Red Hat)*
- Vector IO API ([#4595](https://github.com/ogx-ai/ogx/pull/4595)) - *Sumanth Kamenani*
- Conversations API ([#4342](https://github.com/ogx-ai/ogx/pull/4342)) - *Sébastien Han (Red Hat)*
- Models API ([#4407](https://github.com/ogx-ai/ogx/pull/4407)) - *Nathan Weinberg (Red Hat)*
- Shields API ([#4412](https://github.com/ogx-ai/ogx/pull/4412)) - *Nathan Weinberg (Red Hat)*
- DatasetIO API ([#4400](https://github.com/ogx-ai/ogx/pull/4400)) - *Nathan Weinberg (Red Hat)*
- Prompts API ([#4649](https://github.com/ogx-ai/ogx/pull/4649)) - *Nathan Weinberg (Red Hat)*
- Scoring API ([#4521](https://github.com/ogx-ai/ogx/pull/4521)) - *Guangya Liu*
- Scoring Functions API ([#4599](https://github.com/ogx-ai/ogx/pull/4599)) - *Eleanor (Red Hat)*
- Post-Training API ([#4496](https://github.com/ogx-ai/ogx/pull/4496)) - *Eoin Fennessy (Red Hat)*
- Connectors API ([#4402](https://github.com/ogx-ai/ogx/pull/4402)) - *Jaideep Rao (Red Hat)*

This provides better OpenAPI documentation, improved request validation, and consistent error handling.

## Backward Compatibility Improvements

Several providers have been updated to handle legacy data formats:

- **FAISS** ([#4463](https://github.com/ogx-ai/ogx/pull/4463)) - *Sébastien Han (Red Hat)*: Handles legacy `EmbeddedChunk` format
- **PGVector** ([#4506](https://github.com/ogx-ai/ogx/pull/4506)) - *Ignas Baranauskas (Red Hat)*: Handles legacy chunk format
- **Qdrant** ([#4495](https://github.com/ogx-ai/ogx/pull/4495)) - *Ignas Baranauskas (Red Hat)*: Handles legacy chunk format
- **Milvus** ([#4484](https://github.com/ogx-ai/ogx/pull/4484)) - *Francisco Javier Arceo (Red Hat)*: Handles legacy chunk format
- **SQLite-vec, Chroma, Weaviate** ([#4502](https://github.com/ogx-ai/ogx/pull/4502)) - *Christian Zaccaria (Red Hat)*: Handle legacy chunk formats

## Bug Fixes

- MCP CPU spike fixed by using context manager for session cleanup ([#4758](https://github.com/ogx-ai/ogx/pull/4758)) - *Bill Murdock (Red Hat)*
- Concurrent SentenceTransformer loading race condition fixed ([#4636](https://github.com/ogx-ai/ogx/pull/4636)) - *Sergey Yedrikov (Red Hat)*
- Reasoning content field compatibility with Ollama and vLLM ([#4715](https://github.com/ogx-ai/ogx/pull/4715)) - *Shabana Baig (Red Hat)*
- File search results now include document attributes/metadata ([#4680](https://github.com/ogx-ai/ogx/pull/4680)) - *Cesare Pompeiano (Red Hat)*
- Vector store registration from config with OpenAI metadata ([#4616](https://github.com/ogx-ai/ogx/pull/4616)) - *Cesare Pompeiano (Red Hat)*
- Session polling enabled during streaming responses ([#4738](https://github.com/ogx-ai/ogx/pull/4738)) - *Roland Huß (Red Hat)*
- Security vulnerabilities in GitHub Actions workflows addressed ([#4752](https://github.com/ogx-ai/ogx/pull/4752)) - *Charlie Doern (Red Hat)*

## Documentation

- Updated quick start guide ([#4435](https://github.com/ogx-ai/ogx/pull/4435)) - *Guangya Liu*
- Migration guide from Agents to Responses API ([#4375](https://github.com/ogx-ai/ogx/pull/4375)) - *Bill Murdock (Red Hat)*
- Contributing guidelines for integration tests ([#4460](https://github.com/ogx-ai/ogx/pull/4460)) - *Guangya Liu*
- Provider contribution guide ([#4478](https://github.com/ogx-ai/ogx/pull/4478)) - *Sébastien Han (Red Hat)*
- Release process documentation ([#4470](https://github.com/ogx-ai/ogx/pull/4470)) - *Raghotham Murthy*

## Upgrade Guide

### Before Upgrading (Hard Breaking Changes)

Complete these steps before upgrading to 0.5:

1. **Search for post-training API calls** in your codebase:

   ```bash
   grep -r "post-training/job" .
   ```

   Update any matches to use the new path format: `/post-training/jobs/{job_uuid}/...`

2. **Search for null values in embeddings requests**:

   ```bash
   grep -rE '"(dimensions|user)":\s*null' .
   ```

   Remove these fields entirely instead of setting them to `null`.

3. **If using `inline::meta-reference` provider**, update your config:

   ```yaml
   # Before
   provider_type: inline::meta-reference

   # After (choose one)
   provider_type: remote::vllm
   provider_type: remote::ollama
   ```

4. **If you have custom safety providers**, update method signatures:

   ```python
   # Before
   async def run_shield(
       self, shield_id: str, messages: list, params: dict
   ) -> RunShieldResponse: ...


   # After
   async def run_shield(self, request: RunShieldRequest) -> RunShieldResponse: ...
   ```

5. **If using `required_scope` for endpoint auth**, migrate to new YAML config:

   ```yaml
   server:
     auth:
       endpoint_policy:
         - path: "/v1/inference/*"
           conditions:
             - role: inference-user
   ```

6. **Regenerate client SDKs** if you use generated clients from OpenAPI specs.

### After Upgrading (Deprecations)

Address these warnings before the next major release:

1. **Update configuration files**: Replace `image_name` with `distro_name`
2. **Update vLLM TLS config**: Move `tls_verify` to `network.tls.verify`
3. **Update Eval API calls**: Use `RunEvalRequest` objects instead of keyword arguments

---

### Releases RELEASE NOTES 0.7 (`docs/releases/RELEASE_NOTES_0.7.md`)

# OGX 0.7 Release Notes

**Release Date:** April 2026

Release 0.7 is a major release focused on completing the transition to OpenAI API conformance, introducing comprehensive observability metrics, and significant API cleanup. This release removes the fine-tuning API, completes the FastAPI router migration, removes legacy providers (TGI, HuggingFace), renames core concepts for clarity (agents to responses, knowledge_search to file_search, meta-reference to builtin), and adds structured logging via structlog. New providers include Infinispan vector-io and inline Docling for PDF parsing.

## Breaking Changes

### Summary

> **Note:** Each change is described in detail with migration instructions in the sections below.

**Hard Breaking Changes (action required before upgrading):**

| Change | Migration | PR |
|--------|-----------|-----|
| Fine-tuning API removed | Remove all `/post-training` and `/fine-tuning` API usage | [#5104](https://github.com/ogx-ai/ogx/pull/5104) |
| `meta-reference` providers renamed to `builtin` | Replace `inline::meta-reference` with `inline::builtin` in configs | [#5131](https://github.com/ogx-ai/ogx/pull/5131) |
| `knowledge_search` renamed to `file_search` | Replace `knowledge_search` with `file_search` in tool names and API calls | [#5186](https://github.com/ogx-ai/ogx/pull/5186) |
| Agents API renamed to Responses API | Replace `/agents` endpoints with `/responses` | [#5195](https://github.com/ogx-ai/ogx/pull/5195) |
| `tool_groups` removed from public API | Remove `tool_groups` registration; providers auto-register tools | [#4997](https://github.com/ogx-ai/ogx/pull/4997) |
| TGI and HuggingFace inference providers removed | Switch to `remote::vllm`, `remote::ollama`, or other providers | [#5333](https://github.com/ogx-ai/ogx/pull/5333) |
| `register/unregister` model endpoints removed | Use standard CRUD endpoints for model management | [#5341](https://github.com/ogx-ai/ogx/pull/5341) |
| `@webmethod` decorator removed | All APIs now use FastAPI routers exclusively | [#5248](https://github.com/ogx-ai/ogx/pull/5248) |
| `rag-runtime` provider renamed to `file-search` | Replace `inline::rag-runtime` with `inline::file-search` in configs | [#5187](https://github.com/ogx-ai/ogx/pull/5187) |
| Duplicate `dataset_id` parameter removed from append-rows | Remove `dataset_id` from request body (use path parameter only) | [#4849](https://github.com/ogx-ai/ogx/pull/4849) |
| `/files/{file_id}` GET response format unified | Update clients expecting provider-specific response shapes | [#5154](https://github.com/ogx-ai/ogx/pull/5154) |
| OpenAI API schema transforms added | Review response schemas for new conformance fields | [#5166](https://github.com/ogx-ai/ogx/pull/5166) |
| `starter-gpu` distribution removed | Use `starter` distribution with remote inference providers | [#5279](https://github.com/ogx-ai/ogx/pull/5279) |

**Behavior Changes (no code changes required, but be aware):**

| Change | Note | PR |
|--------|------|-----|
| `sentence_transformers` `trust_remote_code` defaults to `False` | Set `trust_remote_code: true` in config if using custom models | [#4602](https://github.com/ogx-ai/ogx/pull/4602) |
| Inline neural rerank for RAG | Reranking now available as built-in capability | [#4877](https://github.com/ogx-ai/ogx/pull/4877) |
| Logging migrated to structlog | Log output format changed to structured key-value pairs | [#5215](https://github.com/ogx-ai/ogx/pull/5215) |

---

### Hard Breaking Changes

These changes take effect immediately and require updates before upgrading.

#### 1. Fine-Tuning API Removed ([#5104](https://github.com/ogx-ai/ogx/pull/5104))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** All users of the post-training/fine-tuning API

The entire fine-tuning API has been removed from OGX. This includes all `/post-training` endpoints and related provider implementations.

**Migration:** Remove all fine-tuning API calls. Use external fine-tuning services directly.

---

#### 2. `meta-reference` Providers Renamed to `builtin` ([#5131](https://github.com/ogx-ai/ogx/pull/5131))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** All users with `meta-reference` in their distribution configs

**Before:**

```yaml
provider_type: inline::meta-reference
```

**After:**

```yaml
provider_type: inline::builtin
```

**Migration:** Search and replace `inline::meta-reference` with `inline::builtin` in all config files.

```bash
grep -r "meta-reference" your-config-directory/
```

---

#### 3. `knowledge_search` Renamed to `file_search` ([#5186](https://github.com/ogx-ai/ogx/pull/5186))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** All users referencing `knowledge_search` tool name

**Before:**

```text
tools=[{"type": "knowledge_search", ...}]
```

**After:**

```text
tools=[{"type": "file_search", ...}]
```

**Migration:**

```bash
grep -r "knowledge_search" your-project/
```

---

#### 4. Agents API Renamed to Responses API ([#5195](https://github.com/ogx-ai/ogx/pull/5195))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** All users of the agents API endpoints

The agents API has been renamed to the Responses API to align with OpenAI's naming convention. All `/agents` endpoints are now served under `/responses`.

**Migration:** Update API endpoint paths from `/agents/*` to `/responses/*`.

---

#### 5. `tool_groups` Removed from Public API ([#4997](https://github.com/ogx-ai/ogx/pull/4997))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Users who manually register tool groups

Tool groups are now auto-registered from provider specs. The public API for registering/unregistering tool groups has been removed.

**Migration:** Remove any `tool_groups` registration calls. Ensure your provider specs include `toolgroup_id` where needed.

---

#### 6. TGI and HuggingFace Inference Providers Removed ([#5333](https://github.com/ogx-ai/ogx/pull/5333))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Users relying on `remote::tgi` or `remote::huggingface` providers

**Migration:** Switch to `remote::vllm`, `remote::ollama`, or another supported inference provider.

---

#### 7. Deprecated `register`/`unregister` Model Endpoints Removed ([#5341](https://github.com/ogx-ai/ogx/pull/5341))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Users calling deprecated model registration endpoints

**Migration:** Use standard model management endpoints.

---

#### 8. `@webmethod` Decorator Removed — FastAPI Router Migration Complete ([#5248](https://github.com/ogx-ai/ogx/pull/5248))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Custom provider authors who used `@webmethod`

All APIs now use FastAPI routers exclusively. The legacy `@webmethod` decorator has been removed.

**Migration:** Convert any custom endpoints to use FastAPI router decorators.

---

#### 9. `rag-runtime` Provider Renamed to `file-search` ([#5187](https://github.com/ogx-ai/ogx/pull/5187))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Users with `inline::rag-runtime` or `builtin::rag` in configs

**Before:**

```yaml
provider_type: inline::rag-runtime
toolgroup_id: builtin::rag
```

**After:**

```yaml
provider_type: inline::file-search
toolgroup_id: builtin::file-search
```

---

#### 10. Duplicate `dataset_id` Removed from Append-Rows ([#4849](https://github.com/ogx-ai/ogx/pull/4849))

*Contributed by Eoin Fennessy (Red Hat) — @eoinfennessy*

**Impact:** API clients sending `dataset_id` in both the URL path and request body

**Migration:** Remove `dataset_id` from the request body; it is now taken exclusively from the URL path parameter.

---

#### 11. `/files/{file_id}` GET Response Unified ([#5154](https://github.com/ogx-ai/ogx/pull/5154))

*Contributed by @r3v5*

**Impact:** Clients parsing file metadata responses

The GET endpoint now returns a consistent response shape across all providers, eliminating provider-specific differences.

---

#### 12. OpenAI API Schema Transforms ([#5166](https://github.com/ogx-ai/ogx/pull/5166))

*Contributed by Nathan Weinberg (Red Hat) — @nathan-weinberg*

**Impact:** Clients relying on the exact API response schema

Schema transforms and new types have been added to improve OpenAI API conformance. Response shapes may differ from previous versions.

---

#### 13. `starter-gpu` Distribution Removed ([#5279](https://github.com/ogx-ai/ogx/pull/5279))

*Contributed by Sebastien Han (Red Hat) — @leseb*

**Impact:** Users of the `starter-gpu` distribution

**Migration:** Use the `starter` distribution with remote inference providers instead.

---

### Behavior Changes

#### `sentence_transformers` `trust_remote_code` Now Defaults to `False` ([#4602](https://github.com/ogx-ai/ogx/pull/4602))

*Contributed by Derek Higgins (Red Hat) — @derekhiggins*

For security, `trust_remote_code` now defaults to `False` for sentence_transformers models. If you use custom models that require remote code execution, set `trust_remote_code: true` in your provider config.

#### Structured Logging via structlog ([#5215](https://github.com/ogx-ai/ogx/pull/5215))

*Contributed by Sebastien Han (Red Hat) — @leseb*

All logging has been migrated to structlog with structured key-value output. Log parsing tools that rely on the previous format may need to be updated.

---

## New Features

### Reasoning Output Support

- **Reasoning output in Responses API** — Models can now return reasoning/thinking traces as part of response output ([#5206](https://github.com/ogx-ai/ogx/pull/5206) by @robinnarsinghranabhat)
- **Reasoning as valid conversation item** — Reasoning traces can be included in conversation history ([#5392](https://github.com/ogx-ai/ogx/pull/5392))
- **Reasoning output types in OpenAI spec** — Added `reasoning` output type to the Responses API spec ([#5357](https://github.com/ogx-ai/ogx/pull/5357))

### Comprehensive Observability Metrics

- **API-level request metrics** — Track request counts, latency, and error rates at the API layer ([#5201](https://github.com/ogx-ai/ogx/pull/5201) by @gyliu513)
- **Inference metrics** — Token throughput, latency, and model-level metrics ([#5320](https://github.com/ogx-ai/ogx/pull/5320) by @gyliu513)
- **Vector IO metrics** — Performance metrics for vector store operations ([#5096](https://github.com/ogx-ai/ogx/pull/5096) by @gyliu513)
- **Parameter usage metrics for Responses API** — Track parameter usage patterns ([#5255](https://github.com/ogx-ai/ogx/pull/5255) by @gyliu513)

### Inline Neural Rerank for RAG ([#4877](https://github.com/ogx-ai/ogx/pull/4877))

*Contributed by @r3v5*

RAG pipelines can now use built-in neural reranking without external services, improving search quality with cross-encoder models.

### Inline Docling Provider for PDF Parsing ([#5049](https://github.com/ogx-ai/ogx/pull/5049))

*Contributed by @alinaryan*

Structure-aware PDF parsing using Docling for high-quality document ingestion into vector stores.

### Background Response Cancellation ([#5268](https://github.com/ogx-ai/ogx/pull/5268))

*Contributed by Charlie Doern (Red Hat) — @cdoern*

Added a cancel endpoint for background responses, allowing clients to abort long-running response generation.

### Connector API Promoted to v1beta ([#5129](https://github.com/ogx-ai/ogx/pull/5129))

*Contributed by Sebastien Han (Red Hat) — @leseb*

The Connector API for MCP server management has been promoted from `v1alpha` to `v1beta`, signaling increased API stability.

### `stream_options` Parameter Support ([#4815](https://github.com/ogx-ai/ogx/pull/4815))

*Contributed by @gyliu513*

Added support for the `stream_options` parameter in chat completions, enabling `include_usage` in streaming responses for OpenAI conformance.

### Forward Headers for Inference Passthrough ([#5134](https://github.com/ogx-ai/ogx/pull/5134))

*Contributed by @skamenan7*

The inference passthrough provider now supports forwarding custom headers to upstream backends.

### Form-Encoded Content Type for Responses API ([#5193](https://github.com/ogx-ai/ogx/pull/5193))

*Contributed by @r3v5*

The Responses API now accepts `application/x-www-form-urlencoded` content type in addition to JSON.

### PGVector Filter Support ([#5111](https://github.com/ogx-ai/ogx/pull/5111))

*Contributed by @franciscojavierarceo*

PGVector now supports metadata filters for vector search queries, and f-string usage in table names has been replaced for safety.

### Configurable asyncpg Connection Pools ([#5160](https://github.com/ogx-ai/ogx/pull/5160))

*Contributed by @iamemilio*

PostgreSQL connection pool settings (min/max connections, timeouts) are now configurable via provider config.

### Provider Compatibility Matrix ([#5113](https://github.com/ogx-ai/ogx/pull/5113), [#5115](https://github.com/ogx-ai/ogx/pull/5115))

*Contributed by Sebastien Han (Red Hat) — @leseb*

A provider compatibility matrix for the Responses API and provider version tracking have been added to help users understand which features each provider supports.

### Responses API Test Coverage Analyzer ([#5101](https://github.com/ogx-ai/ogx/pull/5101))

Conformance annotations and a test coverage analyzer for the Responses API have been added to track OpenAI specification coverage.

## New Providers

### Infinispan Vector-IO Provider ([#4839](https://github.com/ogx-ai/ogx/pull/4839))

*Contributed by @rigazilla*

New vector store provider using Infinispan for distributed, high-performance vector storage.

## Refactoring

- **WatsonX: LiteLLM replaced with OpenAI mixin** — Cleaner, more maintainable WatsonX provider ([#5133](https://github.com/ogx-ai/ogx/pull/5133) by @c99cd1a93)
- **`file_search` decoupled from legacy `knowledge_search` tool_groups** ([#5175](https://github.com/ogx-ai/ogx/pull/5175) by @leseb)
- **Large files split into focused modules** ([#5281](https://github.com/ogx-ai/ogx/pull/5281), [#5299](https://github.com/ogx-ai/ogx/pull/5299) by @leseb)
- **Tools API converted to FastAPI router** ([#5246](https://github.com/ogx-ai/ogx/pull/5246) by @leseb)
- **Unused `LiteLLMOpenAIMixin` removed** ([#5159](https://github.com/ogx-ai/ogx/pull/5159))

## Performance Improvements

- **Lazy-load numpy, faiss, sqlite_vec** in vector_io providers to reduce startup memory ([#5118](https://github.com/ogx-ai/ogx/pull/5118))
- **Lazy-load torch and transformers** in prompt_guard ([#5117](https://github.com/ogx-ai/ogx/pull/5117))
- **Lazy-load torch** in embedding_mixin to reduce startup memory ([#5116](https://github.com/ogx-ai/ogx/pull/5116))
- **Lazy-load braintrust autoevals** to reduce idle memory (~63MB) ([#5078](https://github.com/ogx-ai/ogx/pull/5078))

## Security Fixes

- **Path traversal and header injection defenses** ([#5086](https://github.com/ogx-ai/ogx/pull/5086) by @rhdedgar)
- **CVE-2026-33236**: Bump nltk to 3.9.4 ([#5259](https://github.com/ogx-ai/ogx/pull/5259) by @eoinfennessy)
- **CVE-2026-30922**: Bump pyasn1 to 0.6.3 ([#5207](https://github.com/ogx-ai/ogx/pull/5207) by @eoinfennessy)
- **CVE-2026-32597**: Bump pyjwt to 2.12.0 ([#5127](https://github.com/ogx-ai/ogx/pull/5127) by @eoinfennessy)

## Bug Fixes

- Fix provider_data_var context leak ([#5227](https://github.com/ogx-ai/ogx/pull/5227) by @jaideepr97)
- Prevent OTel context leak in fire-and-forget background tasks ([#5168](https://github.com/ogx-ai/ogx/pull/5168) by @iamemilio)
- Disable asyncpg OTel auto-instrumentation to prevent duplicate DB spans ([#5158](https://github.com/ogx-ai/ogx/pull/5158))
- Fix asyncio event loop mismatch via operation deferral ([#5130](https://github.com/ogx-ai/ogx/pull/5130) by @derekhiggins)
- Improve chat completions OpenAI conformance ([#5108](https://github.com/ogx-ai/ogx/pull/5108) by @cdoern)
- Multi-worker cache synchronization for vector stores ([#5076](https://github.com/ogx-ai/ogx/pull/5076) by @elinacse)
- Replace blocking `requests` calls with async `httpx` in WatsonX ([#5280](https://github.com/ogx-ai/ogx/pull/5280) by @gyliu513) and remote providers ([#5162](https://github.com/ogx-ai/ogx/pull/5162) by @gyliu513)
- Use SDK-native model names for Vertex AI ([#5169](https://github.com/ogx-ai/ogx/pull/5169) by @major)
- Fix vLLM health() and rerank() TLS and auth credentials ([#5340](https://github.com/ogx-ai/ogx/pull/5340) by @gyliu513)
- Fix vLLM rerank() provider-data-aware API key lookup ([#5374](https://github.com/ogx-ai/ogx/pull/5374))
- Fix require_approval field check in ApprovalFilter ([#5288](https://github.com/ogx-ai/ogx/pull/5288) by @jaideepr97)
- Gate conversation sync on store flag to prevent data leak when store=false ([#5305](https://github.com/ogx-ai/ogx/pull/5305) by @jaideepr97)
- Fix assistant message rewriting in _separate_tool_calls ([#5303](https://github.com/ogx-ai/ogx/pull/5303) by @jaideepr97)
- Handle asyncio.CancelledError in metrics try/except blocks ([#5336](https://github.com/ogx-ai/ogx/pull/5336) by @gyliu513)
- Race condition fix in background response cancel ([#5363](https://github.com/ogx-ai/ogx/pull/5363) by @leseb)
- Allow multi-worker server with dual-stack IPv6 support ([#5284](https://github.com/ogx-ai/ogx/pull/5284) by @derekhiggins)
- Auto-expand provider dependencies for `--providers` in stack CLI ([#4654](https://github.com/ogx-ai/ogx/pull/4654) by @gyliu513)
- Make InmemoryKVStore.delete consistent with other backends ([#5289](https://github.com/ogx-ai/ogx/pull/5289) by @gyliu513)
- Convert Path to str in _build_ssl_context() for httpx compatibility ([#5380](https://github.com/ogx-ai/ogx/pull/5380) by @gyliu513)
- Surface tiktoken encoding check at provider startup ([#5401](https://github.com/ogx-ai/ogx/pull/5401) by @Bobbins228)
- Pre-cache tiktoken cl100k_base encoding at image build time ([#5391](https://github.com/ogx-ai/ogx/pull/5391) by @Bobbins228)
- Fix milvus hybrid ranker usage ([#5312](https://github.com/ogx-ai/ogx/pull/5312) by @jakub-walaszczyk)
- Remove duplicate decode ([#5177](https://github.com/ogx-ai/ogx/pull/5177))
- Optimize connector listing ([#5164](https://github.com/ogx-ai/ogx/pull/5164))
- Remove references to defunct inline::builtin inference provider ([#5174](https://github.com/ogx-ai/ogx/pull/5174) by @leseb)

## Documentation

- Rewrite README and docs to lead with OpenAI API compatibility ([#5323](https://github.com/ogx-ai/ogx/pull/5323))
- Add AGENTS.md with guidelines for AI coding agents ([#5211](https://github.com/ogx-ai/ogx/pull/5211))
- Add architecture documentation and module-level READMEs ([#5213](https://github.com/ogx-ai/ogx/pull/5213))
- Blog post on Open Responses compliance and OpenAI compatibility ([#5232](https://github.com/ogx-ai/ogx/pull/5232))
- Blog post on OGX observability ([#5387](https://github.com/ogx-ai/ogx/pull/5387))
- Agentic flows tutorial blog post ([#5035](https://github.com/ogx-ai/ogx/pull/5035))
- Blog post about Responses API ([#5196](https://github.com/ogx-ai/ogx/pull/5196))
- Docling provider setup and usage docs ([#5329](https://github.com/ogx-ai/ogx/pull/5329))
- Multi-tenant isolation example for conversations and responses ([#5176](https://github.com/ogx-ai/ogx/pull/5176))
- Update stale documentation to reflect current architecture ([#5393](https://github.com/ogx-ai/ogx/pull/5393))
- Mintlify-inspired documentation UI improvements ([#5405](https://github.com/ogx-ai/ogx/pull/5405))
- Add docstrings to public classes and functions ([#5267](https://github.com/ogx-ai/ogx/pull/5267))
- Update README badges with logos, conformance score, and DeepWiki ([#5389](https://github.com/ogx-ai/ogx/pull/5389))

## CI/CD Improvements

- Auto-record integration tests on PRs with multi-provider support ([#5123](https://github.com/ogx-ai/ogx/pull/5123))
- Add Bedrock to responses CI suite with recordings ([#5254](https://github.com/ogx-ai/ogx/pull/5254))
- Add WatsonX Responses API integration test recordings ([#5120](https://github.com/ogx-ai/ogx/pull/5120))
- Test Responses API against Azure AI Foundry ([#5107](https://github.com/ogx-ai/ogx/pull/5107))
- Add GCP Workload Identity Federation for Vertex AI recording workflow ([#5276](https://github.com/ogx-ai/ogx/pull/5276))
- Cache HuggingFace models and datasets for offline replay tests ([#5382](https://github.com/ogx-ai/ogx/pull/5382))
- Add conventional-pre-commit for commit validation ([#5251](https://github.com/ogx-ai/ogx/pull/5251))
- Add markdownlint and actionlint pre-commit hooks ([#5271](https://github.com/ogx-ai/ogx/pull/5271), [#5285](https://github.com/ogx-ai/ogx/pull/5285))
- Add mypy pre-commit hook enforcement ([#5269](https://github.com/ogx-ai/ogx/pull/5269))
- Replace Mergify queue with GitHub merge queue ([#5383](https://github.com/ogx-ai/ogx/pull/5383))
- Test last 3 release branches in scheduled CI ([#5277](https://github.com/ogx-ai/ogx/pull/5277))
- Remove docker mode from integration test matrix ([#5311](https://github.com/ogx-ai/ogx/pull/5311))

## Upgrade Guide

### Before Upgrading

These hard breaking changes require updates before you can run 0.7:

1. **Check for fine-tuning API usage:**

   ```bash
   grep -r "post-training\|fine.tuning\|fine_tuning" your-project/
   ```

   Remove all fine-tuning API calls.

2. **Update provider names in configs:**

   ```bash
   grep -r "meta-reference" your-config-directory/
   grep -r "rag-runtime" your-config-directory/
   grep -r "starter-gpu" your-config-directory/
   ```

   - `inline::meta-reference` -> `inline::builtin`
   - `inline::rag-runtime` -> `inline::file-search`
   - `builtin::rag` -> `builtin::file-search`
   - `starter-gpu` -> `starter`

3. **Update tool names:**

   ```bash
   grep -r "knowledge_search" your-project/
   ```

   Replace with `file_search`.

4. **Update API endpoints:**

   ```bash
   grep -r "/agents" your-project/
   ```

   Replace agents API calls with responses API equivalents.

5. **Remove tool_groups registration:**

   ```bash
   grep -r "tool_groups\|register_tool" your-project/
   ```

   Tool groups are now auto-registered from provider specs.

6. **Check for removed providers:**

   ```bash
   grep -r "remote::tgi\|remote::huggingface" your-config-directory/
   ```

   Switch to `remote::vllm`, `remote::ollama`, or another supported provider.

7. **Check for deprecated model endpoints:**

   ```bash
   grep -r "register_model\|unregister_model" your-project/
   ```

### After Upgrading

- Review log output if you have log parsing tools, as logging now uses structured key-value format via structlog.
- If using `sentence_transformers` with custom models requiring remote code, add `trust_remote_code: true` to your provider config.

---

### Releases RELEASE NOTES 1.0 (`docs/releases/RELEASE_NOTES_1.0.md`)

# OGX 1.0 Release Notes

**Release Date:** May 2026

OGX 1.0 marks the project's first major-stable release. The `/v1` HTTP API surface is now covered by the stability contract documented in [`docs/docs/concepts/apis/api_leveling.mdx`](../docs/concepts/apis/api_leveling.mdx): no breaking changes to `/v1` datatypes or on-disk storage schemas within the 1.x line. APIs that are not yet stable continue to live under `/v1alpha` and `/v1beta`.

The headline themes for 1.0:

- **Multi-tenancy core for MaaS deployments** — first-class tenant isolation across storage, vector stores, prompts, and conversations.
- **Authorization as a first-class storage concern** — all access-controlled APIs now go through `AuthorizedSqlStore`.
- **Admin/data plane split** — administrative routes (`tools`, `connectors`) moved out of the user-facing `/v1` surface.
- **Safety API removed** — replaced by the OpenAI-compatible moderation endpoint.
- **`ogx-api` namespace split** — `ogx_api.types` (datatypes) and `ogx_api.provider` (provider authoring) are now distinct surfaces with their own stability rules.
- **Gateway-first server architecture** — edge concerns (auth, rate limiting, tenancy) consolidated at the gateway.

## Breaking Changes

### Summary

> **Note:** Each change is described in detail with migration instructions in the sections below.

**Hard Breaking Changes (action required before upgrading):**

| Change | Migration | PR |
|--------|-----------|-----|
| Safety API removed; use `/v1/moderations` | Replace `run-shield` and `shields` calls with the moderation endpoint | [#5291](https://github.com/ogx-ai/ogx/pull/5291), [#5744](https://github.com/ogx-ai/ogx/pull/5744) |
| Tools routes moved to `/v1/admin/tools` | Update tool-management clients to `/v1/admin/tools` | [#5787](https://github.com/ogx-ai/ogx/pull/5787) |
| Connectors routes moved to `/v1alpha/admin/connectors` | Update connector-management clients | [#5659](https://github.com/ogx-ai/ogx/pull/5659) |
| Multi-tenancy enforcement on by default | Provide tenant credentials/headers; review per-tenant data scoping | [#5756](https://github.com/ogx-ai/ogx/pull/5756) |
| `AuthorizedSqlStore` required for access-controlled APIs | Custom providers must migrate from raw SqlStore | [#5776](https://github.com/ogx-ai/ogx/pull/5776) |
| Connectors and batches KVStore migrated to `AuthorizedSqlStore` | On-disk migration runs on first boot; back up state first | [#5757](https://github.com/ogx-ai/ogx/pull/5757) |
| `/v1/models` response shape now multi-SDK | Clients parsing the legacy shape must update | [#5522](https://github.com/ogx-ai/ogx/pull/5522) |
| `ogx-api` split into `ogx_api.types` and `ogx_api.provider` | Update imports in provider code and downstream consumers | [#5740](https://github.com/ogx-ai/ogx/pull/5740) |
| `logprobs` type changed from `bool` to `int` on Completions | Update clients passing `logprobs=True/False` to an integer | [#5343](https://github.com/ogx-ai/ogx/pull/5343) |
| `ogx stack rm` CLI command removed | Use distribution-specific teardown instead | [#5735](https://github.com/ogx-ai/ogx/pull/5735) |

---

### Hard Breaking Changes

#### 1. Safety API Removed; Replaced by Moderation Endpoint ([#5291](https://github.com/ogx-ai/ogx/pull/5291), [#5744](https://github.com/ogx-ai/ogx/pull/5744))

**Impact:** All users of `/v1/safety/run-shield` and the `/v1/shields` list/get endpoints.

The standalone Safety API has been removed. Content moderation is now served by the OpenAI-compatible `/v1/moderations` endpoint.

**Migration:** Replace `run-shield` calls with `/v1/moderations`. Shield registration and listing endpoints are removed; configure moderation models via provider config instead.

---

#### 2. Tools Routes Moved to `/v1/admin/tools` ([#5787](https://github.com/ogx-ai/ogx/pull/5787))

**Impact:** Clients calling `/v1/tools` for tool management.

Tool-management endpoints are now under the administrative path `/v1/admin/tools`, separating the control plane from the user-facing API.

**Migration:** Update tool-management clients to the new path. End-user code that *invokes* tools through Responses/Chat Completions is unaffected.

---

#### 3. Connectors Routes Moved to `/v1alpha/admin/connectors` ([#5659](https://github.com/ogx-ai/ogx/pull/5659))

**Impact:** Clients managing MCP connectors.

Connector management has moved to `/v1alpha/admin/connectors`, reflecting its admin-plane role and pre-stable API level.

**Migration:** Update connector management clients to the new path.

---

#### 4. Multi-Tenancy Core for MaaS Deployments ([#5756](https://github.com/ogx-ai/ogx/pull/5756))

**Impact:** Any deployment running without explicit tenant configuration.

OGX now ships with first-class multi-tenant isolation suitable for Model-as-a-Service deployments. Tenant context is propagated through storage, vector stores, conversations, and prompts. Vector store metadata isolation ([#5782](https://github.com/ogx-ai/ogx/pull/5782)) and prompts tenant isolation tests ([#5758](https://github.com/ogx-ai/ogx/pull/5758)) ship alongside.

**Migration:** Single-tenant deployments must explicitly opt into the default tenant or configure tenant credentials. Review any custom providers that touched storage directly — they must now go through `AuthorizedSqlStore` (see below).

---

#### 5. `AuthorizedSqlStore` Required for Access-Controlled APIs ([#5776](https://github.com/ogx-ai/ogx/pull/5776))

**Impact:** Custom provider authors using raw `SqlStore` for tenant-scoped data.

APIs that require access control now enforce use of `AuthorizedSqlStore`, which integrates tenant identity into every query.

**Migration:** Update custom providers to construct `AuthorizedSqlStore` rather than `SqlStore` for tenant-scoped tables.

---

#### 6. Connectors and Batches KVStore Migrated to AuthorizedSqlStore ([#5757](https://github.com/ogx-ai/ogx/pull/5757))

**Impact:** Existing deployments with stored connector or batch state.

On first boot of 1.0, connector and batch state migrates from the legacy KVStore layout to `AuthorizedSqlStore`-backed tables.

**Migration:** Back up storage before upgrading. The migration is one-way; downgrade is not supported.

---

#### 7. Multi-SDK Response Shapes for `/v1/models` ([#5522](https://github.com/ogx-ai/ogx/pull/5522))

**Impact:** Clients parsing the legacy `/v1/models` response.

`/v1/models` now returns response shapes aligned with each SDK convention (OpenAI, Anthropic, etc.) rather than a single OGX-specific shape.

**Migration:** Update clients parsing model metadata to the new shape. See the API reference for the full schema.

---

#### 8. `ogx-api` Namespace Split into `types` and `provider` ([#5740](https://github.com/ogx-ai/ogx/pull/5740))

**Impact:** Code importing from `ogx_api` directly.

`ogx_api` is now split into two surfaces with distinct stability rules:

- `ogx_api.types` — Pydantic datatypes used over the wire; follows the `/v1` stability contract.
- `ogx_api.provider` — base classes and protocols for provider authors; evolves with provider architecture.

See [#5719](https://github.com/ogx-ai/ogx/pull/5719) for the datatype stability documentation.

**Migration:** Update imports. The old top-level imports remain as transitional shims in 1.0 but will be removed in 2.0.

---

#### 9. `logprobs` Type on Completions: `bool` → `int` ([#5343](https://github.com/ogx-ai/ogx/pull/5343))

**Impact:** Clients passing `logprobs=True` or `logprobs=False` to `/v1/completions`.

The `logprobs` parameter now takes an integer (number of top logprobs to return), matching OpenAI's Completions API.

**Migration:** Replace `True` with an integer (e.g., `1` or `5`); replace `False` with omission of the field.

---

#### 10. `ogx stack rm` CLI Command Removed ([#5735](https://github.com/ogx-ai/ogx/pull/5735))

**Impact:** Users running `ogx stack rm`.

The command was undiscoverable and rarely used.

**Migration:** Use the distribution-specific teardown for your deployment (container stop, `uv` venv removal, etc.).

---

## New Features

### Multi-Tenancy and Authorization

- **Multi-tenancy core for MaaS deployments** ([#5756](https://github.com/ogx-ai/ogx/pull/5756))
- **Tenant isolation for vector store metadata** ([#5782](https://github.com/ogx-ai/ogx/pull/5782))
- **`AuthorizedSqlStore` enforcement across access-controlled APIs** ([#5776](https://github.com/ogx-ai/ogx/pull/5776))
- **Connectors and batches migrated to `AuthorizedSqlStore`** ([#5757](https://github.com/ogx-ai/ogx/pull/5757))
- **Prompts tenant isolation CI workflow** ([#5758](https://github.com/ogx-ai/ogx/pull/5758))
- **GitHub org-membership fetching for RBAC attribute mapping** ([#5711](https://github.com/ogx-ai/ogx/pull/5711))

### Gateway-First Server Architecture ([#5750](https://github.com/ogx-ai/ogx/pull/5750))

Edge concerns — authentication, rate limiting, tenant resolution — are now consolidated at the gateway layer rather than scattered across handlers.

### New Inference Providers and Compatibility

- **Gemini and Azure support in `letsgo`** ([#5706](https://github.com/ogx-ai/ogx/pull/5706))
- **Claude Code compatibility in `letsgo`** ([#5709](https://github.com/ogx-ai/ogx/pull/5709))
- **`inline::auto` file processor in `letsgo`** ([#5704](https://github.com/ogx-ai/ogx/pull/5704))
- **CLI showcase for Claude Code, Codex, and OpenCode on the landing page** ([#5716](https://github.com/ogx-ai/ogx/pull/5716))

### File Processing

- **`inline::auto` composite file processor** ([#5673](https://github.com/ogx-ai/ogx/pull/5673))
- **`inline::markitdown` provider wired into the auto dispatcher** ([#5688](https://github.com/ogx-ai/ogx/pull/5688))

### Conversations and Interactions

- **`previous_interaction_id` for multi-turn conversations** ([#5669](https://github.com/ogx-ai/ogx/pull/5669))
- **Enhanced OpenAI API coverage for Conversations** ([#5748](https://github.com/ogx-ai/ogx/pull/5748))
- **Chat completion message listing endpoint** ([#5459](https://github.com/ogx-ai/ogx/pull/5459))
- **Cursor pagination and `has_more` for conversation list_items** ([#5612](https://github.com/ogx-ai/ogx/pull/5612))

### Files

- **Enhanced OpenAI API coverage for Files API** ([#5747](https://github.com/ogx-ai/ogx/pull/5747))

### CLI

- **Top-level `ogx run` and `ogx letsgo` shortcuts** ([#5689](https://github.com/ogx-ai/ogx/pull/5689))

### `ogx-api` Package

- **`ogx_api.provider` and `ogx_api.types` namespaces introduced** ([#5740](https://github.com/ogx-ai/ogx/pull/5740))
- **Datatype stability and package-surface documentation** ([#5719](https://github.com/ogx-ai/ogx/pull/5719))

## Performance Improvements

- **asyncpg connection pool in PostgreSQL kvstore** ([#5734](https://github.com/ogx-ai/ogx/pull/5734))
- **psycopg2 → asyncpg migration in PostgreSQL KV store** ([#5739](https://github.com/ogx-ai/ogx/pull/5739))
- **Batched guardrail checks during Responses API streaming** ([#5664](https://github.com/ogx-ai/ogx/pull/5664))
- **Explicit HTTP timeouts and improved connection pooling** ([#5737](https://github.com/ogx-ai/ogx/pull/5737))

## Security Fixes

- **Python SAST via Ruff bandit rules and CodeQL scanning** ([#5738](https://github.com/ogx-ai/ogx/pull/5738))
- **High-severity CVE patches in python-multipart, protobuf, lxml, and npm packages** ([#5775](https://github.com/ogx-ai/ogx/pull/5775))
- **Critical and high-severity dependency upgrades** ([#5742](https://github.com/ogx-ai/ogx/pull/5742))
- **CVE-pinned transitive deps moved to constraint-dependencies** ([#5707](https://github.com/ogx-ai/ogx/pull/5707))
- **Dependabot alert resolution in `ogx_api` constraint-dependencies** ([#5778](https://github.com/ogx-ai/ogx/pull/5778))
- **NVIDIA provider: proper URL parsing for hostname validation** ([#5777](https://github.com/ogx-ai/ogx/pull/5777))

## Bug Fixes

- **Thread-safe `OGXAsLibraryClient`** ([#5773](https://github.com/ogx-ai/ogx/pull/5773))
- **SQLite-vec WAL mode and `busy_timeout`** ([#5428](https://github.com/ogx-ai/ogx/pull/5428))
- **Gemini streaming: strip per-chunk usage to prevent token overcounting** ([#5171](https://github.com/ogx-ai/ogx/pull/5171))
- **Responses API: honor `include` on input item retrieval** ([#5605](https://github.com/ogx-ai/ogx/pull/5605))
- **Auth: return 503 only for auth-service outages** ([#5715](https://github.com/ogx-ai/ogx/pull/5715))
- **Auth: respect `verify_tls` in OAuth2 introspection** ([#5710](https://github.com/ogx-ai/ogx/pull/5710))
- **OpenAI: clamp `max_tokens` to per-model limits** ([#5696](https://github.com/ogx-ai/ogx/pull/5696))
- **Ollama: tolerate dict-backed reasoning messages in OpenAI preprocessing** ([#5638](https://github.com/ogx-ai/ogx/pull/5638))
- **Vertex AI: preserve `reasoning_content` as thought parts in multi-turn conversations** ([#5677](https://github.com/ogx-ai/ogx/pull/5677))
- **NVIDIA safety: use `provider_resource_id` for NeMoGuardrails model** ([#5726](https://github.com/ogx-ai/ogx/pull/5726))
- **PostgreSQL storage: filter expired rows in `keys_in_range()`** ([#5712](https://github.com/ogx-ai/ogx/pull/5712))
- **SQL store: propagate real add-column errors** ([#5713](https://github.com/ogx-ai/ogx/pull/5713))
- **KVStore: namespace support and expiration filtering across all backends** ([#5731](https://github.com/ogx-ai/ogx/pull/5731))
- **Vector IO: improved error reporting for file processor rejections** ([#5690](https://github.com/ogx-ai/ogx/pull/5690))
- **Starter extra: add missing dependencies** ([#5674](https://github.com/ogx-ai/ogx/pull/5674))
- **Test parametrization: use `provider_type` instead of `provider_id`** ([#5263](https://github.com/ogx-ai/ogx/pull/5263))

## Refactoring

- **Server adopts gateway-first architecture for edge concerns** ([#5750](https://github.com/ogx-ai/ogx/pull/5750))
- **Dead code removal across the codebase** ([#5779](https://github.com/ogx-ai/ogx/pull/5779))

## Documentation

- **Datatype stability and `ogx-api` package surfaces** ([#5719](https://github.com/ogx-ai/ogx/pull/5719))
- **Consistent agentic API layer** blog post ([#5687](https://github.com/ogx-ai/ogx/pull/5687))
- **Landing page promotes library mode** ([#5761](https://github.com/ogx-ai/ogx/pull/5761))
- **Provider card / DocCardList redesign** ([#5694](https://github.com/ogx-ai/ogx/pull/5694))
- **Claude Code `--model` examples and routing clarification** ([#5692](https://github.com/ogx-ai/ogx/pull/5692))

## CI/CD Improvements

- **Pin `record-integration-tests` action refs to merge commit SHA** ([#5762](https://github.com/ogx-ai/ogx/pull/5762))
- **Break record-integration-tests feedback loop** ([#5781](https://github.com/ogx-ai/ogx/pull/5781))
- **All Ollama variants in the re-record workflow** ([#5746](https://github.com/ogx-ai/ogx/pull/5746))
- **Reduced GitHub Actions runner usage for free-plan constraints** ([#5751](https://github.com/ogx-ai/ogx/pull/5751))
- **Server-only client on PR integration tests** ([#5697](https://github.com/ogx-ai/ogx/pull/5697))
- **Conventional-commit scope allowed in breaking-change acknowledgment regex** ([#5718](https://github.com/ogx-ai/ogx/pull/5718))

## Upgrade Guide

### Before Upgrading

These hard breaking changes require updates before you can run 1.0:

1. **Back up storage.** The connectors/batches KVStore migration is one-way.

2. **Replace Safety API usage.**

   ```bash
   grep -r "/v1/safety\|run-shield\|/v1/shields" your-project/
   ```

   Switch to `/v1/moderations`.

3. **Update admin route clients.**

   ```bash
   grep -r "/v1/tools\b" your-project/
   grep -r "/v1/connectors\b\|/v1alpha/connectors\b" your-project/
   ```

   - `/v1/tools` → `/v1/admin/tools`
   - `/v1/connectors` → `/v1alpha/admin/connectors`

4. **Configure tenancy.** Single-tenant deployments must opt into the default tenant or provide tenant credentials. Review provider configs that touch storage.

5. **Update `logprobs` callers on Completions.**

   ```bash
   grep -rn "logprobs.*=\s*\(True\|False\)" your-project/
   ```

   Replace booleans with integers (or omit the field).

6. **Update `/v1/models` parsers** to the new multi-SDK response shape.

7. **Update `ogx_api` imports** to use `ogx_api.types` or `ogx_api.provider` as appropriate. Transitional shims are in place for 1.0 but will be removed in 2.0.

### After Upgrading

- Custom provider authors: migrate any direct `SqlStore` usage to `AuthorizedSqlStore` for access-controlled tables.
- Review auth/rate-limit configuration in light of the new gateway-first architecture.
- Verify multi-tenant data scoping with the new vector-store metadata isolation if you have shared deployments.

---

### Releases RELEASE NOTES 2.0 (`docs/releases/RELEASE_NOTES_2.0.md`)

# OGX 2.0 Release Notes

**Release Date:** November 2026

**OGX 2.0** is a major release from 28 contributors (133 PRs since v1.5.0). New in this release: the SystemOne judgment model API, available across Ollama, llama.cpp, SGLang, and vLLM; a new SGLang inference provider with Tev1 support; namespaced function tools; a new SearchApi web search backend; and Python 3.14 support.

The headline themes for 2.0:

- **SystemOne judgment model API** — a first-class judgment surface with the TypeSafe provider and local-engine judgment support on Ollama, llama.cpp, SGLang, and vLLM.
- **Web search as a routed API** — search moved out of the `tool_runtime` tools into the `web_search` endpoint, with a new SearchApi backend and a built-in placeholder so it works before any search provider is configured.
- **`tool_runtime`/`tool_groups` retirement** — web and file search now run inside the Responses API, and MCP tools are served by the Responses API directly.
- **Namespaced function tools** with identity-exact mapping through the chat-completions layer.
- **SGLang provider** with Tev1 support and integration CI enabled.
- **Python 3.13–3.14** (3.12 dropped).

## Overview

### Local engine support

- **New SGLang inference provider** with Tev1 support and integration CI enabled ([#6776](https://github.com/ogx-ai/ogx/pull/6776), [#6822](https://github.com/ogx-ai/ogx/pull/6822))
- **Python 3.13–3.14** (3.12 dropped) ([#6973](https://github.com/ogx-ai/ogx/pull/6973))
- Engine pins advanced across the board: **llama.cpp b12360 (v1.0.0)** ([#7010](https://github.com/ogx-ai/ogx/pull/7010)), **Ollama 0.40.16** ([#7011](https://github.com/ogx-ai/ogx/pull/7011)), **vLLM 0.32.0** ([#6840](https://github.com/ogx-ai/ogx/pull/6840)), **SGLang 0.5.23** ([#6986](https://github.com/ogx-ai/ogx/pull/6986))
- Ollama embedding models classified through models.dev ([#6879](https://github.com/ogx-ai/ogx/pull/6879))
- Self-hosted backend and reasoning suites unified into single test matrices ([#6881](https://github.com/ogx-ai/ogx/pull/6881), [#6887](https://github.com/ogx-ai/ogx/pull/6887), [#6889](https://github.com/ogx-ai/ogx/pull/6889))

### Harness & agent support

- **Web search is now a routed API** — search moved from the tool_runtime tools to the `web_search` endpoint; new SearchApi backend, configurable Brave Search base URL, and a built-in placeholder so it works before any search provider is configured ([#7014](https://github.com/ogx-ai/ogx/pull/7014), [#6927](https://github.com/ogx-ai/ogx/pull/6927), [#6878](https://github.com/ogx-ai/ogx/pull/6878), [#6957](https://github.com/ogx-ai/ogx/pull/6957))
- **`tool_runtime`/`tool_groups` APIs retired** — web and file search now run inside the Responses API, and MCP tools are served by the Responses API directly, optionally via MCP connectors ([#7039](https://github.com/ogx-ai/ogx/pull/7039), [#7033](https://github.com/ogx-ai/ogx/pull/7033))
- **Namespaced function tools** with identity-exact mapping through the chat-completions layer ([#6941](https://github.com/ogx-ai/ogx/pull/6941))
- **`ogx connect` CLI overhaul** — shared `--url`, `-k/--insecure`, API-key pass-through, `https://localhost` default, consistent argument forwarding across the agent connectors; deprecated shims removed ([#6928](https://github.com/ogx-ai/ogx/pull/6928), [#6930](https://github.com/ogx-ai/ogx/pull/6930), [#6942](https://github.com/ogx-ai/ogx/pull/6942), [#6953](https://github.com/ogx-ai/ogx/pull/6953), [#6954](https://github.com/ogx-ai/ogx/pull/6954), [#6929](https://github.com/ogx-ai/ogx/pull/6929), [#7076](https://github.com/ogx-ai/ogx/pull/7076))
- Smoke suites for the Claude Code client and the agent CLIs ([#6873](https://github.com/ogx-ai/ogx/pull/6873), [#6958](https://github.com/ogx-ai/ogx/pull/6958))

### SystemOne API

- **SystemOne judgment model API** with the TypeSafe provider ([#6748](https://github.com/ogx-ai/ogx/pull/6748))
- Judgment support on **Ollama, llama.cpp, SGLang, and vLLM**, each with its own integration CI lane ([#6769](https://github.com/ogx-ai/ogx/pull/6769), [#6772](https://github.com/ogx-ai/ogx/pull/6772), [#6782](https://github.com/ogx-ai/ogx/pull/6782), [#6866](https://github.com/ogx-ai/ogx/pull/6866), [#6773](https://github.com/ogx-ai/ogx/pull/6773), [#6880](https://github.com/ogx-ai/ogx/pull/6880))

**Also in this release:** Responses robustness (proper 400s for oversized prompts and incomplete `text.format`, malformed tool-call arguments fed back to the model, no more silently dropped turns, `content_filter` → refusal), Vector IO pagination/chunking/embedding fixes, the Simplified Chinese README, and the finalized JOSS manuscript.

## Breaking Changes

### Summary

> **Note:** Each change is described in detail in the sections below.

| Change | Migration | PR |
|--------|-----------|----|
| Python 3.12 no longer supported (3.13–3.14 are) | `ogx`/`ogx-api` wheels require an interpreter ≥ 3.13; Ubuntu 24.04's stock 3.12 needs uv/pyenv | [#6973](https://github.com/ogx-ai/ogx/pull/6973) |
| `tool_runtime` and `tool_groups` APIs removed (incl. `remote::model-context-protocol`) | Web and file search run inside the Responses API; MCP tools are served by the Responses API directly, optionally via MCP connectors | [#7039](https://github.com/ogx-ai/ogx/pull/7039) |
| `remote::passthrough` inference provider removed | Fixed-endpoint case: `remote::openai` with a `base_url` override. Per-request `passthrough_url`/`forward_headers` has **no equivalent** | [#7034](https://github.com/ogx-ai/ogx/pull/7034) |
| `/v1alpha/file-processors/process` route removed | Use the jobs API | [#7078](https://github.com/ogx-ai/ogx/pull/7078) |
| `knowledge_search` compat alias removed (deprecated since v0.7) | Use `file_search` | [#6803](https://github.com/ogx-ai/ogx/pull/6803) |
| `remote::wolfram-alpha` tool provider removed | — | [#6804](https://github.com/ogx-ai/ogx/pull/6804) |
| String forms of `Models.register_model`/`unregister_model` removed | Pass a `RegisterModelRequest`/`UnregisterModelRequest` (or keyword args) | [#7082](https://github.com/ogx-ai/ogx/pull/7082) |
| Stack/distribution configs using the `tool_runtime` API section no longer load | Move search backends to the `web_search` section | [#7079](https://github.com/ogx-ai/ogx/pull/7079) |
| Deprecated CLI shims removed: `ogx letsgo`, `ogx stack run`, `ogx stack go`, `ogx connect codex --exec` | Use `ogx go`, `ogx run`, or `--` forwarding for codex exec | [#7076](https://github.com/ogx-ai/ogx/pull/7076) |
| Deprecated config keys removed: `image_name`, `registered_resources.tool_groups`, vLLM top-level `tls_verify`; `~/.llama` → `~/.ogx` auto-migration gone | Update config files; move any remaining `~/.llama` state manually | [#7077](https://github.com/ogx-ai/ogx/pull/7077) |
| `ogx connect` resolves the server URL once: per-agent `--url`/`--host/--port` flags removed | Use `ogx connect --url ... <agent>` | [#6929](https://github.com/ogx-ai/ogx/pull/6929) |
| Anthropic message batch metadata persisted in `AuthorizedSqlStore` | A SQL store backend must be resolvable at startup for hand-written KV-only messages configs | [#7047](https://github.com/ogx-ai/ogx/pull/7047) |
| `response_format.json_schema.name` required; incomplete `text.format` → 400 at parse time | Send complete `json_schema` formats (`name` + `schema`) | [#6907](https://github.com/ogx-ai/ogx/pull/6907) |

---

### Runtime & platform

#### Python 3.12 dropped ([#6973](https://github.com/ogx-ai/ogx/pull/6973))

**Impact:** Installations on Python 3.12 (e.g. Ubuntu 24.04 stock).

The `ogx` and `ogx-api` wheels now require Python 3.13 or 3.14.

**Migration:** Use an interpreter ≥ 3.13; on systems with stock 3.12, use uv or pyenv to provision one.

### API surface removals

#### `tool_runtime` and `tool_groups` APIs removed ([#7039](https://github.com/ogx-ai/ogx/pull/7039))

**Impact:** Code calling `Api.tool_runtime`/`Api.tool_groups`, the `ToolGroups`/`ToolRuntime`/`ToolStore` protocols, tool-group models, `GET /v1/admin/tools`, or `ogx-client toolgroups`.

Everything is gone, including the `remote::model-context-protocol` provider. Tool-invocation metrics are renamed `ogx.tool_runtime.*` → `ogx.tools.*`.

**Migration:** Function tools are client-side; web and file search run inside the Responses API; MCP tools are served by the Responses API directly, optionally via MCP connectors — nothing functional is lost.

#### `remote::passthrough` inference provider removed ([#7034](https://github.com/ogx-ai/ogx/pull/7034))

**Impact:** Stacks using `remote::passthrough` as an inference provider.

**Migration:** Fixed-endpoint case: use `remote::openai` with a `base_url` override. Per-request `passthrough_url`/`forward_headers` (caller-supplied downstream URL + credentials) has **no equivalent**.

#### `/v1alpha/file-processors/process` route removed ([#7078](https://github.com/ogx-ai/ogx/pull/7078))

**Migration:** Use the jobs API.

#### `knowledge_search` compat alias removed ([#6803](https://github.com/ogx-ai/ogx/pull/6803))

Deprecated since v0.7. **Migration:** Use `file_search`.

#### `remote::wolfram-alpha` tool provider removed ([#6804](https://github.com/ogx-ai/ogx/pull/6804))

#### String forms of `Models.register_model`/`unregister_model` removed ([#7082](https://github.com/ogx-ai/ogx/pull/7082))

**Impact:** Library (not HTTP/SDK) callers passing string arguments.

**Migration:** Pass a `RegisterModelRequest`/`UnregisterModelRequest` (or keyword args).

### Config & CLI

#### `tool_runtime` config section no longer loads ([#7079](https://github.com/ogx-ai/ogx/pull/7079))

**Impact:** Stack configs and distribution configs using the `tool_runtime` API section (including the removed `inline::file-search` provider) **fail to load** — the interim lenient normalizer was itself removed.

**Migration:** Move search backends to the `web_search` section.

#### Deprecated CLI shims removed ([#7076](https://github.com/ogx-ai/ogx/pull/7076))

**Impact:** Scripts using `ogx letsgo`, `ogx stack run`, `ogx stack go`, or `ogx connect codex --exec`.

**Migration:** Use `ogx go` (auto-detect providers and start the stack), `ogx run` for explicit stack configs, or `--` forwarding for codex exec.

#### Deprecated config keys removed ([#7077](https://github.com/ogx-ai/ogx/pull/7077))

**Impact:** Configs using `image_name`, `registered_resources.tool_groups`, or vLLM top-level `tls_verify`; users relying on the `~/.llama` → `~/.ogx` auto-migration.

**Migration:** Update config files; move any remaining `~/.llama` state manually.

#### `ogx connect` resolves the server URL once ([#6929](https://github.com/ogx-ai/ogx/pull/6929))

**Impact:** Scripts using per-agent `--url` (claude/codex) or `--host/--port` (opencode) flags.

**Migration:** Use `ogx connect --url ... <agent>`. URLs without a `/v1` path (or with a non-numeric port) now fail fast with a parse error.

### Behavior

#### Anthropic message batch metadata in `AuthorizedSqlStore` ([#7047](https://github.com/ogx-ai/ogx/pull/7047))

**Impact:** Hand-written KV-only configs for the messages provider.

Batch metadata is now persisted in an `AuthorizedSqlStore` table, so a SQL store backend must be resolvable at startup. Official distributions (all define `sql_default`) are unaffected.

**Migration:** Add a SQL backend to KV-only messages-provider configs.

#### `response_format.json_schema.name` now required ([#6907](https://github.com/ogx-ai/ogx/pull/6907))

**Impact:** Clients sending `json_schema` response formats without a `name`, or incomplete `text.format` payloads.

Incomplete `text.format` now fails at parse time with a 400 (previously a 500 deep in the provider).

**Migration:** Send complete `json_schema` formats (`name` + `schema`).

---

--- METRICS ---
- Files Extracted: 99
- Estimated Token Budget: ~126055 tokens
- Canonical Reference: https://codewiki.google/github.com/ogx-ai/ogx
