Relay docs

Agents API

POST /v1/agents/{id}/chat/completions — run a stored agent. The request body is a normal chat completion payload, but the agent supplies the model, system prompt (free-text or a library prompt), skills, tools/MCP and optional knowledge-base retrieval. The model field in your body is ignored.

See Agents for how to compose one.

An agent whose model is realtime-capable can also be spoken to — see Realtime.

Three kinds of agent need the acting end user in X-Relay-User-Id (an Entra object id; X-User-Id is accepted as a legacy alias), and it is the same header in every case, so an agent that is two of these needs one header, not two:

  • A dataset agent, which also needs the data.query scope on the key, cannot stream, and returns a relay_dataset object with the SQL that ran and the rows it returned. See Dataset agents.
  • A connector agent, whose tools read that user's own Microsoft 365 account and which needs the connectors.use scope. See Connectors.
  • An agent that is not public, where the gateway checks the user against the agent's creator and its share list. See Agents for how the audience is set and why that id and not another.

Without the header these return 400 user_header_required; without the scope, 403 insufficient_scope.

#List agents

GET /v1/agents — the agents this key can run, so an app can discover them instead of hard-coding ids.

curl http://localhost:5300/v1/agents \
  -H "Authorization: Bearer $RELAY_API_KEY" \
  -H "X-Relay-User-Id: $END_USER_ID"

The user header is optional here even though a private agent's run requires it: listing without one returns the public agents, which is the useful answer for a client that has not yet picked a user.

{ "object": "list", "data": [
  {
    "id": "a1b2c3…",
    "name": "support-assistant",
    "description": "Answers returns and delivery questions",
    "model": "gpt-4o",
    "model_allowed": true,
    "realtime": false,
    "published_version": 3,
    "grounded": true,
    "retrieval_top_k": 4,
    "skills": 2,
    "skills_when_needed": 1,
    "tools": 1,
    "mcp_servers": 0,
    "dataset": false,
    "connectors": false,
    "public": true,
    "requires_user_header": false,
    "user_header": null,
    "temperature": 0.3,
    "max_tokens": 800,
    "pii_redaction": false,
    "web_search": false,
    "workflows": 0,
    "working_loop": false,
    "can_send_outside": false,
    "connector_ready": null
  }
] }

Only enabled agents appear, and only those that are global (no workspace) or owned by the key's workspace — the same visibility rule as the prompt library. Non-public agents appear only when X-Relay-User-Id names their creator or a user they are shared with.

A few fields are worth knowing:

FieldMeaning
model_allowedfalse when the key's model allow-list excludes the agent's model, so a run would return 403 model_not_allowed. Reported rather than filtered on — an agent hidden for this reason looks deleted, while an unexplained 403 looks like a bug.
realtimeWhether the agent's model speaks the bidirectional-audio protocol, so the agent can be opened as a voice session. Reported here because the agent's model may not be in the key's own GET /v1/models view, so an app offering a "talk to an agent" picker could otherwise only discover the answer from a 400 unsupported_capability after the user had already chosen. Filter on this, unlike model_allowed — an agent that cannot be spoken to is not a permissions problem to explain, it simply has no voice option.
published_versionThe published version that will actually run. Null means the live draft is in effect, because a run prefers a published snapshot whenever one exists.
groundedWhether a knowledge base is attached. retrieval_top_k is present only when it is — otherwise it is a stored default that never takes effect.
publicfalse when the agent is shared with named users rather than open to every caller. Because the listing already omits the ones this user may not run, a false here means "you can see this because the user you named created it or was shared it", not "you might be refused".
dataset / connectorsWhether a dataset is pinned / a connector is attached — the two kinds of agent that act as the end user and need an extra scope.
requires_user_headerWhether a run needs X-Relay-User-Id. True for a dataset agent (to resolve per-user data access), a connector agent (its tools act as that user) or a non-public one (to check the share list); any one reason is enough, and user_header gives the header name.
web_searchWhether the agent can search the web during a run. Needs no extra scope or header. See Agents.
skills / tools / mcp_servers / workflowsCounts, not ids. workflows is the workflows the agent can run as tools.
skills_when_neededHow many of skills are set to Load when needed; the rest are Always on.
working_loopWhether Working loop is on. Such an agent streams when asked, a dataset agent included.
can_send_outsidetrue when a run can carry what it is sent outside the company: web_search, connectors, mcp_servers > 0 or workflows > 0. An app can ask its user before sending data to such an agent. Drafting workflows does not count, since a draft is saved switched off and runs nothing.
connector_readyFor an agent with connectors, listed with X-Relay-User-Id: true when that user has a working connection on every connector the agent uses, false when one is missing or needs reconnecting. null when the agent has no connectors or no user was named. An app can offer "connect your account" before the question instead of an error after it.
connect_urlThe control panel's Connectors page, where the user connects. Present only beside connector_ready: false, and only when the gateway knows the panel's address (Gateway:PanelBaseUrl).

