OpenAI-compatible APIs (LLMs)
Two endpoints call an API that speaks the OpenAI wire format: OpenAI itself,
and the servers that copied it, such as Ollama, vLLM, LM Studio, Groq and
Mistral. A third, llm_hosted_agent, calls an API that runs tools and MCP servers
itself: OpenAI’s Responses API or Anthropic’s Messages API.
| Endpoint | Calls | Requests |
|---|---|---|
openai_chat | /chat/completions | one per message, or one per messages_per_request |
openai_embeddings | /embeddings | one per batch |
llm_hosted_agent | /responses or /messages | one per message |
All of them answer; they write nothing. Use them as the from of a
lookup, which puts the answer into the message, or
as the to of a request endpoint, which
forwards the answer. Recipes are in the LLM cookbook.
A request endpoint sends its messages one by one, so under it both endpoints
make one API request per message: messages_per_request bundles nothing and
openai_embeddings embeds one text per request. Put a
buffer on the to endpoint and the sends
of a batch leave together again, 40 messages as one embeddings request:
output:
request:
to:
openai_embeddings: { model: text-embedding-3-small, input: "${payload:text}" }
middlewares:
- buffer: { max_messages: 500, max_delay_ms: 0 }
forward_to: { file: { path: "vectors.jsonl", format: payload } }
A lookup, or the endpoint as the output itself, batches without it.
mq-bridge is not affiliated with OpenAI; the names say which API the endpoints speak.
openai_chat
Sends one chat completion per message and answers with the text of the first choice.
output:
middlewares:
- lookup:
from:
openai_chat:
url: "http://localhost:11434" # Ollama; leave out for api.openai.com
model: llama3.2
system: "Answer with one word: positive, negative or neutral."
prompt: "${payload:text}"
into: sentiment
kafka: { topic: "reviews.scored", url: "localhost:9092" }
With json: true the endpoint asks for a JSON object and parses it, so the
answer is an object in the message instead of text:
output:
middlewares:
- lookup:
concurrency: 4
from:
openai_chat:
api_key: "${env:OPENAI_API_KEY}"
model: gpt-4o-mini
json: true
prompt: 'Extract {"city": string, "urgent": boolean} as JSON from: ${payload:text}'
options: { temperature: 0 }
into: extracted
kafka: { topic: "tickets.extracted", url: "localhost:9092" }
On the command line the scheme is openai:// or openai-chat://, for example
openai://localhost:11434?model=llama3.2&prompt=….
Under a lookup
A lookup hands the endpoint the whole batch. Which concurrency limits the
requests depends on whether messages are bundled:
Without messages_per_request | With messages_per_request | |
|---|---|---|
| Requests | one per message | one per bundle |
| Requests in flight | the lookup’s concurrency (default 16) | the endpoint’s concurrency (default 8) |
| A message that cannot be answered | fails alone | fails alone |
Set the one that applies to what the server can run at once. When you compare both forms against a local model, keep the two values equal, or the comparison measures the concurrency too.
Several messages in one request
Bundling saves prompt tokens, which pays off where repeated input is billed or
no prompt cache exists. With a cache it need not save time: fifteen tickets with
a policy of about 460 tokens on Ollama (qwen3.5:2b, one local server) sent 861
instead of 6,040 prompt tokens as one bundle, but took 50 s against 40 s as
separate requests, with 695 instead of 494 output tokens, and 5 of the 15
answers differed. Compare both on your own data.
With messages_per_request the endpoint sends that many messages as numbered
inputs of one completion and hands each message its own answer. The system
message, and with it most of the prompt tokens, is sent once per request
instead of once per message:
reviews_scored:
batch_size: 100
input: { kafka: { topic: "reviews", url: "localhost:9092" } }
output:
middlewares:
- lookup:
from:
openai_chat:
api_key: "${env:OPENAI_API_KEY}"
model: gpt-4o-mini
system: "Answer with one word: positive, negative or neutral."
prompt: "${payload:text}"
messages_per_request: 20
options: { temperature: 0 }
into: sentiment
kafka: { topic: "reviews.scored", url: "localhost:9092" }
The request asks for a JSON object {"answers": [{"n": 1, "result": …}, …]}
with one entry per input, and sends that shape as a json_schema. Each answer
goes to the message whose number it carries, so the order the model answers in
does not matter. With json: true each result is a JSON object, otherwise a
string.
On the command line it is one more parameter:
openai://localhost:11434?model=llama3.2&prompt=…&messages_per_request=20.
- Answers that cannot be matched are asked again in halves. A response that is not that object, or holds a number twice or one no input has, is not used. Its messages are sent again in two requests, and so on, until what cannot be answered stands alone and fails for good. A request the API refuses with 400, 409, 413 or 422, such as one over the context length, is halved the same way, so one oversized message does not fail its neighbours.
systemmay name the format of one answer. The request adds that this format applies to each entry ofanswers.- Missing answers are asked for again. Entries that came back are kept, and only the missing messages go into the next request.
- Halving costs requests. A response that cannot be matched at all is asked again in halves. One bad message among 20 costs about ten requests instead of one; a model that loses count at every size costs up to twice as many requests as without bundling. Pick a size your model handles; how many inputs a model keeps apart depends on the model and on the length of the texts. Each halving logs a warning with the reason.
- Under a
lookup, a failed message fails alone too. The other messages of the batch keep their answers and are not asked again. - Leave room for the answers. A
max_tokensinoptionsbounds the whole response, andrequest_timeout_msthe whole request. Unset, a request fails when no response byte arrives for 300 s; setrequest_timeout_mshigher for a model that takes longer to answer, or to0for no limit. An answer that was cut off cannot be matched; the warning then says the response ended withlength. - Size is counted in messages and bytes, not tokens.
max_request_bytesbounds the request body. A single message over the model’s context is refused by the API and fails alone. - The route’s
batch_sizeis the upper bound. A bundle is cut from one batch, so a route withbatch_size: 1still sends one message per request. Nothing is held back to fill a bundle. - 429, 408 and 5xx fail the whole batch as retryable and are not halved;
retrysends it again. ARetry-Afterheader is not read: set the backoff inretry. systemis fixed text here. It is sent once per request, so it cannot take values from a message; put those intoprompt. Being the same in every request, it is also what a provider’s prompt cache can reuse.- Put the task into
systemand only the data intoprompt. The model sees all inputs of a request together, and a text that reads like an instruction can change the answers of its neighbours. Do not bundle texts from sources you do not trust with ones whose answers matter, and leavemessages_per_requestout where each message needs a request of its own. - The inputs are sent as text parts of one user message
(
content: [{"type": "text", …}]), and the request sets ajson_schemaasresponse_format. For a server that refuses it, set another inoptions, e.g.response_format: { type: text };json_objectis replaced by the schema. Only Ollama was called with this schema. - A plain-text payload: use
${message:payload}, which sends the payload as text, with invalid UTF-8 bytes replaced.${payload}and fields such as${payload:text}need a JSON payload; for plain text they render empty. - No metrics per bundle. An answer carries no mark of the bundle it came
from. With
DEBUGlogging, each non-streaming response logs itsprompt_tokensand, if the server reports them,cached_tokensandcompletion_tokens.
| Field | Default | Meaning |
|---|---|---|
url | https://api.openai.com/v1 | Base URL. One without a path gets /v1. openai://host is plain HTTP, openai+https://host is HTTPS |
api_key | none | Sent as Authorization: Bearer |
model | required | Model name |
prompt | required | Template of the user message |
system | none | Template of the system message |
json | false | Asks for response_format: json_object (with messages_per_request, the bundle’s schema) and parses the answer. An answer that is not JSON fails its message for good |
options | none | Further request fields, e.g. temperature, max_tokens, response_format; on Ollama reasoning_effort: none turns off thinking. It cannot set model, messages or stream. JSON text in a URI |
concurrency | 8 | Requests in flight when a batch is sent to the endpoint as an output. Under a lookup, the lookup’s own concurrency (default 16) decides, unless messages_per_request is set |
messages_per_request | none | Messages answered by one request, see above. Unset: one request per message |
max_request_bytes | 10 MiB | With messages_per_request: a bundle over this size is cut earlier |
request_timeout_ms | see right | Timeout of one request; 0: none. Unset: a request fails after 300 s without a response byte. With stream_to it bounds each silence of the stream, not the whole answer |
tls | none | TLS options as on http_bulk. JSON text in a URI |
auth | none | oauth2 or aws_sigv4 credentials as on http_bulk, in place of api_key. JSON text in a URI |
messages_from_payload | false | The payload is the messages array, e.g. a whole conversation. Excludes prompt, system and messages_per_request |
stream_to | none | Streams the answer, see below: every text delta goes to this endpoint. Excludes messages_per_request. JSON text in a URI |
cancel_from | none | With stream_to: a message here stops the request with its correlation_id. JSON text in a URI |
A whole conversation as the payload
With messages_from_payload: true the payload is sent as the request’s
messages, so the caller keeps the history and sends all of it:
[{"role": "system", "content": "Answer briefly."}, {"role": "user", "content": "Hi"}]
The payload must be that JSON array; anything else is refused by the API and fails its message for good.
Streaming the answer
With stream_to the endpoint asks for a streamed completion and sends every
text delta to that endpoint the moment it arrives. The whole answer is still
the message’s response, as without streaming:
chat:
concurrency: 8
input: { nats: { url: "nats://localhost:4222", subject: "chat.requests", stream: "chat_requests" } }
output:
openai_chat:
url: "http://localhost:11434"
model: llama3.2
messages_from_payload: true
stream_to: { nats: { url: "nats://localhost:4222", subject: "chat.tokens", stream: "chat_tokens", no_jetstream: true } }
cancel_from: { nats: { url: "nats://localhost:4222", subject: "chat.cancel", stream: "chat_cancel", no_jetstream: true } }
Each token message carries the delta text as payload and this metadata:
| Key | Value |
|---|---|
correlation_id | The request’s correlation_id, else its message id as 32 hex digits |
mqb.stream.attempt | A new id for each attempt at the request |
mqb.stream.index | 0, 1, 2, … within one attempt |
mqb.stream.end | true on the last token message of an attempt, else false |
mqb.stream.status | Last message only: complete, cancelled or error |
mqb.stream.stop_reason | Last message only, when the API sent one, e.g. stop or length |
The last message has an empty payload, or the error text with error. The
response carries correlation_id, mqb.stream.attempt, mqb.stream.status and
mqb.stream.stop_reason too.
- Token messages are for latency, the response is the result. The input is
committed after the whole answer, so a crash or a retry starts a new attempt:
its tokens come again from index 0 under a new
mqb.stream.attempt. A reader that sees a new attempt for acorrelation_iddrops what it collected before. What happens to tokens already sent is up tostream_to; a memory channel or core NATS loses them on a restart, a durable broker such as JetStream or Kafka keeps them. - Every attempt ends with a last token message, also one that fails
before the stream starts. A stream that breaks off ends with
errorand fails its message as retryable. An error status before the stream fails like without streaming, 408, 429 and 5xx as retryable, others for good, and its last token message holds the error withmqb.stream.index0, so a reader can tell that no text came. - A failing
stream_todoes not fail the request. It logs one warning, sends no further tokens for that request and still delivers the answer. - Cancel by
correlation_id. A message oncancel_fromwhosecorrelation_id, or else whose payload, names a running request closes its connection. The response then holds the answer so far withmqb.stream.status: cancelled, and the input is committed. A cancel that arrives before its request starts is kept for 30 s (at most 1024): the request then ends at once ascancelled, without being sent. Each such cancel stops one request. - Requests run side by side up to
concurrencywithin a batch. The route sends the next batch only when one finishes, so set the route’sconcurrencyabove 1, or a new conversation waits for the previous answer. - Do not put a collecting middleware such as
bufferonstream_to. It holds the tokens back, which is what streaming is meant to avoid. json: trueparses the complete answer. The tokens are raw text; a cancelled answer stays text.
On the command line, stream_to and cancel_from are JSON text:
openai://localhost:11434?model=llama3.2&messages_from_payload=true&stream_to={"memory":{"topic":"tokens"}}.
openai_embeddings
Sends the texts of a whole batch in one request and answers each message with its vector.
output:
middlewares:
- lookup:
from:
openai_embeddings:
api_key: "${env:OPENAI_API_KEY}"
model: text-embedding-3-small
input: "${payload:title}: ${payload:body}"
into: vector
qdrant: { url: "http://localhost:6333", collection: docs }
That writes the message with a vector field; shape it into a point first, as
on the Qdrant page. On the command line the scheme is
openai-embeddings://.
| Field | Default | Meaning |
|---|---|---|
url | https://api.openai.com/v1 | Base URL, as above. openai-embeddings://host is plain HTTP |
api_key | none | Sent as Authorization: Bearer |
model | required | Embedding model |
input | required | Template of the text to embed |
dimensions | none | Length of the vectors, for models that can shorten them |
max_request_bytes | 10 MiB | A larger batch is split into several requests |
request_timeout_ms | see right | Timeout of one request; 0: none. Unset: a request fails after 300 s without a response byte |
tls | none | TLS options as on http_bulk. JSON text in a URI |
auth | none | oauth2 or aws_sigv4 credentials as on http_bulk, in place of api_key. JSON text in a URI |
llm_hosted_agent
Sends one request per message to an API that runs the agent loop itself: the model calls tools and remote MCP servers on the provider’s side, and mq-bridge gets the final answer. mq-bridge runs no loop and calls no tool.
output:
request:
to:
llm_hosted_agent:
provider: openai # or anthropic
api_key: "${env:OPENAI_API_KEY}"
model: gpt-5-mini
system: "Answer from the documentation only."
prompt: "${payload:question}"
mcp_servers:
- name: docs
url: https://developers.openai.com/mcp
forward_to: { file: { path: "answers.jsonl", format: payload } }
provider | API | Also serves |
|---|---|---|
openai (default) | POST /responses with type: mcp tools | Azure OpenAI, xAI, Groq: set url |
anthropic | POST /messages with the MCP connector (anthropic-beta: mcp-client-2025-11-20) |
Amazon Bedrock Agents is not a provider: an agent and its tools (Lambda action groups)
are set up in AWS beforehand, and its answer is a binary AWS event stream, not one JSON
response. Bedrock models still work through openai_chat and through llm_agent with
provider: openai_chat, see Amazon Bedrock.
The answer is the text of the last message item (openai) or the text blocks
after the last tool result (anthropic). A message fails for good when the
response is failed or incomplete, stops with refusal, pause_turn or
max_tokens, has no text, asks to approve an MCP call, or calls a function
tool of options.tools, which mq-bridge does not run. mq-bridge sets
require_approval: never on every MCP server of openai; with
answer: full the whole response is the answer, tool calls included, and none
of these checks run.
| Field | Default | Meaning |
|---|---|---|
provider | openai | openai or anthropic |
url | https://api.openai.com/v1, https://api.anthropic.com/v1 | Base URL; one without a path gets /v1. llm-hosted-agent://host is plain HTTP |
api_key | none | Authorization: Bearer (openai) or x-api-key (anthropic) |
model | required | Model name |
system | none | Template of the instructions |
prompt | required | Template of the user input |
messages_from_payload | false | The payload is the input (openai) or messages (anthropic) array, in place of prompt |
mcp_servers | none | List of {name, url, token, allowed_tools}; token is the bearer token the provider sends to the server |
max_tokens | 16000 for anthropic | Most tokens of one answer |
json | false | Parse the answer as JSON; openai is also asked for a JSON object |
answer | text | full: the whole response |
options | none | Further request fields, e.g. {temperature: 0}; tools is added to the MCP tools. JSON text in a URI |
concurrency | 8 | Requests in flight for one batch |
request_timeout_ms | see openai_embeddings | Timeout of one request |
tls, auth | none | As on http_bulk |
The MCP servers must be reachable from the provider, not from mq-bridge. A
local model has no such loop; to try the endpoint without a key, point url
at a stub server. On the command line the scheme is llm-hosted-agent://, with
mcp_servers as JSON text:
llm-hosted-agent+https://api.anthropic.com?provider=anthropic&model=…&prompt=…&mcp_servers=[{"name":"docs","url":"https://…"}].
llm_agent
llm_agent runs the tool loop in mq-bridge: it asks the model, calls the tools the
model asks for, hands the results back and asks again, until the model answers
without a tool call. A tool is an endpoint that answers, such as an http request or
a lookup-able database, or a tool of an MCP server, reached over Streamable HTTP
(url) or started as a local process that speaks MCP on stdin and stdout (command).
Unlike llm_hosted_agent, the tools need not be reachable from the provider, and any
model with tool calls works. It needs a build with the llm-agent feature (in the full
plugin).
output:
request:
to:
llm_agent:
provider: openai_chat # or openai, anthropic
url: http://localhost:11434 # Ollama
model: qwen3:8b
system: "Answer from the order system only."
prompt: "${payload:question}"
max_rounds: 8
tools:
- name: get_order
description: "Looks up an order by its id"
schema: { type: object, properties: { id: { type: string } }, required: [id] }
endpoint: { http: { url: "http://orders.internal/api/lookup" } }
mcp_servers:
- name: docs
url: https://developers.openai.com/mcp
- name: files
command: npx
args: ["-y", "@modelcontextprotocol/server-filesystem", "/srv/docs"]
allowed_tools: [read_text_file, search_files]
forward_to: { file: { path: "answers.jsonl", format: payload } }
provider | API | Also serves |
|---|---|---|
openai (default) | POST /responses | Azure OpenAI, xAI, Groq: set url |
anthropic | POST /messages | |
openai_chat | POST /chat/completions | Ollama, vLLM, Groq, Mistral, DeepSeek, Bedrock; Gemini at https://generativelanguage.googleapis.com/v1beta/openai, Cohere at https://api.cohere.ai/compatibility/v1 |
The Gemini and Cohere compatibility APIs were checked for their configuration only, not run.
An endpoint tool gets the call’s arguments as its JSON payload; its answer is the result. An MCP tool is called with the arguments; the text parts of its result are the result. Tool names must be unique across all tools and servers. Each round sends the whole conversation in the provider’s own format, so reasoning items, thinking blocks and their signatures go back unchanged.
| What happens | Outcome |
|---|---|
| A tool fails for good, is unknown, or gets arguments that are not a JSON object | The error goes back to the model as the tool’s result; the loop goes on |
| A tool fails retryably (connection lost) | The message fails retryably; a retry runs the whole loop again |
| A tool’s endpoint gives no answer | The message fails for good |
The model stops with refusal, max_tokens/length or no text | The message fails for good |
max_rounds model calls and still tool calls | The message fails for good |
Because a retry starts the conversation over, a tool that writes should be idempotent.
The answer is the final text (parsed with json: true), or with answer: full the whole
conversation as a JSON array. It carries llm_rounds, llm_input_tokens and
llm_output_tokens as metadata. options.tools adds provider tools, such as
web_search, that the provider runs itself.
command starts a program from the configuration, with the rights of mq-bridge. Accept
it only from configurations you trust; a route started through the app’s MCP server can
carry one too.
Amazon Bedrock
Bedrock serves the chat completions API at
https://bedrock-runtime.<region>.amazonaws.com/openai/v1. Use a Bedrock API key as
api_key, or sign the requests with the AWS credentials of the environment (needs a build
with the aws feature):
output:
request:
to:
openai_chat:
url: https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1
auth:
aws_sigv4: { region: us-west-2, service: bedrock }
model: openai.gpt-oss-20b-1:0
prompt: "Summarise: ${payload:text}"
forward_to: { file: { path: "summaries.jsonl", format: payload } }
llm_agent takes the same url and auth with provider: openai_chat, so mq-bridge runs
the tool loop against a Bedrock model.
This was checked for its configuration only, not run against Bedrock.
From Rust
OpenAiChatConfig, OpenAiEmbeddingsConfig and LlmHostedAgentConfig are the typed forms of the
tables above. Each converts into an Endpoint; it needs the http-bulk
feature and no registration.
use mq_bridge::endpoints::http_bulk::OpenAiChatConfig;
use mq_bridge::models::Endpoint;
let llm: Endpoint = OpenAiChatConfig {
model: "gpt-4o-mini".into(),
prompt: "Summarise: ${payload:text}".into(),
..Default::default()
}
.into();
What to know
- Templates are escaped. Text taken from a message is JSON-escaped, so a quote or a line break in it cannot break the request.
- Thinking models look hung. Ollama lets a model such as
qwen3.5reason before every answer. Setoptions: { reasoning_effort: none }; Ollama ignoresthink: falsehere. - A temporary error fails only its message. 408, 429 and 5xx are retryable.
List
retryafter thelookup; it repeats only the messages that failed, so answers already paid for are kept. - One request per batch means one fate per batch for embeddings. A request
the API refuses fails every message in it. OpenAI refuses an empty text, so
drop such messages with a
filterfirst. - Vectors are matched by position. The API must answer in input order, which OpenAI documents. A response with another number of vectors fails the batch for good.
- Batch size is the request size. OpenAI takes at most 2048 texts per
embeddings request; keep the route’s
batch_sizeat or below your provider’s limit. - It works on Android. HTTPS there checks the server against the Mozilla
roots built into mq-bridge; no JNI setup is needed. Behind a proxy with its
own CA, set
tls.ca_file. - Nothing is cached. A replayed message is sent, and billed, again. Use
deduplicationbefore the lookup if that matters. - Streaming works for other APIs too.
openai_chatsetsstream_to, see above; for another API, such as Anthropic’s, usehttp_bulkwithstream_to.
Both endpoints are the generic http_bulk query with the
requests filled in. An API with another shape, such as Anthropic’s
/v1/messages, is a query with per_message: true:
output:
http_bulk:
url: https://api.anthropic.com
headers:
x-api-key: <api key>
anthropic-version: "2023-06-01"
query:
path: /v1/messages
format: json_array
per_message: true
request: '{"model":"claude-haiku-4-5","max_tokens":256,"messages":[{"role":"user","content":"${payload:text}"}]}'
value: /content/0/text
error: /error/message
Use cases with a runnable example: RAG index sync: Postgres CDC → embeddings → Qdrant and classify and route messages with an LLM.