This is a directory, not a definition: the system prompt, the prompt id and the skill / tool / MCP ids are deliberately not returned. They are authoring detail, the prompt can carry sensitive instructions, and the ids name resources that may belong to another team. Nothing but id is needed to invoke an agent. Compose and inspect agents in the panel under Agents.

#Request

curl -X POST http://localhost:5300/v1/agents/AGENT_ID/chat/completions \
  -H "Authorization: Bearer $RELAY_API_KEY" -H "Content-Type: application/json" \
  -d '{
        "messages": [{ "role": "user", "content": "How do I return an item?" }],
        "stream": false
      }'
  • The agent's settings win. Its model replaces whatever model you send, its temperature and max tokens apply as defaults, and if it has tools of its own they replace any tools in your body.
  • The message is optional. If the agent's prompt already contains the user turn (a chat-type prompt), or the system prompt is self-contained, you can omit it.
  • Variables. If the agent's prompt has {{variables}}, pass them as a top-level variables object; the gateway compiles the system prompt before running (the variables are not forwarded upstream):
{ "messages": [{ "role": "user", "content": "…" }],
  "variables": { "company": "Spinneys", "language": "English" } }
  • Attachments. A top-level file_ids array names uploaded files. A text file's text is injected after any retrieved knowledge, and the agent's PII redaction applies to it; an image is added to your last user message as an image part. An unreadable id fails the run with 404 file_not_found rather than being skipped.
  • Images go in as content parts exactly as on chat completions, or by id in file_ids. The agent's model needs vision: otherwise the run is refused with 400 vision_not_supported, naming the model, before retrieval or the model call spend anything. A thread remembers its images (see Conversation memory).

#Conversation memory

Add ?thread=<id> to give the agent multi-turn memory. Prior turns for that thread are prepended, and this turn is persisted afterwards (only on success, and only role + content). Images are kept as references to uploaded files, never as bytes: one sent inline is stored as an image file first. On later turns the five most recent images go to the model again as images, older ones as a note such as "[image shelf_3.jpg]", every one as a note for a model without vision, and one whose file has expired or been deleted as "[image no longer available]". The response includes X-Relay-Thread-Id, and the thread id doubles as the trace's session id unless you sent X-Relay-Session-Id yourself. A threaded call can stream (see Streaming vs. tool loop): the reply is saved once the stream has ended with success, and a failed or cancelled stream saves nothing.

POST /v1/agents/{id}/chat/completions?thread=my-thread-123

Threads are visible in the panel under Conversations.

#Deleting threads

An app that deletes a conversation on its side can make the agent forget it too. Both calls need the chat.completions scope and soft-delete, as the panel does. A later call with the same thread id starts that thread over, empty.

DELETE /v1/threads/{id}
DELETE /v1/threads?prefix={prefix}
  • DELETE /v1/threads/{id} deletes one thread of the key's workspace, or one with no workspace. It answers 204 when it deleted the thread, and 404 thread_not_found when there was nothing to delete.
  • DELETE /v1/threads?prefix= deletes every thread of the key's workspace whose id starts with the prefix, for an app that names its threads after its own conversation ({conversationId}:{agentId}). The prefix must be at least 16 characters, or the call fails with 400 prefix_too_short, so a short prefix cannot sweep the whole workspace. It answers { "deleted": n }, and threads with no workspace are left alone.

#Tools & MCP

If the agent has MCP servers, workflows, a connector, a dataset or a skill set to Load when needed attached, the gateway runs a tool loop: it calls the model, executes any requested tool itself, feeds the result back, and repeats. The budget is Gateway:ToolMaxIterations (default 5) for MCP and workflow tools, Gateway:Connectors:MaxIterations (default 8) for a connector agent and Gateway:Data:MaxIterations (default 6) for a dataset agent. The skill tools relay_load_skill and relay_read_skill_file count against Gateway:ToolMaxIterations. Plain registry tools (no backend of their own) are advertised to the model, and their tool_calls are returned to you to execute. A registry tool whose name collides with an attached workflow or connector tool fails the run with 409 tool_name_conflict. See Skills, tools & MCP.

#Working loop (harness mode)

Turn on Working loop in the agent editor and the agent keeps working until it has the answer. Each step is one model call: it plans (relay_update_plan), calls its tools, reads the results, and decides what to do next. The run ends only when the agent calls relay_finish (an answer plus up to three suggested follow-ups) or relay_ask_user (one question, with likely answers as options). If it replies in plain text, it is nudged once to finish properly. If it runs out of steps, it gets one last call to answer with what it has, and the response is marked incomplete. Steps default to 12 per question, can be set per agent up to 40, and the server-wide default is Gateway:Harness:MaxSteps. The relay_* tools never leave the gateway, and an attached tool with one of those names fails the run with 409 tool_name_conflict.

The message content is always readable text (the answer, or the question), so a plain OpenAI client keeps working. Clients that want more read relay_harness on the response:

"relay_harness": {
  "status": "answered",            // answered | needs_input | incomplete | handed_back
  "steps": 4,
  "tool_calls": 3,
  "suggestions": ["Break it down by region", "Compare with last year"],
  "question": null,                // { "text", "options": [] } when status is needs_input
  "plan": [{ "step": "Query sales", "status": "done" }],
  "workflows_created": null        // [{ "id", "name", "valid" }] when the agent drafted workflows
}

The status is also sent as the X-Relay-Harness-Status header (JSON responses only). To answer a question, send the user's reply as the next turn. With ?thread=, the thread keeps the run's tool calls and results, and later turns see them as a short note, so the agent remembers what it already looked up. Inside a workflow's Agent node the agent is not offered relay_ask_user, since nobody is there to answer, and the node's output gains harnessStatus, steps and suggestions. A run's usage is the whole run's (every model call), not the last call's.

#Streaming a harness run

Send "stream": true and the run comes back as server-sent events. A dataset agent with Working loop on can stream too. The stream is OpenAI-shaped, so any OpenAI client reads it:

  • data: lines carrying chat.completion.chunk objects. The first has delta.role, then delta.content pieces carry the answer (or the question), then a closing chunk carries finish_reason, the run's usage and the same extras a JSON response has: relay_harness, relay_dataset, relay_web_search, relay_connectors_needed. Then data: [DONE].
  • The answer is sent once the run knows it, in pieces, not token by token: it arrives whole inside the relay_finish call.
  • A turn handed back to the caller sends its tool_calls in a delta, with finish_reason: "tool_calls".
  • A failure after the stream started is a data: {"error": {...}} line, then [DONE].
  • While the run works, each model call writes an SSE comment (: working), which keeps proxies from timing out a quiet run.

Progress events. Add "relay_events": true to the request to also receive the run's progress as named events. Each is event: relay.harness with a JSON data: object whose type says what happened. They are opt-in because a reader that treats every data: line as a chunk would trip over them.

typeFieldsWhen
run.startedmax_steps, harnessBefore the first model call.
step.startedstepA model call begins (1-based).
step.finishedstep, duration_ms, prompt_tokens, completion_tokens, cost_usd, model, tool_calls (names requested)The model call returned.
planstep, plan ([{step, status}])The agent stated or updated its plan.
tool.startedstep, call_id, name, backend (dataset_sql, mcp, connector, workflow, workflow_draft, unavailable…), arguments (JSON string)The gateway starts running a tool.
tool.finishedstep, call_id, name, duration_ms, failed, result (first 600 characters)The tool returned. failed is true for an error result.
nudgestep, reason (plain_text, out_of_steps)The harness told the agent to finish properly.
control.rejectedstep, name, problemA malformed relay_finish / relay_ask_user was sent back to the agent.
run.finishedstatus, report (the relay_harness object)After the closing chunk, before [DONE].
errormessage, error_type, codeBefore the error chunk.

Stopping is closing the connection: the gateway cancels the run.

Drafting workflows. With Can draft workflows also on, the agent gets relay_list_workflow_nodes (the node catalogue) and relay_create_workflow. A submitted graph goes through the same validation as the editor. If it has errors, nothing is saved and the errors go back to the agent so it can fix them within the same run. A valid workflow is saved in the caller's workspace disabled, with API access off, so a person reviews and turns it on in the editor before it can run.

#Streaming vs. tool loop

  • An agent with none of the above (no MCP, workflow, connector or dataset) and no working loop streams like a normal chat call, with or without ?thread=. With a thread, the history is prepended as usual, X-Relay-Thread-Id is sent with the headers, and the reply is saved to the thread once the stream ends with [DONE].
  • An agent whose only gateway-run tools are its skill tools streams too. Each model call is streamed: its text reaches you as it is written, while a skill call is run inside Relay and the loop goes on. Text from more than one call (a model that says what it is about to check, then answers) arrives as one answer with a blank line between the parts. A call to a registry tool ends the stream with those tool_calls, as on a plain stream. The last chunk carries finish_reason, the run's usage and relay_skills, then [DONE].
  • An agent with Working loop on streams its run when asked (see Streaming a harness run).
  • Otherwise the run is non-streamed and returns a single JSON completion: stream: true is ignored, except for a dataset agent, which refuses it with 400 stream_not_supported so the caller knows.

#Response

Standard chat completion shape, plus relay_skills when the agent loaded a skill or read a skill file ({ "loaded": [{ "skill": "refund-policy", "name": "Refund policy" }], "files_read": [{ "skill": "refund-policy", "path": "reference/limits.md", "kind": "reference" }] }), plus relay_connectors_needed when a connector tool call found the user not connected (see Connectors), plus relay_web_search on a non-streamed run of a web search agent that searched (queries, pages found, citations and billed search count, summed over the tool loop — the shape is in Chat completions), plus X-Relay-Request-Id, X-Relay-Trace-Id, X-Relay-Observation-Id, X-Relay-Cost-Usd (non-streamed runs only), X-Relay-Cache when caching is on, X-Relay-Thread-Id for threads, and X-Relay-Dataset-Id / X-Relay-Sql-Queries / X-Relay-Rls-Applied for a dataset agent.