--- title: Quickstart description: Make your first SubQ API request, a decision with SubQ Snap or text with SubQ Savant. --- [Create API key](https://console.subq.ai/api-keys) ## Save your API key ```bash export SUBQ_API_KEY="your_api_key_here" ``` ## Make your first request ### SubQ Snap Ask yes/no, choice, and score questions about text and images. Get typed answers with probabilities. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/systemone \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-snap-1.3", "state": "Asthma patient, short of breath since breakfast.", "questions": { "escalate": { "type": "noul", "instructions": "Should a nurse see this today?" } } } ' ``` ```ts title="TypeScript" const baseURL = "https://api.subq.ai/v1"; const response = await fetch(`${baseURL}/systemone`, { method: "POST", headers: { Authorization: `Bearer ${process.env.SUBQ_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "subq-snap-1.3", state: "Asthma patient, short of breath since breakfast.", questions: { escalate: { type: "noul", instructions: "Should a nurse see this today?", }, }, }), }); if (!response.ok) throw new Error(await response.text()); const { answers } = await response.json(); console.log(answers.escalate.noul); // probability of yes, 0 to 1 ``` ```py title="Python" import os import httpx2 # pip install httpx2 base_url = "https://api.subq.ai/v1" api_key = os.environ["SUBQ_API_KEY"] body = { "model": "subq-snap-1.3", "state": "Asthma patient, short of breath since breakfast.", "questions": { "escalate": { "type": "noul", "instructions": "Should a nurse see this today?", }, }, } response = httpx2.post( f"{base_url}/systemone", headers={"Authorization": f"Bearer {api_key}"}, json=body, timeout=60, ) response.raise_for_status() answers = response.json()["answers"] print(answers["escalate"]["noul"]) # probability of yes, 0 to 1 ``` [Make a decision](/using-the-api/make-a-decision/) ### SubQ Savant (Preview) Generate long-context text with the OpenAI SDK. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": "Explain a force majeure clause in one sentence." } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", input: "Explain a force majeure clause in one sentence.", }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", input="Explain a force majeure clause in one sentence.", ) print(response.output_text) ``` [Generate text](/using-the-api/generate-text/) [FAQ](/using-the-api/faq/): Answers on API keys, models, billing, and data retention. [SubQ Playground](https://playground.subq.ai): Try interactive Snap decisions in the browser. [SubQ Search](https://search.subq.ai): Search large file sets with long-context Savant. --- title: Models description: Supported SubQ model IDs and what each one accepts. --- Pass the model ID in the `model` field. IDs are case-sensitive. To list the IDs available to your API key, use the [Models API](/endpoints/models-api/). Each model has a versioned ID and a `-latest` alias. The alias points to the newest version of that model and moves when a new version is released. Use the versioned ID to stay on one version. ## SubQ Snap 1.3 The default Decision model for fast, structured decisions. - Model ID: `subq-snap-1.3` - Alias: `subq-snap-latest` - Endpoint: [Decisions](/endpoints/decisions-api/) - Modalities: Text (input and output), Image (input only) - Context window: 384K tokens - Features: [Images](/using-the-api/documents-and-images/#images) - Pricing: Text input ($0.04 / 1M tokens), Image input ($0.08 / 1M tokens), Output (Free) ## SubQ Savant 1.4 The long-context model for text generation. It reads up to 4M tokens in one request and reasons before it answers. Savant is available in preview. The [Models API](/endpoints/models-api/) lists the models your API key can use. - Model ID: `subq-savant-1.4` - Alias: `subq-savant-latest` - Status: Preview - Endpoint: [Chat Completions](/endpoints/chat-completions-api/), [Responses](/endpoints/responses-api/) - Modalities: Text (input and output), Image (input only) - Context window: 4M tokens - Features: [Reasoning](/endpoints/chat-completions-api/#reasoning-effort), [Files](/using-the-api/file-inputs/), [Images](/using-the-api/file-inputs/#format-support), [Function calling](/using-the-api/function-calling/), [Structured outputs](/using-the-api/structured-outputs/) - Pricing: Text input ($0.10 / 1M tokens), Image input ($0.20 / 1M tokens), Cached input ($0.01 / 1M tokens), Output ($0.50 / 1M tokens) Rates are the same at any prompt length. - **Reasoning bills as output.** Reasoning tokens are part of `completion_tokens`. See [Reasoning effort](/endpoints/chat-completions-api/#reasoning-effort). - **Cached input bills at the cached rate.** `usage.prompt_tokens_details.cached_tokens` reports how many input tokens were served from cache. See [Usage fields](/endpoints/chat-completions-api/#usage-fields). Reading a 1M-token contract set and returning 2,000 output tokens, reasoning included, costs the input price once plus 0.2% of the output price. ### Defaults and restrictions Savant always reasons before it answers and always samples at temperature `1`. | Setting | Default | What you can send | | ----------- | -------------------- | ------------------------------------------------------------------------------------- | | Reasoning | On, at `high` effort | `low`, `high`, or `max` effort. Reasoning cannot be turned off: `none` returns `400`. | | Temperature | `1` | Omit it or send `1`. Chat Completions returns `400` for any other value. | See [Restricted parameters](/endpoints/chat-completions-api/#restricted-parameters) for every restricted parameter and the error it returns, and [Reasoning effort](/endpoints/chat-completions-api/#reasoning-effort) for choosing an effort. ## Deprecated models A deprecated model ID works as before until its shutdown date. Update your requests to the recommended replacement, or to its `-latest` alias, before then. | Deprecated model | Shutdown date | Recommended replacement | | ------------------- | ----------------- | ----------------------- | | `subq-snap-1.2` | December 4, 2026 | `subq-snap-1.3` | | `subq-preview` | November 25, 2026 | `subq-savant-1.4` | | `subq-1p2-medium` | November 25, 2026 | `subq-savant-1.4` | | `subq-snap-1.1` | November 11, 2026 | `subq-snap-1.3` | | `subq-snap-preview` | November 11, 2026 | `subq-snap-1.3` | --- title: Data retention description: How long SubQ stores prompts, completions, and conversation history. --- Inputs and outputs from [Chat Completions](/endpoints/chat-completions-api/) and [Decisions](/endpoints/decisions-api/) requests are deleted within 60 days of processing. Organizations on [zero data retention](#zero-data-retention) store nothing. Other data has no expiry: - **Conversation history.** Saved [Responses](/endpoints/responses-api/) turns stay stored. Each belongs to the conversation named in the response's `conversation.id`; [delete that conversation](/endpoints/conversations-api/#delete-a-conversation) to remove it with every turn in it. - **Inline PDF and Word files.** A PDF or Word file sent as `file_data` on Chat Completions is stored, and the API can't delete it. To control when a file is deleted, [upload it](/endpoints/files-api/) and delete it when you're done. - **Uploaded files.** Files sent to the [Files API](/endpoints/files-api/) stay until you [delete them](/endpoints/files-api/#delete-file). Content flagged for a potential violation of the Terms or Usage Policy may be kept while SubQ investigates the violation. SubQ may also keep inputs and outputs longer when the law requires it. SubQ always records model, token counts, timing, and your [`metadata`](/endpoints/chat-completions-api/#metadata) tags for billing and support. That record never includes prompts or completions. ## Zero data retention Requests work as usual, but nothing is stored afterward. To enable it for your organization, submit the [form](https://share-na2.hsforms.com/1ikOZ84D1RACcMJlibb1z9w418zam) at the bottom of this page. | Endpoint | Behavior | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | [Chat Completions](/endpoints/chat-completions-api/) | Works as usual. Nothing is stored. | | [Responses](/endpoints/responses-api/) | Works, but turns aren't saved. Send the full context in `input` on every request instead of `previous_response_id`. | | [Conversations](/endpoints/conversations-api/) | Unavailable (`403` `zero_data_retention`). | | [Decisions](/endpoints/decisions-api/) | Works as usual. Nothing is stored. | | Inline PDF and Word files (`file_data`) | Rejected (`400` `document_source_unsupported`). Upload the file and pass [`file_id`](/using-the-api/file-inputs/). | ## Zero Data Retention (ZDR) Request [Submit a ZDR request](https://share-na2.hsforms.com/1ikOZ84D1RACcMJlibb1z9w418zam) --- title: Rate limits description: Default request and token limits for each model. --- Rate limits cap how many requests and tokens your organization sends per minute, and how much work it has in flight at once. Usage is counted per organization, across all of its API keys, not per key. The table shows the default limits. The Organization page in the [console](https://console.subq.ai) shows your organization's limits for each model. | Model | Requests / min | Tokens / min | Input tokens / min | Output tokens / min | Concurrent requests | Concurrent input | Limit pool | | ----------------- | ------------------------------------- | ------------------------------------- | -------------------------------------- | -------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------- | | `subq-snap-1.3` | 1,200 | 6,000,000 | 6,000,000 | 6,000,000 | 100 | 6,000,000 | Separate | | `subq-savant-1.4` | 250 | 5,500,000 | 5,000,000 | 500,000 | 10 | 5,000,000 | Separate | ## How the limits combine Every limit in a row is checked on each request. The request is refused if it would go over any one of them. - **Tokens / min** counts input and output together. **Input tokens / min** and **Output tokens / min** each count one side. With all three at 60M, 40M input and 30M output in one minute stay under both per-side limits, but the 70M total goes over **Tokens / min**. - **Token limits use an estimate.** A request is checked against an estimate of its tokens when it arrives, and the count is corrected to actual usage when it finishes. A large request can be refused before it runs. - **Concurrent requests** counts requests that have started and not finished. **Concurrent input tokens** is the estimated input of those requests, added together. *Unlimited* means no limit is enforced. ## Limit pools The **Limit pool** column shows whether a model shares its limits with other models. - **Shared:** one pool for the organization. Every Shared model counts toward the same numbers. If `subq-snap-1.3` and `subq-savant-1.4` are both Shared, their requests add up against one Requests / min limit, not one each. - **Separate:** the model has its own limits and its own pool, matched on the exact model ID in the request. An alias such as `subq-savant-latest` does not use the separate limits of the model it points to. It counts in the shared pool unless the alias has limits of its own. ## When you hit a limit The request fails with `429` and nothing is charged. Per-minute limits reset at the start of each minute. Model requests do not return `Retry-After` or `x-ratelimit-*` headers, so time retries in your client. A `429` means either your organization exceeded a limit or the model is temporarily busy. Retry both with exponential backoff and jitter. ### Chat Completions and Responses Your organization's limit uses `error.code` `rate_limit_exceeded`. The message names the limit, such as Requests per minute or Tokens per minute. ```json { "error": { "message": "Requests per minute limit exceeded", "type": "rate_limit_error", "code": "rate_limit_exceeded" } } ``` A busy model uses `error.code` `model_rejected_request`, with the same `error.type`. ```json { "error": { "message": "The model is receiving too many requests. Please retry shortly.", "type": "rate_limit_error", "code": "model_rejected_request" } } ``` ### Decisions Decisions returns `detail.error_type` `rate_limit_error` for both causes. ```json { "detail": { "error_type": "rate_limit_error", "message": "Rate limit exceeded. Retry after a short delay." } } ``` For higher limits, [contact support](/using-the-api/support/). --- title: Release notes description: New SubQ models, API changes, and model retirements, newest first. --- ## December 4, 2026 ### SubQ Snap 1.3 SubQ Snap 1.3 is now the default Decision model. It is more accurate and faster than Snap 1.2, returns better-calibrated probabilities, and takes more images, questions, and options in one request. `subq-snap-1.3` · `subq-snap-latest` · Retired: `subq-snap-1.2` - **Higher request limits:** Send up to 16 images, 256 questions, and 2,500 options per choice question in one request, up from 4 images, 128 questions, and 255 options. - **Better calibration:** Higher overall accuracy than Snap 1.2, and probabilities that more closely match how often a decision is right. - **Lower latency:** Decisions return faster than on Snap 1.2. - **Image pricing:** Image input tokens now bill at twice the text input rate, $0.08 per 1M tokens. Text input stays at $0.04 per 1M tokens, and output is free. - **Drop-in upgrade:** Context window (384K tokens) and request format remain identical to Snap 1.2. - **Retired model:** `subq-snap-1.2` is now retired. Requests to it, and to the earlier `subq-snap-1.1` and `subq-snap-preview`, are routed to Snap 1.3. Update your requests to `subq-snap-latest`, or to `subq-snap-1.3` to stay on this version, to get the higher limits. Test any thresholds you rely on, as decisions and probabilities may differ. ## December 2, 2026 ### SubQ Savant 1.4 SubQ Savant 1.4 is now in public preview. Any organization can call it with an API key, with no access request. `subq-savant-1.4` · `subq-savant-latest` ## November 11, 2026 ### SubQ Snap 1.2 SubQ Snap 1.2 is now the default Decision model. It brings higher accuracy across decision and long-context benchmarks and eliminates order sensitivity for choice questions. `subq-snap-1.2` · `subq-snap-latest` · Retired: `subq-snap-1.1`, `subq-snap-preview` - **Improved consistency:** Choice questions now return identical decisions regardless of option ordering. - **Higher accuracy:** Better performance across decision and long-context evaluation benchmarks. - **Drop-in upgrade:** Context window (384K tokens), image input, request format, and pricing remain identical to Snap 1.1. - **New model alias:** Use `subq-snap-latest` to automatically point to the newest Snap model. - **Retired models:** `subq-snap-1.1` and `subq-snap-preview` are now retired, and requests to them are routed to Snap 1.2. Update your requests to `subq-snap-1.2` or `subq-snap-latest`, and test any thresholds you rely on, as decisions and probabilities may differ. ### SubQ Savant 1.4 SubQ Savant, previously SubQ Preview, entered early access as a long-context model for text generation. It reads up to 4M tokens in one request and reasons before it answers. Input costs $0.10 per 1M tokens, cached input $0.01, and output $0.50. `subq-savant-1.4` · `subq-savant-latest` · Deprecated: `subq-preview`, `subq-1p2-medium` - **New model IDs:** Use `subq-savant-1.4`, or the `subq-savant-latest` alias to automatically point to the newest Savant model. - **Deprecated models:** `subq-preview` and `subq-1p2-medium` shut down on November 25, 2026, after which requests to them return an error. `subq-preview` already serves Savant 1.4, so switching the ID does not change the model you call. Update your requests to `subq-savant-1.4` or `subq-savant-latest` before then. - **Temperature is fixed at 1:** On Chat Completions, a `temperature` other than `1` now returns `400` `unsupported_value`. Omit the field or send `1`. - **Reasoning is always on:** A request that turns reasoning off, such as `reasoning_effort` set to `none`, now returns `400` `unsupported_value`. Use `low` for the least reasoning. ## October 22, 2026 ### SubQ Snap 1.1 SubQ Snap 1.1 is the new default Decision model, in public preview. Input costs $0.04 per 1M tokens and output is free. Snap Preview input drops to the same price. `subq-snap-1.1` · `subq-snap-preview` ## October 2, 2026 ### SubQ Snap Preview SubQ Snap Preview launches in the Decisions API. Send a state and typed questions, and get back yes/no, choice, and score decisions with probabilities. `subq-snap-preview` · `/v1/systemone` --- title: FAQ description: Answers to common questions about SubQ Savant, from setup and pricing to rate limits, data, and the model. --- ## Access and setup ### How do I get started with Savant? Sign up at [console.subq.ai](https://console.subq.ai), create an API key and follow the [Quickstart](/) to make your first request. ### How do I create and use an API key? Create a key on the [API keys page](https://console.subq.ai/api-keys) of the console, then send it as a Bearer token: `Authorization: Bearer $SUBQ_API_KEY`. ### Which model ID should I use? `subq-savant-1.4` for text generation, or `subq-snap-1.3` for the Decisions API. Use `subq-savant-latest` or `subq-snap-latest` to always get the newest version of that model. See [Models](/using-the-api/models/). ### Does Savant work with the OpenAI SDK? Yes. The SubQ API is OpenAI-compatible: set the SDK's base URL to `https://api.subq.ai/v1` and pass your SubQ API key. Savant supports the Chat Completions and Responses APIs. ### Can I use Savant in a coding agent? Yes, in any coding agent that accepts an OpenAI-compatible provider. Set the base URL to `https://api.subq.ai/v1`, the API key to your SubQ key, and the model to `subq-savant-latest`. [Use Savant in a coding agent](/cookbook/coding-agents/) has setup steps for OpenCode, VS Code, and Codex. ### What's the difference between Savant and Snap? Savant is the long-context model for text generation: it reads up to 4M tokens in one request and reasons before it answers. Snap is the Decision model: it answers yes/no, choice and score questions with typed answers and probabilities. One API key works for both. ## Pricing, credits and billing ### How much does Savant cost? See [pricing](/using-the-api/models/#subq-savant-14) for the most up-to-date information. ### Do credits expire? Credits you purchase don't expire. Promotional and free credits can expire, under the terms shown when they're offered. ### Is there a subscription or coding plan? No. Savant is pay-as-you-go: you pay per token, with no subscription. ### Where do I find my receipts? A receipt is emailed to your organization's billing email after each purchase; by default, that's the owner's email. Organization owners can download receipts from the Stripe portal, opened from the [Billing page](https://console.subq.ai/billing) of the console. ### How do I check my credit balance and spend? Your credit balance and total spend are on the Overview page of the [console](https://console.subq.ai). ## Rate limits and concurrency ### What are the default rate limits? See [Rate limits](/using-the-api/rate-limits/) for the most up-to-date information. The Organization page in the [console](https://console.subq.ai) shows your organization's limits. ### Can I get higher rate limits? [Contact support](/using-the-api/support/) with your use case and expected volume. SubQ reviews requests case by case. ### How do I avoid `429` errors when running several agents at once? Limits are counted per organization. Keep the number of in-flight requests under your concurrent request limit. A request that fails with `429` isn't charged. [Contact support](/using-the-api/support/) with your use case and expected volume. SubQ reviews requests case by case. ## Data, privacy and ZDR ### Is my data used for training? No. SubQ doesn't use customer content to train or improve its models. ### How long does SubQ keep my prompts and outputs? Chat Completions and Decisions inputs and outputs are deleted within 60 days of processing. Responses API conversations and uploaded files are kept until you delete them. Content flagged for a potential policy violation, or that the law requires SubQ to keep, can be held longer. [Data retention](/using-the-api/data-retention/) has the full breakdown. ### What is zero data retention (ZDR), and how do I get it? With ZDR, SubQ doesn't store your prompts or outputs after a request finishes. It's enabled per organization on request and subject to approval: [submit a ZDR request](/using-the-api/data-retention/#zdr-request-form). ### Can I delete data I've already sent? Yes. Delete saved Responses conversations and uploaded files through the API. For anything else, [contact support](/using-the-api/support/); other stored inputs and outputs are deleted within 60 days in any case. Turning on ZDR doesn't remove data stored before it was enabled. ### Does SubQ offer a Data Processing Agreement (DPA)? Yes. The [DPA](https://subq.ai/data-processing-agreement) is part of the Terms and applies automatically, including to self-serve accounts. No separate signature is needed. ## Model, context and performance ### How large is Savant's context window? What about 12M tokens? 4M tokens, shared between input and output. The 12M-token figure is a research result that's still in development. We will continue to monitor the feasibility of a 12M token context window for our customer's production use cases. ### How do I get faster responses from Savant? Savant always reasons before it answers, and reasoning takes time. Set reasoning effort to `low` for the fastest responses and the fewest reasoning tokens. Reasoning can't be turned off. See [Reasoning effort](/endpoints/chat-completions-api/#reasoning-effort). ### Does Savant support images, files, function calling and structured outputs? Yes. Savant takes text and images as input and returns text. It supports [file inputs](/using-the-api/file-inputs/) such as PDF and Word documents, [function calling](/using-the-api/function-calling/) and [structured outputs](/using-the-api/structured-outputs/). Send an image inline through [Chat Completions](/endpoints/chat-completions-api/#images), or upload it and pass its `file_id` in a Responses [`input_image`](/endpoints/responses-api/#uploaded-images) part. --- title: Support description: Get help with the SubQ API, billing, or your account. --- Email or chat with us in the [console](https://console.subq.ai): the chat button is in the bottom-right corner. We can help with: - **API / product** — errors, unexpected output, or how to call an endpoint. - **Billing** — credits, invoices, or `402` responses. - **Data deletion / privacy** — deleting stored data or questions about [data retention](/using-the-api/data-retention/). - **Zero data retention** — use the [ZDR request form](/using-the-api/data-retention/#zdr-request-form) to turn it on. - **Security** — report a vulnerability or security concern. ## For API errors Include as much of this as you can. It helps us find the problem faster. - **Request ID** — the `x-request-id` response header. In OpenAI SDKs it's `request_id` (Python) or `requestID` (TypeScript) on the error. The [Files API](/endpoints/files-api/) doesn't return one. - **Endpoint and model** - **Status code and error body** - **When it happened**, roughly Never send your API key. --- title: Make a decision description: Ask yes/no, choice, and score questions about text, and get typed answers with probabilities. --- SubQ Snap answers questions about a `state` (text, an object, or an array) and returns typed answers with probabilities your code can act on: route a ticket, gate an action, rate how urgent something is. To generate text instead, see [Generate text](/using-the-api/generate-text/). ## Pick a question type | Type | Asks | Answer | | -------- | ----------------------------------- | ------------------------------------------------------------------------------ | | `noul` | A yes/no gate. | `noul`, the probability of yes from `0` to `1`. | | `choice` | Which one of 2–2,500 named options. | `choice`, a probability for every option, and `confidence`. | | `score` | A rating on 2–10 ordered levels. | `score`, which can fall between levels, plus `probabilities` and `confidence`. | ## Example A clinic's patient chat gets one message. Three questions decide what happens next: does a nurse need to see it, which team owns it, and how soon someone should reply. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/systemone \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data @- <<'EOF' { "model": "subq-snap-1.3", "state": "Patient with asthma reports a sore throat, fever since yesterday, and shortness of breath walking to the kitchen this morning.", "questions": { "escalate": { "type": "noul", "instructions": "Should a nurse see this chat before the patient books anything?", "criteria": { "true": "Breathing trouble, chest pain, or a flare of a known condition", "false": "Stable symptoms the patient can book for themselves" } }, "queue": { "type": "choice", "instructions": "Which team should own this chat?", "criteria": { "nurse_line": "Needs a nurse to assess symptoms today", "primary_care": "Book with the patient's own doctor", "pharmacy": "Refill or medication question only", "front_desk": null } }, "acuity": { "type": "score", "instructions": "How soon should someone respond?", "criteria": [ "Within a week", "Within a day", "Within an hour" ] } } } EOF ``` ```ts title="TypeScript" const baseURL = "https://api.subq.ai/v1"; // The text to judge. const state = "Patient with asthma reports a sore throat, fever since yesterday, and shortness of breath walking to the kitchen this morning."; // One question per judgment: a yes/no gate, an owning team, a response time. const questions = { escalate: { type: "noul", instructions: "Should a nurse see this chat before the patient books anything?", criteria: { true: "Breathing trouble, chest pain, or a flare of a known condition", false: "Stable symptoms the patient can book for themselves", }, }, queue: { type: "choice", instructions: "Which team should own this chat?", criteria: { nurse_line: "Needs a nurse to assess symptoms today", primary_care: "Book with the patient's own doctor", pharmacy: "Refill or medication question only", front_desk: null, }, }, acuity: { type: "score", instructions: "How soon should someone respond?", criteria: ["Within a week", "Within a day", "Within an hour"], }, }; const response = await fetch(`${baseURL}/systemone`, { method: "POST", headers: { Authorization: `Bearer ${process.env.SUBQ_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "subq-snap-1.3", state, questions, }), }); if (!response.ok) { const error = await response.json(); throw new Error( `${response.status} ${error.detail.error_type}: ${error.detail.message}`, ); } const result = await response.json(); const { escalate, queue, acuity } = result.answers; // Your code decides what happens next. Unsure routing goes to a nurse, // and so does anything the gate says needs one. let owner = queue.confidence >= 0.6 ? queue.choice : "nurse_line"; if (escalate.noul >= 0.5) owner = "nurse_line"; const respondWithin = acuity.legend[String(Math.round(acuity.score))]; console.log(`Escalate: ${escalate.noul.toFixed(2)}`); console.log( `Owner: ${owner} (model picked ${queue.choice}, confidence ${queue.confidence.toFixed(2)})`, ); console.log(`Respond: ${respondWithin}`); ``` ```py title="Python" import os import httpx2 # pip install httpx2 base_url = "https://api.subq.ai/v1" # The text to judge. state = ( "Patient with asthma reports a sore throat, fever since yesterday, and " "shortness of breath walking to the kitchen this morning." ) # One question per judgment: a yes/no gate, an owning team, a response time. questions = { "escalate": { "type": "noul", "instructions": ( "Should a nurse see this chat before the patient books anything?" ), "criteria": { "true": ( "Breathing trouble, chest pain, or a flare of a known condition" ), "false": "Stable symptoms the patient can book for themselves", }, }, "queue": { "type": "choice", "instructions": "Which team should own this chat?", "criteria": { "nurse_line": "Needs a nurse to assess symptoms today", "primary_care": "Book with the patient's own doctor", "pharmacy": "Refill or medication question only", "front_desk": None, }, }, "acuity": { "type": "score", "instructions": "How soon should someone respond?", "criteria": ["Within a week", "Within a day", "Within an hour"], }, } response = httpx2.post( f"{base_url}/systemone", headers={"Authorization": f"Bearer {os.environ['SUBQ_API_KEY']}"}, json={ "model": "subq-snap-1.3", "state": state, "questions": questions, }, timeout=60, ) result = response.json() if response.is_error: detail = result["detail"] raise RuntimeError( f"{response.status_code} {detail['error_type']}: {detail['message']}" ) answers = result["answers"] escalate = answers["escalate"]["noul"] queue = answers["queue"] acuity = answers["acuity"] # Your code decides what happens next. Unsure routing goes to a nurse, # and so does anything the gate says needs one. owner = queue["choice"] if queue["confidence"] >= 0.6 else "nurse_line" if escalate >= 0.5: owner = "nurse_line" respond_within = acuity["legend"][str(round(acuity["score"]))] print(f"Escalate: {escalate:.2f}") print( f"Owner: {owner} " f"(model picked {queue['choice']}, confidence {queue['confidence']:.2f})" ) print(f"Respond: {respond_within}") ``` Read each answer by its question name: - `answers.escalate.noul` is `0.92`, so a nurse sees the chat. - `answers.queue.choice` is `"nurse_line"`. - `answers.acuity.score` is `1.86`, close to "Within an hour". See [Response](/endpoints/decisions-api/#response) for the full shape. ## Build reliable decision workflows Keep your code in charge. Rules you can write down belong in code. Ask the model only for the judgment code can't make, then let code decide what happens next. - **One judgment per question.** Split a broad question into narrow ones, like the gate, owner, and deadline above. Code then combines the answers. - **Ask related questions together.** Questions about the same `state` go in one request, so the state is sent once. - **Send only what the decision needs.** Trim `state` to the relevant fields, and name the field an instruction is about. - **Set thresholds from your own data.** Run the questions over cases you've already labeled and choose cutoffs from the results. - **Send uncertain or high-impact cases to a person.** Outputs can vary between requests, so route low `confidence`, a noul near `0.5`, or a costly mistake to review. - **Retry `429` and `5xx` with backoff.** Fix a `400` or `422` before resending; a retry won't change it. ## Next steps - [Documents and images](/using-the-api/documents-and-images/): ask about a document's text or up to 16 images. - [Decisions API](/endpoints/decisions-api/): every field, limit, and error. --- title: Documents and images description: Ask SubQ Snap about a document's text, or about up to 16 images alongside it. --- SubQ Snap takes text and images, not files. Send a document's text as `state`, and add images to judge what they show. Both go in the same [Decisions API](/endpoints/decisions-api/) request as your questions. ## Documents Use a document to fact-check a claim against its source, find the passage that backs an answer, or tag a record from its text. The Decisions API takes no files. To ask about a PDF, Word file, or other document, extract its text and send it as `state`, on its own or as a field next to other data. Run OCR on scanned PDFs first. - **Label the parts.** Mark pages, sections, or passages in the text, like `[P2]` or `--- page 24 ---`, so options can name them. - **Ask where.** A choice whose options are those labels returns a probability for each location. Add an option like `not_found` for when the document doesn't say. Send the text as a `state` field, and use the labels as `choice` options: ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/systemone \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data @- <<'EOF' { "model": "subq-snap-1.3", "state": { "claim": "Under Harlow v. Pemberton (2019), a landlord must return a tenant's security deposit within 14 days of move-out, no exceptions.", "source": "Harlow v. Pemberton, State Court of Appeals (2019)\n\n[P1] Tenant Dana Harlow moved out of a two-bedroom apartment on June 1. Landlord Owen Pemberton kept her $1,800 deposit for 30 days, then returned $600 with a note that the rest covered carpet damage.\n\n[P2] We hold that Section 12 of the Residential Tenancy Act requires a landlord to return the deposit within 14 days of move-out, unless within those same 14 days the landlord sends the tenant a written, itemized list of the damage it intends to deduct. A landlord who sends the list in time may keep the listed amounts while the dispute is resolved.\n\n[P3] Pemberton sent no itemized list within 14 days. He therefore owes Harlow the full deposit and, under Section 15, a penalty equal to the amount wrongly withheld.\n\n[P4] Harlow argues that Section 12 sets a 14-day deadline \"with no exceptions,\" and that any deduction needs a court order. We disagree. The Act plainly allows deductions that are itemized in time.\n\n[P5] Judge Alvarez, dissenting: I would allow the itemized-list route only for landlords who also photographed the unit at move-in. Without that record, the 14-day deadline should apply to the whole deposit.\n\n[P6] Headnote (written by the publisher, not part of the opinion): Landlords must return deposits within 14 days." }, "questions": { "support": { "type": "score", "instructions": "How well does the source support the claim as written?", "criteria": [ "Not supported", "Partly supported", "Fully supported" ] }, "best_passage": { "type": "choice", "instructions": "Which source passage states the court's rule on the claim's subject?", "criteria": { "P1": null, "P2": null, "P3": null, "P4": null, "P5": null, "P6": null, "not_found": "No passage states it" } }, "omits_condition": { "type": "noul", "instructions": "Does the claim leave out a condition or exception that the court's holding sets?" }, "no_exceptions_source": { "type": "choice", "instructions": "Where in the source does the claim's \"no exceptions\" come from?", "criteria": { "majority": "The court's own holding or reasoning", "party_argument": "An argument the court describes and rejects", "dissent": "The dissenting judge", "headnote": "The publisher's headnote, which is not law", "not_found": "The source never says it" } } } } EOF ``` `best_passage` returns `"choice": "P2"` with a probability for every label, including `not_found`. ## Images Judge photos or screenshots alongside the text, such as checking that a listing's photos match its description, or that a screenshot shows a step is done. Send each image as base64, with no URL or `data:` prefix: ```ts title="TypeScript" import { readFileSync } from "node:fs"; const baseURL = "https://api.subq.ai/v1"; // The ticket note. The photo carries the rest: which device, and what shape it is. const state = "The number row stopped working."; // Plain base64 of the file bytes. No data: URL prefix. // PNG, JPEG, or WebP, at most 4 MiB decoded per image. const photo = readFileSync("./keyboard.jpg").toString("base64"); // One question per judgment. Every question sees the note and every image. const questions = { shows_keyboard: { type: "noul", instructions: "Does the photo show a keyboard?", criteria: { true: "A keyboard is the main object", false: "No keyboard is visible", }, }, layout: { type: "choice", instructions: "Which keyboard layout is in the photo?", criteria: { full_size: "Desktop keyboard with a numeric keypad", tenkeyless: "Desktop keyboard with no numeric keypad", laptop: "Built into a laptop", not_a_keyboard: null, }, }, wear: { type: "score", instructions: "How worn does the keyboard look?", criteria: ["Looks new", "Everyday wear", "Replace it"], }, }; const response = await fetch(`${baseURL}/systemone`, { method: "POST", headers: { Authorization: `Bearer ${process.env.SUBQ_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "subq-snap-1.3", state, images: [{ mediaType: "image/jpeg", base64: photo }], questions, }), }); if (!response.ok) { const error = await response.json(); throw new Error( `${response.status} ${error.detail.error_type}: ${error.detail.message}`, ); } const result = await response.json(); const { shows_keyboard, layout, wear } = result.answers; // A photo that is not a keyboard, or an unsure layout, goes back to the employee. if ( shows_keyboard.noul < 0.5 || layout.confidence < 0.6 || layout.choice === "not_a_keyboard" ) { console.log("Ask for a clearer photo of the keyboard."); } else { const condition = wear.legend[String(Math.round(wear.score))]; console.log(`Keyboard: ${layout.choice} (${condition})`); } ``` ```py title="Python" import base64 import os from pathlib import Path import httpx2 # pip install httpx2 base_url = "https://api.subq.ai/v1" # The ticket note. The photo carries the rest: which device, and what shape it is. state = "The number row stopped working." # Plain base64 of the file bytes. No data: URL prefix. # PNG, JPEG, or WebP, at most 4 MiB decoded per image. photo = base64.b64encode(Path("./keyboard.jpg").read_bytes()).decode("ascii") # One question per judgment. Every question sees the note and every image. questions = { "shows_keyboard": { "type": "noul", "instructions": "Does the photo show a keyboard?", "criteria": { "true": "A keyboard is the main object", "false": "No keyboard is visible", }, }, "layout": { "type": "choice", "instructions": "Which keyboard layout is in the photo?", "criteria": { "full_size": "Desktop keyboard with a numeric keypad", "tenkeyless": "Desktop keyboard with no numeric keypad", "laptop": "Built into a laptop", "not_a_keyboard": None, }, }, "wear": { "type": "score", "instructions": "How worn does the keyboard look?", "criteria": ["Looks new", "Everyday wear", "Replace it"], }, } response = httpx2.post( f"{base_url}/systemone", headers={"Authorization": f"Bearer {os.environ['SUBQ_API_KEY']}"}, json={ "model": "subq-snap-1.3", "state": state, "images": [{"mediaType": "image/jpeg", "base64": photo}], "questions": questions, }, timeout=60, ) result = response.json() if response.is_error: detail = result["detail"] raise RuntimeError( f"{response.status_code} {detail['error_type']}: {detail['message']}" ) answers = result["answers"] shows_keyboard = answers["shows_keyboard"]["noul"] layout = answers["layout"] wear = answers["wear"] # A photo that is not a keyboard, or an unsure layout, goes back to the employee. if ( shows_keyboard < 0.5 or layout["confidence"] < 0.6 or layout["choice"] == "not_a_keyboard" ): print("Ask for a clearer photo of the keyboard.") else: condition = wear["legend"][str(round(wear["score"]))] print(f"Keyboard: {layout['choice']} ({condition})") ``` ### cURL with an image `openssl base64 -A` writes the file as one line. The heredoc is unquoted so the shell encodes the file before the request is sent. Shrink the photo first so the decoded file stays under 4 MiB. ```bash curl -sS -X POST https://api.subq.ai/v1/systemone \ -H "Authorization: Bearer $SUBQ_API_KEY" \ -H "Content-Type: application/json" \ --data-binary @- < Status: Preview SubQ Savant (`subq-savant-1.4`) generates text over up to 4M tokens of context, and reasons before it answers. Call it with the OpenAI SDK, with the base URL set to `https://api.subq.ai/v1`, on either endpoint below. ## Choose an endpoint Use Chat Completions if you already have a Chat Completions client or build the message list yourself. Use Responses for multi-turn work, where SubQ keeps the history for you. | | Chat Completions | Responses API | | ------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------- | | Conversation state | You send the full `messages[]` each request | Server stores history; continue with `previous_response_id` or `conversation` | | System prompt | `system` role in messages | `instructions` (per turn, not inherited) | | Built-in web search | Not available | `tools: [{ "type": "web_search_preview" }]` | | Function calling | Nested shape (`{"type":"function","function":{...}}`) | Flattened shape (`{"type":"function","name":...}`) | | Structured outputs | `response_format` | `text.format` (flattened shape) | | File input | `file` parts (`file_data` or `file_id`) | `input_file` parts (`file_id` only) | | Image input | `image_url` parts (base64 data URI) or `file` parts (`file_id`) | `input_image` parts (`file_id` only) | | Reasoning effort | Top-level `reasoning_effort` | Nested `reasoning.effort` | | Output cap | `max_tokens` | `max_output_tokens` | | Stream terminator | `data: [DONE]` | `response.completed` event | ## Send a request On Chat Completions: ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "system", "content": "Answer questions about the contract the user provides. Cite the section you rely on. Answer in one sentence." }, { "role": "user", "content": [ { "type": "text", "text": "Section 9. Term and Termination\n9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date.\n9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice.\n9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period." }, { "type": "text", "text": "How much notice do we need to give to cancel without cause?" } ] } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); // In practice, read this from your document store or a file. const contract = `Section 9. Term and Termination 9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date. 9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice. 9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period.`; const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "system", content: "Answer questions about the contract the user provides. Cite the section you rely on. Answer in one sentence.", }, { role: "user", content: [ { type: "text", text: contract }, { type: "text", text: "How much notice do we need to give to cancel without cause?", }, ], }, ], }); console.log(completion.choices[0].message.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) # In practice, read this from your document store or a file. contract = """Section 9. Term and Termination 9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date. 9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice. 9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period.""" completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "system", "content": ( "Answer questions about the contract the user provides. Cite " "the section you rely on. Answer in one sentence." ), }, { "role": "user", "content": [ {"type": "text", "text": contract}, { "type": "text", "text": "How much notice do we need to give to cancel without cause?", }, ], }, ], ) print(completion.choices[0].message.content) ``` The answer is in `choices[0].message.content`: ```text Under Section 9.2 (Termination for convenience), you must give ninety (90) days' prior written notice to terminate without cause. ``` On Responses, the system prompt moves to `instructions` and the parts become `input_text`: ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "instructions": "Answer questions about the contract the user provides. Cite the section you rely on. Answer in one sentence.", "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "Section 9. Term and Termination\n9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date.\n9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice.\n9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period." }, { "type": "input_text", "text": "How much notice do we need to give to cancel without cause?" } ] } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", instructions: "Answer questions about the contract the user provides. Cite the section you rely on. Answer in one sentence.", input: [ { role: "user", content: [ { type: "input_text", text: "Section 9. Term and Termination\n9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date.\n9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice.\n9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period." }, { type: "input_text", text: "How much notice do we need to give to cancel without cause?" } ] } ] }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", instructions="Answer questions about the contract the user provides. Cite the section you rely on. Answer in one sentence.", input=[ { "role": "user", "content": [ { "type": "input_text", "text": "Section 9. Term and Termination\n9.1 Term. This Agreement runs for twenty-four (24) months from the Effective Date.\n9.2 Termination for convenience. Either party may terminate this Agreement upon ninety (90) days prior written notice.\n9.3 Termination for cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches it and fails to cure the breach within that period.", }, { "type": "input_text", "text": "How much notice do we need to give to cancel without cause?", }, ], }, ], ) print(response.output_text) ``` The answer is in `output_text`. The OpenAI SDKs build it from the `message` items and skip the `reasoning` item that usually comes first, so don't read `output[0]`. With tools, take the last `message` instead. See [Extracting the assistant text](/endpoints/responses-api/#extracting-the-assistant-text). ## Control reasoning and length - **Reasoning effort:** `low`, `high` (the default), or `max`. Reasoning can't be turned off. Reasoning tokens are billed as output tokens. See [Reasoning effort](/endpoints/chat-completions-api/#reasoning-effort). - **Output cap:** reasoning and the answer share one allowance, so a low cap can end before any visible answer. See [Token limits](/endpoints/chat-completions-api/#token-limits). - **Reasoning text** comes back apart from the answer. Parse only the answer. See [Reasoning output](/endpoints/chat-completions-api/#reasoning-output). ## Continue a conversation - **Chat Completions:** append the assistant's reply and the next user message to `messages`, and send the whole list again. - **Responses:** send only the new `input` with the last response's `id` as `previous_response_id`. Resend `instructions` each turn. See [Multi-turn conversations](/endpoints/responses-api/#multi-turn-conversations). ## Next steps - [Sending files](/using-the-api/file-inputs/): ask about PDFs and other documents. - [Structured outputs](/using-the-api/structured-outputs/): get JSON that matches your schema. - [Function calling](/using-the-api/function-calling/): let the model call your code. - [Use Savant in a coding agent](/cookbook/coding-agents/): set up OpenCode, VS Code, Codex, or another OpenAI-compatible agent. --- title: Sending files description: Send documents inline as base64, or upload once and reference them by file_id on Chat Completions or Responses. --- > Status: Preview Send a small, one-off file inline with Chat Completions. Upload first when you use Responses, reuse a file, or need the larger upload limit. ## Choose a method | | Inline base64 | Uploaded file | | ------------- | -------------------------------------------------------------------------- | -------------------------------------- | | Available on | Chat Completions | Chat Completions and Responses | | Request field | `file_data` | `file_id` returned by `POST /v1/files` | | Best for | One-off files | Reuse, Responses, and larger files | | Size | 25 MiB for the whole request, base64 included (about 18 MiB of file bytes) | 50 MiB per file; 10 MiB per image | | Retention | Follows the request policy; inline PDF and Word persist | Kept until you delete the file | See [Data retention](/using-the-api/data-retention/) for storage details. ### Format support | Format | Inline Chat | Uploaded Chat | Uploaded Responses | | ---------------------------------------------- | ----------- | ------------- | --------------------- | | PDF, Word, text, Markdown, CSV, TSV, JSON, XML | Yes | Yes | Yes | | PNG, JPEG, WebP | Yes | Yes | Yes, as `input_image` | | JSONL | No | Yes | Yes | - **Responses images:** send an uploaded image as `{ "type": "input_image", "file_id": "file_img456" }`. See [Uploaded images](/endpoints/responses-api/#uploaded-images). - **Word:** keep a `.doc` or `.docx` filename so SubQ can detect the format. - **Uploaded non-text files:** wait for `status: "processed"` before using the ID. ## Inline base64 Inline `file_data` is Chat Completions only. Pass raw base64 with no line wrapping or `data:` prefix. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Summarize this report." }, { "type": "file", "filename": "report.pdf", "file_data": "JVBERi0xLjcKJdDUxdgK..." } ] } ] } ' ``` ```ts title="TypeScript" import { readFileSync } from "node:fs"; import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const report = readFileSync("./report.pdf").toString("base64"); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: [ { type: "text", text: "Summarize this report." }, { type: "file", filename: "report.pdf", file_data: report, }, ], }, ], }); console.log(completion.choices[0].message.content); ``` ```py title="Python" import base64 import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) with open("./report.pdf", "rb") as handle: report = base64.b64encode(handle.read()).decode("ascii") completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "user", "content": [ {"type": "text", "text": "Summarize this report."}, { "type": "file", "filename": "report.pdf", "file_data": report, }, ], } ], ) print(completion.choices[0].message.content) ``` Use the flat file part shown above for every supported inline format: ```json { "type": "file", "filename": "report.pdf", "file_data": "" } ``` For OpenAI compatibility, PDFs also accept a nested `file` object. Nested file parts are PDF-only and accept raw base64 or a `data:application/pdf;base64,` URI. ```json { "type": "file", "file": { "filename": "report.pdf", "file_data": "" } } ``` | Field | Required | Description | | ----------- | ----------- | -------------------------------------------------------------- | | `filename` | Recommended | Required for Word; use a `.doc` or `.docx` extension. | | `mime_type` | No | If omitted, SubQ detects the type from the bytes and filename. | | `file_data` | Yes | Base64-encoded file bytes. | Use exactly one source per file part: `file_data` or `file_id`. ## Uploaded files Upload through the [Files API](/endpoints/files-api/) with purpose `assistants`, then use the returned ID. The example IDs below represent values returned by `POST /v1/files`. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": [ { "type": "input_file", "file_id": "file_abc123" }, { "type": "input_file", "file_id": "file_def456" }, { "type": "input_text", "text": "Summarize these documents." } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const fileId1 = process.env.SUBQ_FILE_ID ?? "file_abc123"; const fileId2 = process.env.SUBQ_FILE_ID_2 ?? "file_def456"; const response = await client.responses.create({ model: "subq-savant-1.4", input: [ { type: "input_file", file_id: fileId1 }, { type: "input_file", file_id: fileId2 }, { type: "input_text", text: "Summarize these documents." }, ], }); const message = response.output.find((item) => item.type === "message"); const text = message?.content ?.filter((part) => part.type === "output_text") .map((part) => part.text) .join(""); console.log(text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) file_id_1 = os.getenv("SUBQ_FILE_ID", "file_abc123") file_id_2 = os.getenv("SUBQ_FILE_ID_2", "file_def456") response = client.responses.create( model="subq-savant-1.4", input=[ {"type": "input_file", "file_id": file_id_1}, {"type": "input_file", "file_id": file_id_2}, {"type": "input_text", "text": "Summarize these documents."}, ], ) message = next((item for item in response.output if item.type == "message"), None) text = "".join( part.text for part in (message.content if message else []) if part.type == "output_text" ) print(text) ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Summarize these documents." }, { "type": "file", "file_id": "file_abc123" }, { "type": "file", "file_id": "file_def456" } ] } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const fileId1 = process.env.SUBQ_FILE_ID ?? "file_abc123"; const fileId2 = process.env.SUBQ_FILE_ID_2 ?? "file_def456"; const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: [ { type: "text", text: "Summarize these documents." }, { type: "file", file_id: fileId1 }, { type: "file", file_id: fileId2 }, ], }, ], }); console.log(completion.choices[0].message.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) file_id_1 = os.getenv("SUBQ_FILE_ID", "file_abc123") file_id_2 = os.getenv("SUBQ_FILE_ID_2", "file_def456") completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "user", "content": [ {"type": "text", "text": "Summarize these documents."}, {"type": "file", "file_id": file_id_1}, {"type": "file", "file_id": file_id_2}, ], } ], ) print(completion.choices[0].message.content) ``` Chat Completions accepts the flat `file_id` part shown in the Chat tab for every supported format. PDFs also accept the nested OpenAI shape: `{ "type": "file", "file": { "file_id": "file_abc123" } }`. Responses uses `{ "type": "input_file", "file_id": "file_abc123" }` for documents and `{ "type": "input_image", "file_id": "file_img456" }` for images. ## Common errors | Error | Cause | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `400 validation_error` | Malformed part, more than one source, invalid declared MIME type, or a Responses `input_image` with `image_url` instead of `file_id` | | `400 unsupported_file_type` | Unsupported bytes, an image in a Responses `input_file` part, or a document in an `input_image` part | | `409 file_not_ready` | Uploaded file has not reached `processed` | | `413` | File or inline request exceeds its size limit | See the [Files API](/endpoints/files-api/) for upload mechanics and [Structured outputs](/using-the-api/structured-outputs/) to extract fields instead of a free-text summary. --- title: Structured outputs description: Return JSON that matches your schema, from the Responses API or Chat Completions. --- > Status: Preview Structured Outputs ensures the model's reply matches your JSON Schema — set `text.format.type` (Responses) or `response_format.type` (Chat Completions) to `"json_schema"` and define your schema (`name` and `schema`). For a yes/no, category, or rating judgment with probabilities, use the [Decisions API](/endpoints/decisions-api/) instead. ## Field reference | | Responses API | Chat Completions | | --------------- | ------------------------------------------------------------------- | ------------------------------------- | | Enable | `text.format.type: "json_schema"` | `response_format.type: "json_schema"` | | Schema name | `text.format.name` | `response_format.json_schema.name` | | Strict mode | `text.format.strict` | `response_format.json_schema.strict` | | Schema | `text.format.schema` | `response_format.json_schema.schema` | | Output location | `output_text` in the OpenAI SDKs, or the `message` item in `output` | `choices[0].message.content` | Note the Responses shape is **flattened** — `name`, `strict`, and `schema` sit directly on `text.format` — while Chat Completions nests them under `response_format.json_schema`. Both accept the same JSON Schema shape in `schema`. ### Schema requirements - Root type must be `object`. - List every property in `required`. - Set `additionalProperties: false` on each object. - Supported types: `string`, `number`, `boolean`, `integer`, `enum`, `array`, nested `object`. There is no native datetime type—use a `string` field with ISO 8601 in the name or description (for example, `submit_by`, `detected_at`). ## Example List Nobel Peace Prize winners from 2022 through 2024, classifying each as a person or an organization. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "instructions": "Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence.", "input": "List Nobel Peace Prize winners from 2022 through 2024.", "text": { "format": { "type": "json_schema", "name": "nobel_peace_laureates", "strict": true, "schema": { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": { "type": "integer" }, "name": { "type": "string" }, "kind": { "type": "string", "enum": [ "👤", "🏛️" ], "description": "👤 for a person; 🏛️ for an organization or institution" }, "country_code": { "type": "string", "description": "ISO 3166-1 alpha-2" }, "motivation": { "type": "string", "description": "One-sentence citation summary" } }, "required": [ "year", "name", "kind", "country_code", "motivation" ], "additionalProperties": false } } }, "required": [ "laureates" ], "additionalProperties": false } } } } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", instructions: "Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence.", input: "List Nobel Peace Prize winners from 2022 through 2024.", text: { format: { type: "json_schema", name: "nobel_peace_laureates", strict: true, schema: { type: "object", properties: { laureates: { type: "array", items: { type: "object", properties: { year: { type: "integer" }, name: { type: "string" }, kind: { type: "string", enum: [ "👤", "🏛️" ], description: "👤 for a person; 🏛️ for an organization or institution" }, country_code: { type: "string", description: "ISO 3166-1 alpha-2" }, motivation: { type: "string", description: "One-sentence citation summary" } }, required: [ "year", "name", "kind", "country_code", "motivation" ], additionalProperties: false } } }, required: [ "laureates" ], additionalProperties: false } } } }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", instructions="Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence.", input="List Nobel Peace Prize winners from 2022 through 2024.", text={ "format": { "type": "json_schema", "name": "nobel_peace_laureates", "strict": True, "schema": { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": { "type": "integer", }, "name": { "type": "string", }, "kind": { "type": "string", "enum": [ "👤", "🏛️", ], "description": "👤 for a person; 🏛️ for an organization or institution", }, "country_code": { "type": "string", "description": "ISO 3166-1 alpha-2", }, "motivation": { "type": "string", "description": "One-sentence citation summary", }, }, "required": [ "year", "name", "kind", "country_code", "motivation", ], "additionalProperties": False, }, }, }, "required": [ "laureates", ], "additionalProperties": False, }, }, }, ) print(response.output_text) ``` The model returns schema-valid JSON as a string in `output_text`; parse it to get the object. A `reasoning` item usually comes first in `output`, so don't read `output[0]`. With tools, parse the last `message` instead. See [Extracting the assistant text](/endpoints/responses-api/#extracting-the-assistant-text). ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "system", "content": "Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence." }, { "role": "user", "content": "List Nobel Peace Prize winners from 2022 through 2024." } ], "stream": false, "response_format": { "type": "json_schema", "json_schema": { "name": "nobel_peace_laureates", "strict": true, "schema": { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": { "type": "integer" }, "name": { "type": "string" }, "kind": { "type": "string", "enum": [ "👤", "🏛️" ], "description": "👤 for a person; 🏛️ for an organization or institution" }, "country_code": { "type": "string", "description": "ISO 3166-1 alpha-2" }, "motivation": { "type": "string", "description": "One-sentence citation summary" } }, "required": [ "year", "name", "kind", "country_code", "motivation" ], "additionalProperties": false } } }, "required": [ "laureates" ], "additionalProperties": false } } } } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "system", content: "Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence." }, { role: "user", content: "List Nobel Peace Prize winners from 2022 through 2024." } ], stream: false, response_format: { type: "json_schema", json_schema: { name: "nobel_peace_laureates", strict: true, schema: { type: "object", properties: { laureates: { type: "array", items: { type: "object", properties: { year: { type: "integer" }, name: { type: "string" }, kind: { type: "string", enum: [ "👤", "🏛️" ], description: "👤 for a person; 🏛️ for an organization or institution" }, country_code: { type: "string", description: "ISO 3166-1 alpha-2" }, motivation: { type: "string", description: "One-sentence citation summary" } }, required: [ "year", "name", "kind", "country_code", "motivation" ], additionalProperties: false } } }, required: [ "laureates" ], additionalProperties: false } } } }); console.log(completion.choices[0]?.message?.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "system", "content": "Return Nobel Peace Prize laureates for only the year range in the user message. One array entry per laureate (shared prizes produce multiple entries with the same year). Set kind to 👤 for a person and 🏛️ for an organization or institution. Use ISO 3166-1 alpha-2 country codes. Keep each motivation to one sentence.", }, { "role": "user", "content": "List Nobel Peace Prize winners from 2022 through 2024.", }, ], stream=False, response_format={ "type": "json_schema", "json_schema": { "name": "nobel_peace_laureates", "strict": True, "schema": { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": { "type": "integer", }, "name": { "type": "string", }, "kind": { "type": "string", "enum": [ "👤", "🏛️", ], "description": "👤 for a person; 🏛️ for an organization or institution", }, "country_code": { "type": "string", "description": "ISO 3166-1 alpha-2", }, "motivation": { "type": "string", "description": "One-sentence citation summary", }, }, "required": [ "year", "name", "kind", "country_code", "motivation", ], "additionalProperties": False, }, }, }, "required": [ "laureates", ], "additionalProperties": False, }, }, }, ) print(completion.choices[0].message.content) ``` The model returns schema-valid JSON as a string in `choices[0].message.content`. Shown below after parsing (same shape either way — only the output location differs, see [Field reference](#field-reference)): ```json { "laureates": [ { "year": 2022, "name": "Ales Bialiatski", "kind": "👤", "country_code": "BY", "motivation": "Recognized for his tireless efforts to expose human rights abuses and promote democracy in Belarus." }, { "year": 2022, "name": "Memorial", "kind": "🏛️", "country_code": "RU", "motivation": "Honored for its documentation of political repression and human rights violations in the Soviet Union and Russia." }, { "year": 2022, "name": "Center for Civil Liberties", "kind": "🏛️", "country_code": "UA", "motivation": "Commended for its courageous work defending human rights and civil liberties in Ukraine." }, { "year": 2023, "name": "Narges Mohammadi", "kind": "👤", "country_code": "IR", "motivation": "Awarded for her unwavering fight against oppression and her advocacy for women's rights in Iran." }, { "year": 2024, "name": "Nihon Hidankyo", "kind": "🏛️", "country_code": "JP", "motivation": "Recognized for its efforts to achieve a world free of nuclear weapons and its work to eliminate nuclear weapons." } ] } ``` | Field | Type | Notes | | -------------- | ------- | ----------------------------------- | | `laureates` | array | One object per laureate | | `year` | integer | Award year | | `name` | string | Person or organization | | `kind` | enum | `👤` individual, `🏛️` organization | | `country_code` | string | ISO 3166-1 alpha-2 | | `motivation` | string | One-sentence citation summary | Set `stream` to `false` or omit it for a single JSON response. ## Response handling Parse the JSON string at the output location from the [field reference](#field-reference) above. Before parsing, check for HTTP 4xx errors, refusals/incomplete status, and truncation, then validate the parsed JSON in your app. ### Handling edge cases (Responses API) ```ts title="TypeScript" import OpenAI from "openai"; const nobelSchema = { type: "object", properties: { laureates: { type: "array", items: { type: "object", properties: { year: { type: "integer" }, name: { type: "string" }, }, required: ["year", "name"], additionalProperties: false, }, }, }, required: ["laureates"], additionalProperties: false, }; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", maxRetries: 0, }); let laureates; try { const response = await client.responses.create({ model: "subq-savant-1.4", input: "List Nobel Peace Prize winners from 2024.", text: { format: { type: "json_schema", name: "nobel_peace_laureates", strict: true, schema: nobelSchema, }, }, }); // @check truncated — status is not "completed", or incomplete_details is set if (response.status !== "completed" || response.incomplete_details) { throw new Error(`Response did not complete: ${response.status}`); } const message = response.output.find((item) => item.type === "message"); const text = message?.content ?.filter((part) => part.type === "output_text") .map((part) => part.text) .join(""); if (!text) { throw new Error("Missing assistant text."); } // @check parse — content is a JSON string at output[].content[].text const data = JSON.parse(text); // @check validate — schema-valid JSON; verify meaning in your app laureates = data.laureates; } catch (error) { // @check bad-request — HTTP 4xx + error (no response) if (error instanceof OpenAI.APIError) throw error; throw error; } ``` ```py title="Python" import json import os from openai import APIError, OpenAI nobel_schema = { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": {"type": "integer"}, "name": {"type": "string"}, }, "required": ["year", "name"], "additionalProperties": False, }, }, }, "required": ["laureates"], "additionalProperties": False, } client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", max_retries=0, ) try: response = client.responses.create( model="subq-savant-1.4", input="List Nobel Peace Prize winners from 2024.", text={ "format": { "type": "json_schema", "name": "nobel_peace_laureates", "strict": True, "schema": nobel_schema, }, }, ) except APIError: # @check bad-request — HTTP 4xx + error (no response) raise # @check truncated — status is not "completed", or incomplete_details is set if response.status != "completed" or response.incomplete_details: raise RuntimeError(f"Response did not complete: {response.status}") message = next((item for item in response.output if item.type == "message"), None) text = "".join( part.text for part in (message.content if message else []) if part.type == "output_text" ) if not text: raise RuntimeError("Missing assistant text.") # @check parse — content is a JSON string at output[].content[].text data = json.loads(text) # @check validate — schema-valid JSON; verify meaning in your app laureates = data["laureates"] ``` ### Handling edge cases (Chat Completions) ```ts title="TypeScript" import OpenAI from "openai"; const nobelSchema = { type: "object", properties: { laureates: { type: "array", items: { type: "object", properties: { year: { type: "integer" }, name: { type: "string" }, }, required: ["year", "name"], additionalProperties: false, }, }, }, required: ["laureates"], additionalProperties: false, }; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", maxRetries: 0, }); let laureates; try { const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: "List Nobel Peace Prize winners from 2024." }, ], response_format: { type: "json_schema", json_schema: { name: "nobel_peace_laureates", strict: true, schema: nobelSchema, }, }, }); const choice = completion.choices[0]; const message = choice?.message; // @check refusal — choices[0].message.refusal if (message?.refusal) { throw new Error(`Refused: ${message.refusal}`); } // @check truncated — finish_reason is "length" if (choice?.finish_reason === "length") { throw new Error("Response truncated; increase max_tokens or narrow the schema."); } if (!message?.content) { throw new Error("Missing assistant content."); } // @check parse — content is a JSON string in choices[0].message.content const data = JSON.parse(message.content); // @check validate — schema-valid JSON; verify meaning in your app laureates = data.laureates; } catch (error) { // @check bad-request — HTTP 4xx + error (no completion) if (error instanceof OpenAI.APIError) throw error; throw error; } ``` ```py title="Python" import json import os from openai import APIError, OpenAI nobel_schema = { "type": "object", "properties": { "laureates": { "type": "array", "items": { "type": "object", "properties": { "year": {"type": "integer"}, "name": {"type": "string"}, }, "required": ["year", "name"], "additionalProperties": False, }, }, }, "required": ["laureates"], "additionalProperties": False, } client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", max_retries=0, ) try: completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ {"role": "user", "content": "List Nobel Peace Prize winners from 2024."}, ], response_format={ "type": "json_schema", "json_schema": { "name": "nobel_peace_laureates", "strict": True, "schema": nobel_schema, }, }, ) except APIError: # @check bad-request — HTTP 4xx + error (no completion) raise choice = completion.choices[0] message = choice.message # @check refusal — choices[0].message.refusal if getattr(message, "refusal", None): raise RuntimeError(f"Refused: {message.refusal}") # @check truncated — finish_reason is "length" if choice.finish_reason == "length": raise RuntimeError("Response truncated; increase max_tokens or narrow the schema.") if not message.content: raise RuntimeError("Missing assistant content.") # @check parse — content is a JSON string in choices[0].message.content data = json.loads(message.content) # @check validate — schema-valid JSON; verify meaning in your app laureates = data["laureates"] ``` ## Best practices - **Use the system message (or `instructions`) to interpret the schema.** The schema sets shape; the system prompt sets meaning. Spell out formats, enums, and terse field names—the example above does this. - **Define fallbacks for missing data.** Required fields still need a value when input omits them—e.g. "use 0 for exposure\_usd when not applicable." - **Keep schemas small.** Flat objects are easier to satisfy than deep nesting. ## Related - [Responses API](/endpoints/responses-api/#structured-outputs) — structured output via `text.format`. - [Chat Completions API](/endpoints/chat-completions-api/) — request fields and response shape. - [Decisions API](/endpoints/decisions-api/) — yes/no, choice, and score judgments with probabilities. - [Function calling](/using-the-api/function-calling/) — tools and tool call outputs. - [Models](/using-the-api/models/) — supported model IDs. --- title: Function calling description: Connect SubQ models to your application with OpenAI-compatible tools, on Chat Completions or the Responses API. --- > Status: Preview Function calling (also known as tool calling) lets SubQ models interface with external systems and data outside their training data. Pass function tools defined by a JSON schema in the `tools` parameter; the model may return a **tool call**, and your application executes the function and sends the **tool call output** back so the model can finish the reply. The shape differs by endpoint: Responses uses a flattened tool object (`type`/`name`/`parameters` directly on it), while Chat Completions nests those fields under a `function` object. ## How it works **Tools** — functionality you give the model. A function tool is a JSON Schema definition the model can choose to call, for example `get_stock_quote`, account lookup, or issuing a refund. **Tool calls** — requests from the model to use a tool. If the prompt needs live data, the model returns one or more calls, each with a function `name` and JSON-encoded arguments. **Tool call outputs** — results your application sends back so the model can finish the reply. ### The tool calling flow 1. Make a request to the model with tools it could call 2. Receive a tool call from the model 3. Execute code on the application side with input from the tool call 4. Make a second request to the model with the tool output 5. Receive a final response from the model (or more tool calls) ## Field reference | | Responses API | Chat Completions | | ------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | Tool shape | `type`, `name`, `description`, `parameters`, `strict` directly on the tool object | `type: "function"` plus a nested `function: { name, description, parameters, strict }` | | Tool call | `function_call` output item — `call_id`, `name`, `arguments` | `tool_calls[]` on the assistant message — `id`, `function: { name, arguments }` | | Sending the result | `function_call_output` input item — `call_id`, `output` | A message with `role: "tool"`, `tool_call_id`, `content` | | Streaming | `response.function_call_arguments.delta`/`.done` events | `delta.tool_calls[]`, keyed by `index` | | Continuing the loop | `previous_response_id` (or `conversation`) | Resend the full `messages[]`, including the assistant and tool messages | Both accept the same JSON Schema shape in `parameters`, and the same [strict mode](#strict-mode) requirements. ## Example End-to-end flow for a `get_stock_quote` function: the first request declares the tool, the model returns a tool call, your code runs the function and sends the result back for a final answer. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data @- <<'EOF' { "model": "subq-savant-1.4", "input": "What's NVDA trading at right now?", "tools": [ { "type": "function", "name": "get_stock_quote", "description": "Retrieves the latest quote for a stock ticker.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT" }, "currency": { "type": [ "string", "null" ], "enum": [ "USD", "EUR" ], "description": "Quote currency. Defaults to USD when null." }, "include_extended_hours": { "type": "boolean", "description": "When true, include pre-market and after-hours price if available." } }, "required": [ "symbol", "currency", "include_extended_hours" ], "additionalProperties": false }, "strict": true } ] } EOF ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", input: "What's NVDA trading at right now?", tools: [ { type: "function", name: "get_stock_quote", description: "Retrieves the latest quote for a stock ticker.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT" }, currency: { type: [ "string", "null" ], enum: [ "USD", "EUR" ], description: "Quote currency. Defaults to USD when null." }, include_extended_hours: { type: "boolean", description: "When true, include pre-market and after-hours price if available." } }, required: [ "symbol", "currency", "include_extended_hours" ], additionalProperties: false }, strict: true } ] }); const calls = response.output.filter((item) => item.type === "function_call"); for (const call of calls) { console.log(call.name, call.arguments); } if (calls.length === 0) { console.log(response.output_text); } ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", input="What's NVDA trading at right now?", tools=[ { "type": "function", "name": "get_stock_quote", "description": "Retrieves the latest quote for a stock ticker.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT", }, "currency": { "type": [ "string", "null", ], "enum": [ "USD", "EUR", ], "description": "Quote currency. Defaults to USD when null.", }, "include_extended_hours": { "type": "boolean", "description": "When true, include pre-market and after-hours price if available.", }, }, "required": [ "symbol", "currency", "include_extended_hours", ], "additionalProperties": False, }, "strict": True, }, ], ) calls = [item for item in response.output if item.type == "function_call"] for call in calls: print(call.name, call.arguments) if not calls: print(response.output_text) ``` Accumulate any text preamble, execute every `function_call` in the turn, then continue with one `function_call_output` per `call_id`: ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); // Responses API function tools use a flattened shape. Unlike Chat // Completions, name/description/parameters are not nested under `function`. const tools = [ { type: "function", name: "get_stock_quote", description: "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT.", }, }, required: ["symbol"], additionalProperties: false, }, strict: true, }, ]; const SAMPLE_QUOTES = { NVDA: { price: 210.96, change_percent: 4.03 }, MSFT: { price: 402.18, change_percent: 1.12 }, }; // Replace this stub with a call to your market-data provider. async function getStockQuote({ symbol }) { return { symbol, as_of: new Date().toISOString(), ...SAMPLE_QUOTES[symbol] }; } const functionHandlers = { get_stock_quote: getStockQuote, }; // A function_call turn may carry a text preamble as a `message` item before // the call; it is never the final answer by itself, so always take the *last* // message item. function getLastAssistantText(response) { const messages = response.output.filter((item) => item.type === "message"); return ( messages .at(-1) ?.content?.filter((part) => part.type === "output_text") .map((part) => part.text) .join("") ?? "" ); } let response = await client.responses.create({ model: "subq-savant-1.4", input: "What are NVDA and MSFT trading at, and which moved more today?", tools, }); // A response can contain more function calls after receiving function call // outputs, so continue until the model returns a final response. const maxFunctionRounds = 8; for (let round = 0; round < maxFunctionRounds; round += 1) { const functionCalls = response.output.filter( (item) => item.type === "function_call", ); if (functionCalls.length === 0) break; // A message before a function call is an optional preamble, not the final // answer. It can be shown to the user while the functions are running. const preamble = getLastAssistantText(response); if (preamble) { console.log(preamble); } // Execute every function_call in the turn — the model may call in parallel. const functionCallOutputs = await Promise.all( functionCalls.map(async (call) => { const handler = functionHandlers[call.name]; if (!handler) { throw new Error(`No handler registered for function "${call.name}".`); } return { type: "function_call_output", call_id: call.call_id, output: JSON.stringify(await handler(JSON.parse(call.arguments))), }; }), ); response = await client.responses.create({ model: "subq-savant-1.4", previous_response_id: response.id, input: functionCallOutputs, // Resend tools so the model can request another function call. tools, }); } if (response.output.some((item) => item.type === "function_call")) { throw new Error(`Exceeded ${maxFunctionRounds} function-calling rounds.`); } console.log(getLastAssistantText(response)); ``` ```py title="Python" import json import os from datetime import datetime, timezone from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) # Responses API function tools use a flattened shape. Unlike Chat # Completions, name/description/parameters are not nested under `function`. tools = [ { "type": "function", "name": "get_stock_quote", "description": ( "Get the latest price for one stock ticker. " "Returns symbol, price, change_percent, and as_of." ), "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT.", }, }, "required": ["symbol"], "additionalProperties": False, }, "strict": True, }, ] SAMPLE_QUOTES = { "NVDA": {"price": 210.96, "change_percent": 4.03}, "MSFT": {"price": 402.18, "change_percent": 1.12}, } # Replace this stub with a call to your market-data provider. def get_stock_quote(symbol): quote = SAMPLE_QUOTES.get(symbol, {}) return { "symbol": symbol, "as_of": datetime.now(timezone.utc).isoformat(), **quote, } function_handlers = { "get_stock_quote": get_stock_quote, } # A function_call turn may carry a text preamble as a `message` item before # the call; it is never the final answer by itself, so always take the *last* # message item. def get_last_assistant_text(response): messages = [item for item in response.output if item.type == "message"] if not messages: return "" return "".join( part.text for part in (messages[-1].content or []) if part.type == "output_text" ) response = client.responses.create( model="subq-savant-1.4", input="What are NVDA and MSFT trading at, and which moved more today?", tools=tools, ) # A response can contain more function calls after receiving function call # outputs, so continue until the model returns a final response. max_function_rounds = 8 for _ in range(max_function_rounds): function_calls = [ item for item in response.output if item.type == "function_call" ] if not function_calls: break # A message before a function call is an optional preamble, not the final # answer. It can be shown to the user while the functions are running. preamble = get_last_assistant_text(response) if preamble: print(preamble) # Execute every function_call in the turn — the model may call in parallel. function_call_outputs = [] for call in function_calls: handler = function_handlers.get(call.name) if handler is None: raise RuntimeError(f'No handler registered for function "{call.name}".') result = handler(**json.loads(call.arguments)) function_call_outputs.append( { "type": "function_call_output", "call_id": call.call_id, "output": json.dumps(result), } ) response = client.responses.create( model="subq-savant-1.4", previous_response_id=response.id, input=function_call_outputs, # Resend tools so the model can request another function call. tools=tools, ) if any(item.type == "function_call" for item in response.output): raise RuntimeError(f"Exceeded {max_function_rounds} function-calling rounds.") print(get_last_assistant_text(response)) ``` Set `stream` to `true` and include your function definitions in `tools`. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data @- <<'EOF' { "model": "subq-savant-1.4", "messages": [ { "role": "user", "content": "What's NVDA trading at right now?" } ], "tools": [ { "type": "function", "function": { "name": "get_stock_quote", "description": "Retrieves the latest quote for a stock ticker.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT" }, "currency": { "type": [ "string", "null" ], "enum": [ "USD", "EUR" ], "description": "Quote currency. Defaults to USD when null." }, "include_extended_hours": { "type": "boolean", "description": "When true, include pre-market and after-hours price if available." } }, "required": [ "symbol", "currency", "include_extended_hours" ], "additionalProperties": false }, "strict": true } } ], "stream": true } EOF ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const stream = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: "What's NVDA trading at right now?" } ], tools: [ { type: "function", function: { name: "get_stock_quote", description: "Retrieves the latest quote for a stock ticker.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT" }, currency: { type: [ "string", "null" ], enum: [ "USD", "EUR" ], description: "Quote currency. Defaults to USD when null." }, include_extended_hours: { type: "boolean", description: "When true, include pre-market and after-hours price if available." } }, required: [ "symbol", "currency", "include_extended_hours" ], additionalProperties: false }, strict: true } } ], stream: true }); let fullText = ""; for await (const chunk of stream) { const delta = chunk.choices[0]?.delta?.content ?? ""; fullText += delta; process.stdout.write(delta); } console.log(); console.log(fullText); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) stream = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "user", "content": "What's NVDA trading at right now?", }, ], tools=[ { "type": "function", "function": { "name": "get_stock_quote", "description": "Retrieves the latest quote for a stock ticker.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT", }, "currency": { "type": [ "string", "null", ], "enum": [ "USD", "EUR", ], "description": "Quote currency. Defaults to USD when null.", }, "include_extended_hours": { "type": "boolean", "description": "When true, include pre-market and after-hours price if available.", }, }, "required": [ "symbol", "currency", "include_extended_hours", ], "additionalProperties": False, }, "strict": True, }, }, ], stream=True, ) full_text = "" for chunk in stream: delta = chunk.choices[0].delta.content or "" full_text += delta print(delta, end="", flush=True) print() print(full_text) ``` Accumulate streamed `delta.tool_calls` into one assistant message, execute each call, append `role: "tool"` results, then call the model again: ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", maxRetries: 0, }); // 1. Define callable tools for the model const tools = [ { type: "function", function: { name: "get_stock_quote", description: "Retrieves the latest quote for a stock ticker.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT", }, currency: { type: ["string", "null"], enum: ["USD", "EUR"], description: "Quote currency. Defaults to USD when null.", }, include_extended_hours: { type: "boolean", description: "When true, include pre-market and after-hours price if available.", }, }, required: ["symbol", "currency", "include_extended_hours"], additionalProperties: false, }, strict: true, }, }, ]; function getStockQuote({ symbol, currency, include_extended_hours }) { const quoteCurrency = currency ?? "USD"; return JSON.stringify({ symbol: symbol.toUpperCase(), price: 210.96, currency: quoteCurrency, change: 8.18, change_percent: 4.03, open: 202.0, high: 211.0, low: 201.92, previous_close: 202.78, market_cap: 5.11e12, pe_ratio: 32.31, market_open: false, extended_hours: include_extended_hours ? { price: 210.38, change: -0.58, change_percent: -0.27, session: "after_hours", } : null, as_of: "2026-07-10T21:22:00Z", }); } /** Accumulate streamed chat.completion chunks into one assistant message. */ async function createCompletion(messages) { const stream = await client.chat.completions.create({ model: "subq-savant-1.4", messages, tools, stream: true, }); const message = { role: "assistant", content: null, tool_calls: [], }; for await (const chunk of stream) { const delta = chunk.choices[0]?.delta; if (!delta) continue; if (typeof delta.content === "string") { message.content = (message.content ?? "") + delta.content; } for (const toolCall of delta.tool_calls ?? []) { const index = toolCall.index ?? 0; if (!message.tool_calls[index]) { message.tool_calls[index] = { id: toolCall.id, type: toolCall.type ?? "function", function: { name: toolCall.function?.name ?? "", arguments: toolCall.function?.arguments ?? "", }, }; continue; } if (toolCall.id) message.tool_calls[index].id = toolCall.id; if (toolCall.function?.name) { message.tool_calls[index].function.name += toolCall.function.name; } if (toolCall.function?.arguments) { message.tool_calls[index].function.arguments += toolCall.function.arguments; } } } if (message.tool_calls.length === 0) { delete message.tool_calls; } return message; } const messages = [ { role: "user", content: "What's NVDA trading at right now?" }, ]; // 2. Prompt the model with tools available let message = await createCompletion(messages); messages.push(message); if (!message.tool_calls?.length) { console.log(message.content); process.exit(0); } // 3. Execute each tool call on the application side for (const toolCall of message.tool_calls) { if (toolCall.function.name !== "get_stock_quote") continue; const args = JSON.parse(toolCall.function.arguments); const result = getStockQuote(args); // 4. Provide tool call outputs back to the model messages.push({ role: "tool", tool_call_id: toolCall.id, content: result, }); } // 5. Receive a final response (or more tool calls) message = await createCompletion(messages); console.log(message.content); ``` ```py title="Python" import json import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", max_retries=0, ) # 1. Define callable tools for the model tools = [ { "type": "function", "function": { "name": "get_stock_quote", "description": "Retrieves the latest quote for a stock ticker.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT", }, "currency": { "type": ["string", "null"], "enum": ["USD", "EUR"], "description": "Quote currency. Defaults to USD when null.", }, "include_extended_hours": { "type": "boolean", "description": ( "When true, include pre-market and after-hours " "price if available." ), }, }, "required": ["symbol", "currency", "include_extended_hours"], "additionalProperties": False, }, "strict": True, }, } ] def get_stock_quote(symbol, currency=None, include_extended_hours=False): quote_currency = currency or "USD" return json.dumps( { "symbol": symbol.upper(), "price": 210.96, "currency": quote_currency, "change": 8.18, "change_percent": 4.03, "open": 202.0, "high": 211.0, "low": 201.92, "previous_close": 202.78, "market_cap": 5.11e12, "pe_ratio": 32.31, "market_open": False, "extended_hours": ( { "price": 210.38, "change": -0.58, "change_percent": -0.27, "session": "after_hours", } if include_extended_hours else None ), "as_of": "2026-07-10T21:22:00Z", } ) def create_completion(messages): """Accumulate streamed chat.completion chunks into one assistant message.""" stream = client.chat.completions.create( model="subq-savant-1.4", messages=messages, tools=tools, stream=True, ) message = { "role": "assistant", "content": None, "tool_calls": [], } for chunk in stream: delta = chunk.choices[0].delta if chunk.choices else None if delta is None: continue if isinstance(delta.content, str): message["content"] = (message["content"] or "") + delta.content for tool_call in delta.tool_calls or []: index = tool_call.index or 0 if index >= len(message["tool_calls"]): message["tool_calls"].append( { "id": tool_call.id, "type": tool_call.type or "function", "function": { "name": (tool_call.function.name or ""), "arguments": (tool_call.function.arguments or ""), }, } ) continue existing = message["tool_calls"][index] if tool_call.id: existing["id"] = tool_call.id if tool_call.function.name: existing["function"]["name"] += tool_call.function.name if tool_call.function.arguments: existing["function"]["arguments"] += tool_call.function.arguments if not message["tool_calls"]: del message["tool_calls"] return message messages = [ {"role": "user", "content": "What's NVDA trading at right now?"}, ] # 2. Prompt the model with tools available message = create_completion(messages) messages.append(message) if not message.get("tool_calls"): print(message.get("content")) raise SystemExit(0) # 3. Execute each tool call on the application side for tool_call in message["tool_calls"]: if tool_call["function"]["name"] != "get_stock_quote": continue args = json.loads(tool_call["function"]["arguments"]) result = get_stock_quote(**args) # 4. Provide tool call outputs back to the model messages.append( { "role": "tool", "tool_call_id": tool_call["id"], "content": result, } ) # 5. Receive a final response (or more tool calls) message = create_completion(messages) print(message.get("content")) ``` **Example assistant tool call** (after accumulating the stream): ```json { "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_stock_quote", "arguments": "{\"symbol\":\"NVDA\",\"currency\":\"USD\",\"include_extended_hours\":false}" } } ] } ``` **Example tool message** you send back: ```json { "role": "tool", "tool_call_id": "call_abc123", "content": "{\"symbol\":\"NVDA\",\"price\":210.96,\"currency\":\"USD\",\"change\":8.18,\"change_percent\":4.03,\"open\":202.0,\"high\":211.0,\"low\":201.92,\"previous_close\":202.78,\"market_cap\":5110000000000,\"pe_ratio\":32.31,\"market_open\":false,\"extended_hours\":null,\"as_of\":\"2026-07-10T21:22:00Z\"}" } ``` A response can contain more calls after receiving outputs, so keep looping until the model returns a final message — cap the number of rounds to avoid runaway loops. Execute every call in a turn concurrently (the model may call in parallel). ### Dispatching multiple tool calls The model may return zero, one, or many calls in a single turn. Dispatch by name and execute them concurrently; on Responses, resend `tools` on each request where the model should be allowed to call again, and match outputs back by `call_id` — the same rules as the single-tool loop above, just with more than one call per turn. On Chat Completions: ```ts title="TypeScript" function getAccountPositions({ account_id, symbol }) { const positions = [ { symbol: "NVDA", quantity: 120, average_cost: 142.5, market_value: 25315.2, }, { symbol: "MSFT", quantity: 40, average_cost: 380.1, market_value: 15404.0, }, ]; const filtered = symbol ? positions.filter((p) => p.symbol === symbol.toUpperCase()) : positions; return JSON.stringify({ account_id, positions: filtered }); } const handlers = { get_stock_quote: getStockQuote, get_account_positions: getAccountPositions, }; // After createCompletion() — same streaming accumulator as the single-tool example for (const toolCall of message.tool_calls ?? []) { const handler = handlers[toolCall.function.name]; if (!handler) { throw new Error(`Unknown tool: ${toolCall.function.name}`); } const args = JSON.parse(toolCall.function.arguments); messages.push({ role: "tool", tool_call_id: toolCall.id, content: handler(args), }); } ``` ```py title="Python" def get_account_positions(account_id, symbol=None): positions = [ { "symbol": "NVDA", "quantity": 120, "average_cost": 142.5, "market_value": 25315.2, }, { "symbol": "MSFT", "quantity": 40, "average_cost": 380.1, "market_value": 15404.0, }, ] if symbol: positions = [p for p in positions if p["symbol"] == symbol.upper()] return json.dumps({"account_id": account_id, "positions": positions}) handlers = { "get_stock_quote": get_stock_quote, "get_account_positions": get_account_positions, } # After create_completion() — same streaming accumulator as the single-tool example for tool_call in message.get("tool_calls") or []: handler = handlers.get(tool_call["function"]["name"]) if handler is None: raise RuntimeError(f"Unknown tool: {tool_call['function']['name']}") args = json.loads(tool_call["function"]["arguments"]) messages.append( { "role": "tool", "tool_call_id": tool_call["id"], "content": handler(**args), } ) ``` See [Responses function calling](/endpoints/responses-api/#function-calling) for that endpoint's own parallel-call example. ## Strict mode Set `strict` to `true` so function arguments adhere to the schema. Recommended for production. Strict schemas require: 1. `additionalProperties` set to `false` on every object in `parameters` 2. Every key in `properties` listed in `required` Mark a field optional by allowing `null` in its type (for example `"type": ["string", "null"]`) while still listing it in `required`. ## Handling function calls Assume zero, one, or many tool calls in a turn — see [Dispatching multiple tool calls](#example) above. 1. Add the model's tool call(s) to your ongoing context (the assistant message on Chat Completions, or nothing extra to add on Responses — just continue via `previous_response_id`/`conversation`) 2. For each call, parse the arguments, run your code, and send back a result keyed by `call_id` (Responses) or `tool_call_id` (Chat Completions) 3. Call the model again with the result — the full `messages[]` on Chat Completions, or just the `function_call_output` items on Responses The result is typically a string — JSON, plain text, or a short success/failure token for side-effect-only functions (for example `"success"`). ## Tool choice By default the model decides when to call tools. On Chat Completions, control that with `tool_choice`: | Value | Behavior | | -------- | ---------------------------------------------- | | `"auto"` | Default. Call zero, one, or multiple functions | | `"none"` | Do not call tools (same as omitting `tools`) | Responses accepts the same two values, defaulting to `"auto"` once `tools` is set. Forcing a tool call, with `"required"` or by naming a specific function, is not supported. ## Best practices - **Write clear names and descriptions.** Say when to use the function, what each parameter means, and what the output represents. Use the system message or `instructions` for when *not* to call a tool. - **Keep the tool list small.** Fewer tools usually improve accuracy; prefer a focused set over a large catalog in one turn. - **Offload known values in code.** Do not ask the model to fill arguments you already know (for example an `order_id` from session state). - **Enable strict mode** and validate parsed arguments in your application before executing side effects. ## Related - [Responses API](/endpoints/responses-api/#function-calling) — request fields and streaming events for the flattened shape. - [Chat Completions API](/endpoints/chat-completions-api/) — request fields and response shape for the nested shape. - [Structured outputs](/using-the-api/structured-outputs/) — schema-constrained JSON replies. - [Models](/using-the-api/models/) — which models support tool calls. --- title: Decisions API description: Turn text or structured state into typed decisions with probabilities and confidence. --- Use the Decisions API for fast, structured judgments rather than generated text. It evaluates a `state` and optional images, then returns typed answers and probabilities your code can use directly. ```text POST /v1/systemone ``` For a walkthrough of question types, see [Make a decision](/using-the-api/make-a-decision/). To generate text, see [Generate text](/using-the-api/generate-text/). ## Example ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/systemone \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data @- <<'EOF' { "model": "subq-snap-1.3", "state": "Patient with asthma reports a sore throat, fever since yesterday, and shortness of breath walking to the kitchen this morning.", "questions": { "escalate": { "type": "noul", "instructions": "Should a nurse see this chat before the patient books anything?", "criteria": { "true": "Breathing trouble, chest pain, or a flare of a known condition", "false": "Stable symptoms the patient can book for themselves" } }, "queue": { "type": "choice", "instructions": "Which team should own this chat?", "criteria": { "nurse_line": "Needs a nurse to assess symptoms today", "primary_care": "Book with the patient's own doctor", "pharmacy": "Refill or medication question only", "front_desk": null } }, "acuity": { "type": "score", "instructions": "How soon should someone respond?", "criteria": [ "Within a week", "Within a day", "Within an hour" ] } } } EOF ``` ```ts title="TypeScript" const baseURL = "https://api.subq.ai/v1"; // The text to judge. const state = "Patient with asthma reports a sore throat, fever since yesterday, and shortness of breath walking to the kitchen this morning."; // One question per judgment: a yes/no gate, an owning team, a response time. const questions = { escalate: { type: "noul", instructions: "Should a nurse see this chat before the patient books anything?", criteria: { true: "Breathing trouble, chest pain, or a flare of a known condition", false: "Stable symptoms the patient can book for themselves", }, }, queue: { type: "choice", instructions: "Which team should own this chat?", criteria: { nurse_line: "Needs a nurse to assess symptoms today", primary_care: "Book with the patient's own doctor", pharmacy: "Refill or medication question only", front_desk: null, }, }, acuity: { type: "score", instructions: "How soon should someone respond?", criteria: ["Within a week", "Within a day", "Within an hour"], }, }; const response = await fetch(`${baseURL}/systemone`, { method: "POST", headers: { Authorization: `Bearer ${process.env.SUBQ_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ model: "subq-snap-1.3", state, questions, }), }); if (!response.ok) { const error = await response.json(); throw new Error( `${response.status} ${error.detail.error_type}: ${error.detail.message}`, ); } const result = await response.json(); const { escalate, queue, acuity } = result.answers; // Your code decides what happens next. Unsure routing goes to a nurse, // and so does anything the gate says needs one. let owner = queue.confidence >= 0.6 ? queue.choice : "nurse_line"; if (escalate.noul >= 0.5) owner = "nurse_line"; const respondWithin = acuity.legend[String(Math.round(acuity.score))]; console.log(`Escalate: ${escalate.noul.toFixed(2)}`); console.log( `Owner: ${owner} (model picked ${queue.choice}, confidence ${queue.confidence.toFixed(2)})`, ); console.log(`Respond: ${respondWithin}`); ``` ```py title="Python" import os import httpx2 # pip install httpx2 base_url = "https://api.subq.ai/v1" # The text to judge. state = ( "Patient with asthma reports a sore throat, fever since yesterday, and " "shortness of breath walking to the kitchen this morning." ) # One question per judgment: a yes/no gate, an owning team, a response time. questions = { "escalate": { "type": "noul", "instructions": ( "Should a nurse see this chat before the patient books anything?" ), "criteria": { "true": ( "Breathing trouble, chest pain, or a flare of a known condition" ), "false": "Stable symptoms the patient can book for themselves", }, }, "queue": { "type": "choice", "instructions": "Which team should own this chat?", "criteria": { "nurse_line": "Needs a nurse to assess symptoms today", "primary_care": "Book with the patient's own doctor", "pharmacy": "Refill or medication question only", "front_desk": None, }, }, "acuity": { "type": "score", "instructions": "How soon should someone respond?", "criteria": ["Within a week", "Within a day", "Within an hour"], }, } response = httpx2.post( f"{base_url}/systemone", headers={"Authorization": f"Bearer {os.environ['SUBQ_API_KEY']}"}, json={ "model": "subq-snap-1.3", "state": state, "questions": questions, }, timeout=60, ) result = response.json() if response.is_error: detail = result["detail"] raise RuntimeError( f"{response.status_code} {detail['error_type']}: {detail['message']}" ) answers = result["answers"] escalate = answers["escalate"]["noul"] queue = answers["queue"] acuity = answers["acuity"] # Your code decides what happens next. Unsure routing goes to a nurse, # and so does anything the gate says needs one. owner = queue["choice"] if queue["confidence"] >= 0.6 else "nurse_line" if escalate >= 0.5: owner = "nurse_line" respond_within = acuity["legend"][str(round(acuity["score"]))] print(f"Escalate: {escalate:.2f}") print( f"Owner: {owner} " f"(model picked {queue['choice']}, confidence {queue['confidence']:.2f})" ) print(f"Respond: {respond_within}") ``` ## Request The JSON body requires: - `model` — a decision model ID, such as `subq-snap-1.3`. See [Models](/using-the-api/models/). - `state` — the text, object, or array to evaluate. To ask about a document, send its text. See [Documents and images](/using-the-api/documents-and-images/). - `questions` — 1–256 named noul, choice, or score questions. Each uses `instructions` and type-specific `criteria`, which can contain strings, objects, or arrays. Answer keys match the question names, which can be up to 100 characters. The request must fit the model's 384K-token (393,216) context window. A request over the limit, or close to it, fails with `400`. The question, option, and image limits on this page apply to `subq-snap-1.3` and `subq-snap-latest`. The retired IDs `subq-snap-1.1` and `subq-snap-preview` keep the earlier limits: 4 images, 128 questions, and 255 options per choice question. Optional: - `images` — up to 16 images to evaluate alongside `state`. See [Images](#images). ### Noul A noul is a yes/no gate. Its answer is `noul`, the probability of yes from `0` to `1`. Optional `criteria.true` and `criteria.false` describe both outcomes. ### Choice A choice selects one named option. Define 2–2,500 options in `criteria`; each option's description may be `null`. The answer includes `choice`, a probability for every option, and `confidence`. ### Score A score uses 2–10 ordered levels. The answer includes a probability-weighted `score`, so it can fall between levels, plus `legend`, `probabilities`, and `confidence`. ### Images Send each image as an object: ```json { "images": [ { "mediaType": "image/jpeg", "base64": "/9j/4AAQSkZJRgABAQAA..." } ] } ``` - `mediaType` — `image/png`, `image/jpeg`, or `image/webp`. - `base64` — the file bytes as one line of base64. No URL and no `data:` prefix. - Send up to 16 images. Each can be up to 4 MiB decoded, with an 8 MiB decoded total. The whole request body can be up to 13 MiB. Image tokens count toward the context window. See [Documents and images](/using-the-api/documents-and-images/#images) for examples and image cost. An invalid image fails with `422` `validation_error`. A file over 4 MiB: ```json { "detail": { "error_type": "validation_error", "message": "images/0: image over 4 MiB" } } ``` Bytes that do not match `mediaType` fail the same way: `images/0: image bytes must match the PNG, JPEG, or WebP mediaType.` The same status covers a URL or `data:` prefix, a bad decode, more than 16 images, or more than 8 MiB decoded in total. ## Response ```json { "model": "subq-snap-1.3", "answers": { "escalate": { "type": "noul", "noul": 0.92 }, "queue": { "type": "choice", "choice": "nurse_line", "probabilities": { "nurse_line": 1, "primary_care": 0, "pharmacy": 0, "front_desk": 0 }, "confidence": 1 }, "acuity": { "type": "score", "score": 1.86, "legend": { "0": "Within a week", "1": "Within a day", "2": "Within an hour" }, "probabilities": { "0": 0, "1": 0.13, "2": 0.87 }, "confidence": 0.79 } }, "usage": { "input_tokens": 477, "output_tokens": 0 } } ``` You pay only for input tokens; `output_tokens` is always `0`. Stored decisions, including images, follow the [data-retention policy](/using-the-api/data-retention/). ## Errors Errors use a `detail` object: ```json { "detail": { "error_type": "validation_error", "message": "questions/queue: must have required property 'criteria'" } } ``` - `400` — input over the token limit, or a request the model rejects. - `401` — missing or invalid credentials. - `402` — insufficient credits. - `403` — the API key cannot use the requested model. - `422` — invalid request (including an invalid or oversized image, or more images, questions, or options than the limits above) or a model that is not a decision model. - `429` — rate limit exceeded. - `5xx` — server error. `503` means the service is temporarily unavailable. `529` (`overloaded_error`) means the service is overloaded; back off and retry. --- title: Chat Completions API description: Create OpenAI-compatible chat completions with SubQ. --- > Status: Preview Use the Chat Completions API to generate a response from [SubQ Savant](/using-the-api/models/#subq-savant-14) (`subq-savant-1.4`) for a list of conversation messages. For server-managed multi-turn conversations with system instructions and built-in web search, see [Responses API](/endpoints/responses-api/). ```text POST /v1/chat/completions ``` ## Request body Send a JSON object with the required `model` and `messages` fields. Omit optional fields unless you need to change generation behavior. | Field | Type | Required | Description | | ------------------- | ------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | string | Yes | Model ID to use, such as `subq-savant-1.4`. See [Models](/using-the-api/models/). | | `messages` | array | Yes | Conversation messages in order. Must contain at least one message. | | `stream` | boolean | No | When `false` or omitted, returns one JSON response. When `true`, returns server-sent events. | | `temperature` | number | No | Fixed at `1`. Omit it or send `1`. Any other value returns `400` `unsupported_value`. See [Restricted parameters](#restricted-parameters). | | `max_tokens` | integer | No | Caps generated tokens. Must be at least `1`. See [Token limits](#token-limits). | | `top_p` | number | No | Nucleus sampling value from `0` to `1`. | | `stop` | string or string\[] | No | Up to 4 sequences where generation stops. Each sequence is at most 256 characters. | | `n` | integer | No | Number of choices to generate, from `1` to `8`. Each comes back as its own entry in `choices`. | | `seed` | integer | No | Sampling seed. Repeating a request with the same seed and parameters aims for the same output; determinism is best-effort. | | `presence_penalty` | number | No | From `-2` to `2`. Positive values penalize tokens that have already appeared, nudging the model toward new topics. | | `frequency_penalty` | number | No | From `-2` to `2`. Positive values penalize tokens in proportion to how often they have appeared, reducing repetition. | | `reasoning_effort` | string | No | How much the model reasons before answering: `low`, `high` (the default), or `max`. Reasoning cannot be turned off. See [Reasoning effort](#reasoning-effort). | | `response_format` | object | No | Constrain the assistant reply to a JSON Schema. See [Structured outputs](/using-the-api/structured-outputs/). | | `tools` | array | No | Function tools the model may call. See [Function calling](/using-the-api/function-calling/). | | `tool_choice` | string | No | Whether the model may call tools: `"auto"` (the default) or `"none"`. See [Tool choice](/using-the-api/function-calling/#tool-choice). | | `metadata` | object or null | No | Up to 16 key-value string pairs attached to the request, for your own tracking. Echoed back on the response. See [Metadata](#metadata). | This page documents the non-streaming response. For a non-streaming request, omit `stream` or set it to `false`. ### Restricted parameters A request that breaks one of these rules returns `400`, and nothing is generated. | Parameter | Rule | `code` | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------- | | `temperature` | Fixed at `1`. Omit it or send `1`. | `unsupported_value` | | `reasoning_effort` | `none` is rejected. Reasoning cannot be turned off, including through a `reasoning` object with `effort: "none"` or `enabled: false`. Use `low` for the least reasoning. | `unsupported_value` | | `logprobs` | `true` is rejected. | `unsupported_parameter` | | `top_logprobs` | Any value from `1` to `20` is rejected. | `unsupported_parameter` | | `logit_bias` | A map with any entries is rejected. | `unsupported_parameter` | | `audio`, `modalities` | `audio`, or `modalities` that includes `"audio"`, is rejected. Audio output is not supported; `modalities: ["text"]` is accepted. | `unsupported_parameter` | | `web_search_options` | Rejected. Use [web search](/endpoints/responses-api/#web-search) on the Responses API. | `unsupported_parameter` | | `functions`, `function_call` | Deprecated and rejected. Use `tools` and `tool_choice`. | `unsupported_parameter` | For `unsupported_parameter`, `param` names the field. The empty forms are accepted: `null` for any of them, `logprobs: false`, `top_logprobs: 0`, and `logit_bias: {}`. ## Token limits `max_tokens` caps the tokens generated in the completion, reasoning included. It does not count the prompt. For Savant, we recommend setting `max_tokens` above 16,000 or omitting it. - **Budget for the reasoning and the answer together.** The model [reasons before answering](#reasoning-effort) from the same allowance, so a request can return `200` with `content` set to `null` and `finish_reason` of `"length"`: billed, with nothing visible. - Input and output share the 4M-token [context window](/using-the-api/models/#subq-savant-14). If the input plus `max_tokens` cannot fit, the API returns `400` `context_length_exceeded`. - Send `max_tokens`, not `max_completion_tokens`. - The minimum is `1`. If omitted, the response can use all remaining context. - If generation hits the cap, `choices[0].finish_reason` is `"length"`. ```json { "model": "subq-savant-1.4", "messages": [ { "role": "user", "content": "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract." } ], "max_tokens": 500 } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "user", "content": "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract." } ], "max_tokens": 500 } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract." } ], max_tokens: 500 }); console.log(completion.choices[0]?.message?.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "user", "content": "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract.", }, ], max_tokens=500, ) print(completion.choices[0].message.content) ``` ### Detecting a response spent on reasoning ```json { "choices": [ { "index": 0, "message": { "role": "assistant", "content": null, "reasoning": "The user wants three bullets comparing indemnification, limitation of liability, and insurance requirements. Indemnification shifts third-party claim costs to one party. Limitation of liability caps" }, "finish_reason": "length" } ], "usage": { "prompt_tokens": 126, "completion_tokens": 64, "total_tokens": 190, "completion_tokens_details": { "reasoning_tokens": 64 } } } ``` Test `message.content` directly—a `null` is easy to pass downstream as if it were an answer. ```js const choice = completion.choices[0]; if (choice.finish_reason === "length" && !choice.message.content) { // The cap was consumed before the answer began. Retry with a larger // max_tokens, or a lower reasoning_effort. // Retrying with the same parameters will produce the same result. } ``` ## Reasoning effort SubQ Savant reasons before it answers. Set top-level `reasoning_effort` to control how much. Reasoning cannot be turned off: `none` returns `400` `unsupported_value`. For the least reasoning, use `low`. | Value | Use it for | | ------ | ----------------------------------------------------------------------------------- | | `low` | Short answers, extraction, and latency-sensitive requests. | | `high` | The default. Most analysis, drafting, and agent loops. | | `max` | Hard questions over long inputs, where accuracy matters more than latency and cost. | `minimal`, `medium`, and `xhigh` are accepted for OpenAI compatibility and run as `low`, `high`, and `max`. - **Reasoning tokens are billed as output tokens.** They are included in `usage.completion_tokens` and counted in `max_tokens`. A one-line answer can bill many times more output tokens than its visible text. - **Higher effort doesn't always use more tokens.** Token use varies by prompt, so compare efforts on your own prompts. ```json { "model": "subq-savant-1.4", "messages": [ { "role": "system", "content": "You are a legal research assistant. Use plain language. Cite only facts in the conversation." }, { "role": "user", "content": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." } ], "reasoning_effort": "max" } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "system", "content": "You are a legal research assistant. Use plain language. Cite only facts in the conversation." }, { "role": "user", "content": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." } ], "reasoning_effort": "max" } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "system", content: "You are a legal research assistant. Use plain language. Cite only facts in the conversation." }, { role: "user", content: "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." } ], reasoning_effort: "max" }); console.log(completion.choices[0]?.message?.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "system", "content": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", }, { "role": "user", "content": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", }, ], reasoning_effort="max", ) print(completion.choices[0].message.content) ``` For classification and routing with probabilities, use the [Decisions API](/endpoints/decisions-api/). ## Reasoning output The model's reasoning comes back separately from its answer, so `content` holds only the answer. | Field | Contains | | -------------------------------------------------- | ----------------------------------------------------------------------------------- | | `choices[0].message.reasoning` | The reasoning text. `null` if the response has no reasoning text. | | `choices[0].delta.reasoning` | When streaming, reasoning text arrives in these deltas before the `content` deltas. | | `usage.completion_tokens_details.reasoning_tokens` | How many of `completion_tokens` were reasoning. | ```json {7,18} { "choices": [ { "index": 0, "message": { "role": "assistant", "reasoning": "The clause lets either party terminate for convenience. The notice period is ninety (90) days and the notice must be written. One sentence.", "content": "You need to give 90 days' written notice." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 58, "completion_tokens": 44, "total_tokens": 102, "prompt_tokens_details": { "cached_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 32 } } } ``` `reasoning` is a SubQ field, so the SDK types don't declare it. Read it like this: ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "user", content: "A vendor contract says: Either party may terminate this Agreement for convenience upon ninety (90) days prior written notice. How much notice do we need to give to cancel? Answer in one sentence.", }, ], reasoning_effort: "low", }); const message = completion.choices[0].message; // `reasoning` is a SubQ field the SDK types don't declare. const { reasoning } = message as typeof message & { reasoning?: string | null }; console.log("Answer:", message.content); console.log("Reasoning:", reasoning); console.log( "Reasoning tokens:", completion.usage?.completion_tokens_details?.reasoning_tokens, ); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "user", "content": ( "A vendor contract says: Either party may terminate this " "Agreement for convenience upon ninety (90) days prior written " "notice. How much notice do we need to give to cancel? Answer " "in one sentence." ), } ], reasoning_effort="low", ) message = completion.choices[0].message # `reasoning` is a SubQ field the SDK types don't declare. reasoning = getattr(message, "reasoning", None) print("Answer:", message.content) print("Reasoning:", reasoning) print( "Reasoning tokens:", completion.usage.completion_tokens_details.reasoning_tokens, ) ``` Show reasoning to your users or log it for debugging, but parse only `content` as the answer. ## Messages Each message has a `role` and, usually, `content`. | Field | Type | Required | Description | | --------- | ------------------------- | ------------------------------------------------------- | ------------------------------------------------------------- | | `role` | string | Yes | One of `system`, `user`, `assistant`, or `tool`. | | `content` | string or content part\[] | Yes, except on an `assistant` message with `tool_calls` | Message text as a plain string, or an array of content parts. | Use `system` for durable instructions, `user` for user input, `assistant` for prior model responses (including messages that contain `tool_calls`), and `tool` for tool result messages already produced by your application. See [Function calling](/using-the-api/function-calling/). The simplest content shape is a string: ```json { "role": "user", "content": "Summarize this release note." } ``` You can also send text content parts: ```json { "role": "user", "content": [ { "type": "text", "text": "Summarize this release note." } ] } ``` For a PDF attachment, send a `file` part in the same `user` message as your instruction. ```json { "role": "user", "content": [ { "type": "text", "text": "Summarize this report." }, { "type": "file", "file": { "filename": "report.pdf", "file_data": "data:application/pdf;base64,JVBERi0xLjcKJdDUxdgK..." } } ] } ``` Use the nested `file` object and supply exactly one source. For an inline PDF, put raw base64 or a `data:application/pdf;base64,` URI in `file_data`. For an uploaded PDF, use [`file_id`](#uploaded-files-file_id). For other document formats, upload the file with the [Files API](/endpoints/files-api/) and pass the returned ID in a Responses [`input_file` part](/endpoints/responses-api/#uploaded-files-file_id). File URLs, audio, and video are unsupported in Chat Completions. ### Images Send an image as an `image_url` part holding a base64 data URI, next to a `text` part that says what to do with it: ```json { "role": "user", "content": [ { "type": "text", "text": "What is the total due on this invoice?" }, { "type": "image_url", "image_url": { "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." } } ] } ``` Image URLs are not supported: an `http` or `https` URL returns `400` `validation_error`. The Responses API takes uploaded images as [`input_image`](/endpoints/responses-api/#uploaded-images) parts. ### Uploaded files (`file_id`) Upload the PDF with the [Files API](/endpoints/files-api/), wait until `status` is `processed`, then put its ID in `file.file_id`. ```json { "model": "subq-savant-1.4", "messages": [{ "role": "user", "content": [ { "type": "text", "text": "Summarize this report." }, { "type": "file", "file": { "file_id": "file_abc123" } } ] }] } ``` An unknown id, or a file owned by another organization, returns `404` `file_not_found`. A file that hasn't finished processing returns `409` `file_not_ready`; retry once `status` is `processed`. See [Sending files](/using-the-api/file-inputs/#uploaded-files) for SDK examples. ## Metadata Attach up to 16 key-value string pairs to a request for your own tracking: run IDs, experiment names, customer tags. SubQ does not act on these values, and the model never sees them. - Keys can be at most 64 characters; values at most 512 characters. - Values must be strings. Numbers and booleans are coerced to strings; objects, arrays, and other non-string values are rejected with a `400` `validation_error`. - Omit `metadata`, or pass `null` or `{}`, for no metadata — all three are treated the same. ```json { "model": "subq-savant-1.4", "messages": [{ "role": "user", "content": "Summarize this release note." }], "metadata": { "run_id": "eval-2026-08-31-014", "experiment": "reasoning-ablation" } } ``` A non-streaming response echoes `metadata` back verbatim: ```json { "id": "chatcmpl-mhw3k9zq_4f7k2a", "metadata": { "run_id": "eval-2026-08-31-014", "experiment": "reasoning-ablation" } } ``` Streaming chunks do not include `metadata`. ## Request examples Use cURL for direct HTTP calls, or use the official OpenAI SDK with SubQ's base URL. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/chat/completions \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "messages": [ { "role": "system", "content": "You are concise and practical." }, { "role": "user", "content": "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract." } ], "max_tokens": 500 } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const completion = await client.chat.completions.create({ model: "subq-savant-1.4", messages: [ { role: "system", content: "You are concise and practical." }, { role: "user", content: "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract." } ], max_tokens: 500 }); console.log(completion.choices[0]?.message?.content); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) completion = client.chat.completions.create( model="subq-savant-1.4", messages=[ { "role": "system", "content": "You are concise and practical.", }, { "role": "user", "content": "In three bullets, explain the difference between indemnification, limitation of liability, and insurance requirements in a software contract.", }, ], max_tokens=500, ) print(completion.choices[0].message.content) ``` ## Response A non-streaming request returns a JSON object with the OpenAI-compatible chat completion shape. ```json {10-14} { "id": "chatcmpl-mhw3k9zq_4f7k2a", "object": "chat.completion", "created": 1784314379, "model": "subq-savant-1.4", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "* **Indemnification** is a contractual obligation where one party agrees to compensate the other for losses, damages, or legal costs arising from third-party claims (such as intellectual property infringement or data breaches), effectively shifting the financial risk of those specific external liabilities to the responsible party.\n* **Limitation of Liability** caps the maximum amount of damages one party can be forced to pay the other for breach of contract or negligence, often excluding consequential or indirect damages, thereby protecting both sides from catastrophic financial exposure beyond a predefined threshold (e.g., fees paid in the prior 12 months).\n* **Insurance Requirements** mandate that one or both parties maintain specific types and minimum amounts of insurance coverage (such as general liability, professional liability, or cyber insurance) to ensure there are financial resources available to cover potential claims, serving as a verification of financial capacity rather than a direct transfer of risk between the contracting parties.", "reasoning": "The user wants three bullets, one per term, in a software-contract setting. Indemnification: who pays for third-party claims. Limitation of liability: a cap on damages between the parties. Insurance requirements: proof there is money behind the promises. Keep each bullet to one sentence and stay practical." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 110, "completion_tokens": 253, "total_tokens": 363, "prompt_tokens_details": { "cached_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 65 } } } ``` ### Response fields | Field | Type | Description | | ---------- | ------- | ------------------------------------------------------------------------------------------------------------------- | | `id` | string | Unique completion ID. | | `object` | string | Object type. Non-streaming responses use `chat.completion`. | | `created` | integer | Unix timestamp, in seconds, for when the completion was created. | | `model` | string | Model ID used for the completion. | | `choices` | array | Generated choices: `n` of them (default `1`), each with its own `index`. | | `usage` | object | Token usage for the request. | | `metadata` | object | Echo of the request's `metadata`, or `{}` if none was sent. Omitted on streaming chunks. See [Metadata](#metadata). | ### Choice fields | Field | Type | Description | | -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `index` | integer | Choice index. | | `message.role` | string | Role of the returned message, usually `assistant`. | | `message.content` | string or null | Generated text. `null` when the model returns tool calls, or when `max_tokens` was consumed before the answer began—see [Token limits](#token-limits). | | `message.reasoning` | string or null | The model's reasoning, separate from the answer. See [Reasoning output](#reasoning-output). | | `message.tool_calls` | array | Present when the model requests function calls. See [Function calling](/using-the-api/function-calling/). | | `finish_reason` | string | Reason generation stopped. Common values include `stop`, `length` (hit `max_tokens` or the remaining window), and `tool_calls`. Handle unknown string values defensively. | ### Usage fields | Field | Type | Description | | -------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `prompt_tokens` | integer | Tokens counted from the request messages. Billed at the input rate. | | `prompt_tokens_details.cached_tokens` | integer | How many of `prompt_tokens` were served from cache. Billed at the cached input rate. | | `prompt_tokens_details.multimodal_tokens` | object | Optional. Per-modality input counts (`image`, `audio`, `video`, each an integer), included in `prompt_tokens`. Present only when the model reports them. | | `completion_tokens` | integer | Tokens generated in the response, including any reasoning tokens. Billed at the output rate. | | `completion_tokens_details.reasoning_tokens` | integer | How many of `completion_tokens` were reasoning. | | `total_tokens` | integer | Sum of prompt and completion tokens. | See [Models](/using-the-api/models/#subq-savant-14) for the rates. ## Errors Errors use the OpenAI-compatible error shape. `param` is present when the error traces to one request field. ```json { "error": { "message": "logprobs is not supported for this model.", "type": "invalid_request_error", "code": "unsupported_parameter", "param": "logprobs" } } ``` Use `code` for programmatic handling — `message` text may change. | HTTP | `code` | Meaning | | ------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | `validation_error` | The body is malformed or a field has an invalid value. | | 400 | `unsupported_value` | The request set `temperature` to a value other than `1`, or tried to turn reasoning off. See [Restricted parameters](#restricted-parameters). | | 400 | `unsupported_parameter` | The request set a parameter SubQ doesn't support. `param` names it. See [Restricted parameters](#restricted-parameters). | | 400 | `context_length_exceeded` | The messages plus `max_tokens` exceed the context window. Shorten the messages or lower `max_tokens`. | | 400, 413, 422 | `model_rejected_request` | The model could not process the request. Check the field named in `param`. | | 401 | `invalid_api_key` | The API key is missing or invalid. | | 402 | `insufficient_credits` | The organization is out of credits. | | 403 | `model_not_allowed` | Your API key or plan doesn't have access to the model. | | 429 | `rate_limit_exceeded` | Your organization hit a rate limit. Retry with backoff. | | 429 | `model_rejected_request` | The model is receiving too many requests. Retry shortly. | | 502 | `model_backend_unavailable`, `model_backend_error`, `upstream_error` | The model is temporarily unavailable. Retry with backoff. | | 503 | `authorization_failed` | Key lookup temporarily unavailable. Retry. | | 504 | `model_backend_timeout` | The model did not respond in time. Retry with backoff. | | 529 | `model_overloaded` | The service is temporarily overloaded. Retry with backoff. | A streaming request that fails after the first chunk closes the connection without an error event. Treat a stream that ends before `data: [DONE]` as failed. --- title: Responses API description: Stateful inference with system instructions, web search, and server-managed conversation history. --- > Status: Preview Use the Responses API for stateful inference with [SubQ Savant](/using-the-api/models/#subq-savant-14) (`subq-savant-1.4`). SubQ stores each turn server-side and links them by ID, so multi-turn workflows — long document review, case research, and agent loops — need no client-side history management. Pass `previous_response_id` to continue from a prior turn. For stateless requests where you send the full `messages` array each time, use the [Chat Completions API](/endpoints/chat-completions-api/). ```text POST /v1/responses ``` To compare Responses with Chat Completions field by field, see [Choose an endpoint](/using-the-api/generate-text/#choose-an-endpoint). ## Request body | Field | Type | Required | Description | | ---------------------- | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `model` | string | Yes | Model ID to use, such as `subq-savant-1.4`. See [Models](/using-the-api/models/). | | `input` | string or content part\[] | Yes | The user's message for this turn. A plain string, or an array of `input_text` and `input_file` parts. See [Input](#input). | | `instructions` | string or null | No | System prompt for the current turn only. Not inherited — pass it on every request if it must persist. | | `previous_response_id` | string or null | No | Continues from a specific prior response. Mutually exclusive with `conversation`. Omit or pass `null` to start a new one. Returns `404` if the ID does not exist. | | `conversation` | string or null | No | Continues a conversation by its `conv_...` id, picking up from its most recently written turn. Mutually exclusive with `previous_response_id`. See [Multi-turn conversations](#multi-turn-conversations). Returns `404` if the conversation does not exist. | | `tools` | object\[] or null | No | Tools available to the model: built-in tools SubQ executes server-side (`{ "type": "web_search_preview" }`, see [Web search](#web-search)) and function tools your application executes (`{ "type": "function", ... }`, see [Function calling](#function-calling)). | | `reasoning` | object or null | No | Reasoning configuration for this turn. Set `effort` to `low`, `high` (the default), or `max`. Reasoning cannot be turned off. See [Reasoning effort](#reasoning-effort). | | `temperature` | number or null | No | Accepted from `0` to `2` for OpenAI compatibility and ignored. Savant always samples at `1`. | | `max_output_tokens` | integer or null | No | Caps generated tokens, reasoning included. Must be at least `16`. A capped response still returns `status: "completed"`. See [Token limits](#token-limits). | | `stream` | boolean | No | When `false` or omitted, returns one JSON response. When `true`, returns server-sent events. | | `text` | object or null | No | Output format. Defaults to `{ "format": { "type": "text" } }`. See [Structured outputs](#structured-outputs). | | `metadata` | object or null | No | Up to 16 key-value string pairs attached to the request, for your own tracking. Echoed back on the response, including streaming `response.created`/`response.completed` events. See [Metadata](/endpoints/chat-completions-api/#metadata) for the limits. | ## Reasoning effort SubQ Savant reasons before it answers. Pass a `reasoning` object with an `effort` field, not a boolean, to control how much: `low`, `high` (the default), or `max`. Reasoning cannot be turned off: `effort: "none"` returns `400` `unsupported_value`. The values and how reasoning is billed are the same as Chat Completions [`reasoning_effort`](/endpoints/chat-completions-api/#reasoning-effort). ```json { "model": "subq-savant-1.4", "instructions": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", "input": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", "reasoning": { "effort": "max" } } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "instructions": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", "input": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", "reasoning": { "effort": "max" } } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", instructions: "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", input: "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", reasoning: { effort: "max" } }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", instructions="You are a legal research assistant. Use plain language. Cite only facts in the conversation.", input="Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", reasoning={ "effort": "max", }, ) print(response.output_text) ``` Reasoning tokens are counted in `usage.output_tokens`. The reasoning itself comes back as a `reasoning` item in `output`, ahead of the answer. See [Output items](#output-items). ## Token limits `max_output_tokens` caps the tokens generated in the response. Reasoning and the answer share the same allowance. It does not count the input, and the minimum is `16`. For Savant, we recommend setting `max_output_tokens` above 16,000 or omitting it. A response that hits the cap still has `status: "completed"` and `incomplete_details: null`. To detect it, compare `usage.output_tokens` to `max_output_tokens`, which the response echoes: ```json {2-4,8} { "status": "completed", "incomplete_details": null, "max_output_tokens": 64, "usage": { "input_tokens": 100, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 64, "output_tokens_details": { "reasoning_tokens": 64 }, "total_tokens": 164 } } ``` ## Input Set `input` to a plain string: ```json { "input": "Summarize the major self-preferencing antitrust cases since 2010." } ``` A content-part array is also accepted. SubQ processes `input_text` (user text), `input_file` (an uploaded document referenced by `file_id`), and `input_image` (an uploaded image referenced by `file_id`). Prefer the string form when the turn has no files. For large documents, include the text in `input` (or earlier turns) and use SubQ's long context window, or upload the file and pass its `file_id`. ### Uploaded files (`file_id`) Upload the document with the [Files API](/endpoints/files-api/), wait until `status` is `processed`, then send an `input_file` part. Responses uses the `input_file` part type, not the Chat Completions `file` part. ```json { "model": "subq-savant-1.4", "input": [ { "type": "input_file", "file_id": "file_abc123" }, { "type": "input_text", "text": "Summarize this document." } ] } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": [ { "type": "input_file", "file_id": "file_abc123" }, { "type": "input_text", "text": "Summarize this document." } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", input: [ { type: "input_file", file_id: "file_abc123" }, { type: "input_text", text: "Summarize this document." } ] }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", input=[ { "type": "input_file", "file_id": "file_abc123", }, { "type": "input_text", "text": "Summarize this document.", }, ], ) print(response.output_text) ``` | Field | Type | Required | Description | | --------- | ------ | -------- | --------------------------------------------- | | `type` | string | Yes | Must be `"input_file"`. | | `file_id` | string | Yes | File identifier returned by `POST /v1/files`. | Inline `file_data` is not accepted on Responses. Upload the file and pass `file_id`, or send a PDF inline with [Chat Completions](/using-the-api/file-inputs/#inline-base64). A missing `file_id` returns `400` `validation_error`. An uploaded image returns `400` `unsupported_file_type`; send it as an [`input_image`](#uploaded-images) part. An unknown id, or a file owned by another organization, returns `404` `file_not_found`. You can also wrap parts in a message item (`{ "role": "user", "content": [ ... ] }`), which is the shape the SDK sends. See [Sending files](/using-the-api/file-inputs/) for upload and inline PDF examples. ### Uploaded images Upload a PNG, JPEG, or WebP image (up to 10 MiB) with the [Files API](/endpoints/files-api/), then send its ID in an `input_image` part. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": [ { "type": "input_image", "file_id": "file_img456" }, { "type": "input_text", "text": "What is the total due on this invoice?" } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", input: [ { type: "input_image", file_id: "file_img456" }, { type: "input_text", text: "What is the total due on this invoice?" } ] }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", input=[ { "type": "input_image", "file_id": "file_img456", }, { "type": "input_text", "text": "What is the total due on this invoice?", }, ], ) print(response.output_text) ``` | Field | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------------------------ | | `type` | string | Yes | Must be `"input_image"`. | | `file_id` | string | Yes | ID of an uploaded image, returned by `POST /v1/files`. | | `detail` | string | No | Accepted and ignored. | The image is stored with the turn, so later turns chained with `previous_response_id` or `conversation` still see it, and conversation item listings include the part. An `image_url` in place of `file_id` returns `400` `validation_error`. A document `file_id` returns `400` `unsupported_file_type`; send documents as `input_file`. ## Instructions Use `instructions` for system guidance — policy constraints, role, citation rules, or output style. It is inserted before conversation history for the current turn, equivalent to a Chat Completions `system` message. `instructions` are **not** carried by `previous_response_id`. Resend them on every turn that needs the same system prompt. ```json { "model": "subq-savant-1.4", "instructions": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", "input": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." } ``` ## Web search Add the `web_search_preview` tool to enable built-in web search. SubQ runs the search loop server-side: when the model asks to search, SubQ runs the search, feeds the results back, and continues until the model gives a final answer, all within one request. ```json { "model": "subq-savant-1.4", "instructions": "Be concise (3 bullets max). Prefer Fed, FDIC, and OCC releases from today. If nothing material, say so.", "input": "Any material US bank regulatory news today?", "tools": [{ "type": "web_search_preview" }] } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "instructions": "Be concise (3 bullets max). Prefer Fed, FDIC, and OCC releases from today. If nothing material, say so.", "input": "Any material US bank regulatory news today?", "tools": [ { "type": "web_search_preview" } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", instructions: "Be concise (3 bullets max). Prefer Fed, FDIC, and OCC releases from today. If nothing material, say so.", input: "Any material US bank regulatory news today?", tools: [ { type: "web_search_preview" } ] }); // A preamble message can precede tool calls; the answer is the last message. const messages = response.output.filter((item) => item.type === "message"); const answer = messages .at(-1) ?.content.filter((part) => part.type === "output_text") .map((part) => part.text) .join(""); console.log(answer ?? ""); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", instructions="Be concise (3 bullets max). Prefer Fed, FDIC, and OCC releases from today. If nothing material, say so.", input="Any material US bank regulatory news today?", tools=[ { "type": "web_search_preview", }, ], ) # A preamble message can precede tool calls; the answer is the last message. messages = [item for item in response.output if item.type == "message"] parts = messages[-1].content if messages else [] print("".join(part.text for part in parts if part.type == "output_text")) ``` ### Prompting the model to search Adding `web_search_preview` enables web search, but `tool_choice` remains `auto`. If you want the model to search rather than rely on its internal knowledge, update your instructions to explicitly tell it to: - Search the web before answering. - Verify facts against current sources. ```json { "model": "subq-savant-1.4", "instructions": "You must search the web before answering. Verify each case's latest procedural status using current authoritative sources. Prefer court decisions and regulator publications.", "input": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", "tools": [{ "type": "web_search_preview" }] } ``` Avoid instructions such as “cite only facts in the conversation” when you want current web results, because they may discourage the model from relying on retrieved information. Each executed search appears in `output` as a `web_search_call` item, in the order it ran, followed by the final assistant `message`. ```jsonc { "output": [ { "id": "ws_019f5c714e4479a5a37680c82da9d06c", "type": "web_search_call", "status": "completed", "action": { "type": "search", "queries": [ "US bank regulatory news today", "FDIC announcements today", "OCC regulatory updates today", "Federal Reserve banking regulations today" ], "query": "US bank regulatory news today" } }, { "id": "msg_019f5c71d7b37b0695ca49dc05c81ba1", "type": "message", "status": "completed", "role": "assistant", "phase": "final_answer", "content": [ { "type": "output_text", "annotations": [], "logprobs": [], "text": "Based on today's regulatory developments, here are the key updates affecting US banks:\n\n- **Immigrant Lending Guidance**: The OCC, FDIC, and NCUA jointly issued nonbinding guidance warning banks about credit risks when lending to undocumented immigrants, citing potential income instability and deportation risks. This implements a May 2026 Trump executive order and follows FinCEN's May advisory on identity theft and money laundering red flags.\n\n- **Circle National Trust Approval**: The OCC granted final approval for Circle to establish a federally regulated national trust bank (Circle National Trust) for digital asset custody. This allows Circle to manage USDC stablecoin reserves under federal oversight, marking a significant step in crypto regulation.\n\n- **Bank Failure**: The OCC shuttered Kentland Federal Savings and Loan Association (Indiana), the nation's smallest standalone bank, due to critical undercapitalization from unsafe practices. This is the third bank failure in 2026." } ] } ] } ``` **Production notes:** - `tool_choice` is `auto` — the model searches only when needed. - A single `web_search_call` may carry up to 5 queries (`action.queries`), run concurrently; `action.query` mirrors the first. - Searches and answers are stored and replayed on later `previous_response_id` turns. - Works with streaming and non-streaming. `usage` covers every inference round in the loop. - Don't assume the answer is `output[0]` or the only `message` item — select `output` items by `type`, and if more than one `message` is present, the **last** one is the final answer. See [Extracting the assistant text](#extracting-the-assistant-text). ## Function calling Define a function tool with the flattened Responses API shape — `type`, `name`, `description`, `parameters`, and `strict` sit directly on the tool object (unlike Chat Completions, which nests these under a `function` object). See [Function calling](/using-the-api/function-calling/) for the concept, the tool calling flow, and the Chat Completions comparison. ```json { "model": "subq-savant-1.4", "input": "What are NVDA and MSFT trading at, and which moved more today?", "tools": [ { "type": "function", "name": "get_stock_quote", "description": "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT." } }, "required": ["symbol"], "additionalProperties": false }, "strict": true } ] } ``` ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": "What are NVDA and MSFT trading at, and which moved more today?", "tools": [ { "type": "function", "name": "get_stock_quote", "description": "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT." } }, "required": [ "symbol" ], "additionalProperties": false }, "strict": true } ] } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", input: "What are NVDA and MSFT trading at, and which moved more today?", tools: [ { type: "function", name: "get_stock_quote", description: "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT." } }, required: [ "symbol" ], additionalProperties: false }, strict: true } ] }); const calls = response.output.filter((item) => item.type === "function_call"); for (const call of calls) { console.log(call.name, call.arguments); } if (calls.length === 0) { console.log(response.output_text); } ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", input="What are NVDA and MSFT trading at, and which moved more today?", tools=[ { "type": "function", "name": "get_stock_quote", "description": "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT.", }, }, "required": [ "symbol", ], "additionalProperties": False, }, "strict": True, }, ], ) calls = [item for item in response.output if item.type == "function_call"] for call in calls: print(call.name, call.arguments) if not calls: print(response.output_text) ``` When the model calls a function, the response contains a `function_call` output item — one per call, since the model may call the same function (or several different ones) in parallel within a single turn: ```json { "id": "resp_01a3f8c2...", "output": [ { "id": "fc_01a3f8c2b9d14e67a8b5c3d0e2f14a79", "type": "function_call", "status": "completed", "call_id": "call_5b1f0a9c3d7e42a68c0f1b2d", "name": "get_stock_quote", "arguments": "{\"symbol\": \"NVDA\"}" }, { "id": "fc_01a3f8c2b9d14e67a8b5c3d0e2f14a80", "type": "function_call", "status": "completed", "call_id": "call_9e4d2c7a1f6b48d3a05c7e91", "name": "get_stock_quote", "arguments": "{\"symbol\": \"MSFT\"}" } ] } ``` Treat `call_id` as an opaque string and pass it back verbatim in `function_call_output`. Execute the function in your application, then send its result back as a `function_call_output`. Include one function call output per `call_id`: ```json { "model": "subq-savant-1.4", "previous_response_id": "resp_01a3f8c2...", "input": [ { "type": "function_call_output", "call_id": "call_5b1f0a9c3d7e42a68c0f1b2d", "output": "{\"symbol\":\"NVDA\",\"price\":210.96,\"change_percent\":4.03,\"as_of\":\"2026-07-17T17:42:03.000Z\"}" }, { "type": "function_call_output", "call_id": "call_9e4d2c7a1f6b48d3a05c7e91", "output": "{\"symbol\":\"MSFT\",\"price\":402.18,\"change_percent\":1.12,\"as_of\":\"2026-07-17T17:42:03.000Z\"}" } ], "tools": [{ "type": "function", "name": "get_stock_quote", "description": "...", "parameters": { "type": "object", "properties": {} } }] } ``` SubQ adds the function call and its output to the model's context. The next response may contain a final response or another `function_call`; repeat the tool calling flow until the model returns a message. Resend `tools` on each request where the model should be allowed to make another call. Function call outputs are accepted only for calls from the immediately preceding `previous_response_id`. ### Full loop A response can contain more function calls after receiving function call outputs, so keep looping until the model returns a final response — cap the number of rounds to avoid runaway loops. Execute every `function_call` in a turn with `Promise.all`, since the model may call in parallel: ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); // Responses API function tools use a flattened shape. Unlike Chat // Completions, name/description/parameters are not nested under `function`. const tools = [ { type: "function", name: "get_stock_quote", description: "Get the latest price for one stock ticker. Returns symbol, price, change_percent, and as_of.", parameters: { type: "object", properties: { symbol: { type: "string", description: "Ticker symbol, e.g. NVDA or MSFT.", }, }, required: ["symbol"], additionalProperties: false, }, strict: true, }, ]; const SAMPLE_QUOTES = { NVDA: { price: 210.96, change_percent: 4.03 }, MSFT: { price: 402.18, change_percent: 1.12 }, }; // Replace this stub with a call to your market-data provider. async function getStockQuote({ symbol }) { return { symbol, as_of: new Date().toISOString(), ...SAMPLE_QUOTES[symbol] }; } const functionHandlers = { get_stock_quote: getStockQuote, }; // A function_call turn may carry a text preamble as a `message` item before // the call; it is never the final answer by itself, so always take the *last* // message item. function getLastAssistantText(response) { const messages = response.output.filter((item) => item.type === "message"); return ( messages .at(-1) ?.content?.filter((part) => part.type === "output_text") .map((part) => part.text) .join("") ?? "" ); } let response = await client.responses.create({ model: "subq-savant-1.4", input: "What are NVDA and MSFT trading at, and which moved more today?", tools, }); // A response can contain more function calls after receiving function call // outputs, so continue until the model returns a final response. const maxFunctionRounds = 8; for (let round = 0; round < maxFunctionRounds; round += 1) { const functionCalls = response.output.filter( (item) => item.type === "function_call", ); if (functionCalls.length === 0) break; // A message before a function call is an optional preamble, not the final // answer. It can be shown to the user while the functions are running. const preamble = getLastAssistantText(response); if (preamble) { console.log(preamble); } // Execute every function_call in the turn — the model may call in parallel. const functionCallOutputs = await Promise.all( functionCalls.map(async (call) => { const handler = functionHandlers[call.name]; if (!handler) { throw new Error(`No handler registered for function "${call.name}".`); } return { type: "function_call_output", call_id: call.call_id, output: JSON.stringify(await handler(JSON.parse(call.arguments))), }; }), ); response = await client.responses.create({ model: "subq-savant-1.4", previous_response_id: response.id, input: functionCallOutputs, // Resend tools so the model can request another function call. tools, }); } if (response.output.some((item) => item.type === "function_call")) { throw new Error(`Exceeded ${maxFunctionRounds} function-calling rounds.`); } console.log(getLastAssistantText(response)); ``` ```py title="Python" import json import os from datetime import datetime, timezone from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) # Responses API function tools use a flattened shape. Unlike Chat # Completions, name/description/parameters are not nested under `function`. tools = [ { "type": "function", "name": "get_stock_quote", "description": ( "Get the latest price for one stock ticker. " "Returns symbol, price, change_percent, and as_of." ), "parameters": { "type": "object", "properties": { "symbol": { "type": "string", "description": "Ticker symbol, e.g. NVDA or MSFT.", }, }, "required": ["symbol"], "additionalProperties": False, }, "strict": True, }, ] SAMPLE_QUOTES = { "NVDA": {"price": 210.96, "change_percent": 4.03}, "MSFT": {"price": 402.18, "change_percent": 1.12}, } # Replace this stub with a call to your market-data provider. def get_stock_quote(symbol): quote = SAMPLE_QUOTES.get(symbol, {}) return { "symbol": symbol, "as_of": datetime.now(timezone.utc).isoformat(), **quote, } function_handlers = { "get_stock_quote": get_stock_quote, } # A function_call turn may carry a text preamble as a `message` item before # the call; it is never the final answer by itself, so always take the *last* # message item. def get_last_assistant_text(response): messages = [item for item in response.output if item.type == "message"] if not messages: return "" return "".join( part.text for part in (messages[-1].content or []) if part.type == "output_text" ) response = client.responses.create( model="subq-savant-1.4", input="What are NVDA and MSFT trading at, and which moved more today?", tools=tools, ) # A response can contain more function calls after receiving function call # outputs, so continue until the model returns a final response. max_function_rounds = 8 for _ in range(max_function_rounds): function_calls = [ item for item in response.output if item.type == "function_call" ] if not function_calls: break # A message before a function call is an optional preamble, not the final # answer. It can be shown to the user while the functions are running. preamble = get_last_assistant_text(response) if preamble: print(preamble) # Execute every function_call in the turn — the model may call in parallel. function_call_outputs = [] for call in function_calls: handler = function_handlers.get(call.name) if handler is None: raise RuntimeError(f'No handler registered for function "{call.name}".') result = handler(**json.loads(call.arguments)) function_call_outputs.append( { "type": "function_call_output", "call_id": call.call_id, "output": json.dumps(result), } ) response = client.responses.create( model="subq-savant-1.4", previous_response_id=response.id, input=function_call_outputs, # Resend tools so the model can request another function call. tools=tools, ) if any(item.type == "function_call" for item in response.output): raise RuntimeError(f"Exceeded {max_function_rounds} function-calling rounds.") print(get_last_assistant_text(response)) ``` ## Request examples Basic request with system instructions: ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "instructions": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", "input": "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const response = await client.responses.create({ model: "subq-savant-1.4", instructions: "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", input: "Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel." }); console.log(response.output_text); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) response = client.responses.create( model="subq-savant-1.4", instructions="You are a legal research assistant. Use plain language. Cite only facts in the conversation.", input="Summarize the major self-preferencing antitrust cases since 2010 and list open questions for counsel.", ) print(response.output_text) ``` ## Response A non-streaming request returns a Response object: ```json {6,11,30,37-43} { "id": "resp_01939abc1234567890abcdef", "object": "response", "created_at": 1768000000, "completed_at": 1768000001, "status": "completed", "model": "subq-savant-1.4", "output": [ { "id": "rs_019f42995c1e7b02a9d1c3e5f7a80b12", "type": "reasoning", "status": "completed", "summary": [], "content": [ { "type": "reasoning_text", "text": "The user wants a plain-language summary and open questions. Define self-preferencing first, name the leading cases, then list what counsel still has to decide." } ] }, { "id": "msg_019f42995d097843a2bbdada3a046f14", "type": "message", "role": "assistant", "status": "completed", "phase": "final_answer", "content": [ { "type": "output_text", "text": "Self-preferencing means a platform favors its own products over competitors. Major cases since 2010 include the EU Google Shopping decision and related follow-on actions. Open questions for counsel often include how to define the relevant market and how to measure harm to rivals.", "annotations": [], "logprobs": [] } ] } ], "usage": { "input_tokens": 100, "input_tokens_details": { "cached_tokens": 0 }, "output_tokens": 104, "output_tokens_details": { "reasoning_tokens": 36 }, "total_tokens": 204 }, "instructions": "You are a legal research assistant. Use plain language. Cite only facts in the conversation.", "previous_response_id": null, "tools": [], "text": { "format": { "type": "text" } }, "error": null, "incomplete_details": null } ``` ### Extracting the assistant text The answer is not at a fixed index. A `reasoning` item usually comes first, so `output[0].content[0].text` returns the model's reasoning, not its answer. Without tools, read `output_text`. The OpenAI SDKs add it to the response, joining the text of every `message` item and skipping `reasoning`. A turn without tools has one `message`, so `output_text` is the answer. When tools run, `output` also contains `web_search_call` or `function_call` items, and the model may first emit a short text preamble, such as "Let me look that up.", as its own `message` item ahead of them. A turn can therefore hold two `message` items, for example `[message, web_search_call, message]`, and `output_text` glues them together. Select message items by `type`, and take the **last** one as the final answer: ```js const messages = response.output.filter((item) => item.type === "message"); const text = messages .at(-1) ?.content.filter((part) => part.type === "output_text") .map((part) => part.text) .join("") ?? ""; ``` Save `response.id` for the next turn's `previous_response_id`. ### Key response fields | Field | Description | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | Stable response ID for `previous_response_id`. | | `status` | `completed` on a finished response. When streaming, `in_progress` on `response.created` and `failed` on `response.failed`. | | `output` | Ordered items for this turn: `reasoning`, `message`, `web_search_call`, and `function_call`, in the order the model produced them. See [Output items](#output-items). | | `usage` | Token counts for this request. Input includes the conversation history replayed for the turn. | | `instructions` / `tools` / `text` / `reasoning` / `max_output_tokens` | Echo of request fields. | | `metadata` | Echo of the request's `metadata`, or `{}` if none was sent. | | `conversation` | Present on every turn: `{ "id": "conv_..." }` identifying the conversation this response belongs to. See the [Conversations API](/endpoints/conversations-api/). | Other request fields such as `tool_choice` may also be echoed. `temperature` is not: Savant always samples at `1`. ### Output items | `type` | Meaning | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `reasoning` | The model's reasoning for this turn, before the answer. Read `content[].text` where `type` is `reasoning_text`. `summary` is always empty. Show it or log it, but don't parse it as the answer. | | `message` | Assistant text. Read `content[].text` where `type` is `output_text`. A turn may include more than one — a preamble before tool calls, and the final answer. | | `web_search_call` | A completed search. See `action.queries` / `action.query`. | | `function_call` | A function call generated by the model. See `call_id`, `name`, `arguments`, and [Function calling](#function-calling). | ### Usage fields | Field | Description | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `input_tokens` | Tokens the model read for this turn: `instructions`, the replayed conversation history, and the new `input`. A web search loop counts them once per round. Billed at the input rate. | | `input_tokens_details.cached_tokens` | Always `0` on this endpoint. Chat Completions reports cached tokens in [`prompt_tokens_details.cached_tokens`](/endpoints/chat-completions-api/#usage-fields). | | `output_tokens` | Tokens generated in the response, including reasoning tokens. Billed at the output rate. | | `output_tokens_details.reasoning_tokens` | How many of `output_tokens` were reasoning. | | `total_tokens` | Sum of input and output tokens. | See [Models](/using-the-api/models/#subq-savant-14) for the rates. ## Multi-turn conversations Pass the `id` from a previous response as `previous_response_id` to continue. The server rebuilds history automatically — send only the new `input` and the prior response ID. ``` Turn 1: POST /v1/responses { "model": "subq-savant-1.4", "input": "Who won the 2024 Nobel Prize in Physics?" } ← { "id": "resp_019f42fa...", "output": [{ "content": [{ "text": "John J. Hopfield and Geoffrey E. Hinton — for foundational work on machine learning with artificial neural networks." }] }] } Turn 2: POST /v1/responses { "model": "subq-savant-1.4", "input": "How does this connect to modern deep learning?", "previous_response_id": "resp_019f42fa..." } ← { "id": "resp_019f430a...", "previous_response_id": "resp_019f42fa...", "output": [{ "content": [{ "text": "Hopfield networks inspired associative memory and energy-based models; Hinton's backpropagation and deep networks underpin today's CNNs, transformers, and LLMs." }] }] } Turn 3: POST /v1/responses { "model": "subq-savant-1.4", "input": "Are there any other physics-inspired ML ideas not from these laureates?", "previous_response_id": "resp_019f430a..." } ← { "id": "resp_019f4319...", "previous_response_id": "resp_019f430a...", "output": [{ "content": [{ "text": "Yes — Boltzmann machines, diffusion models, renormalization-group analyses of deep networks, and thermodynamics-inspired views of SGD, among others." }] }] } ``` Chain turns by passing the latest `id` as `previous_response_id`. Resend `instructions` (and `tools`, if needed) on each turn — they are not inherited. ### Continuing by conversation id Every response includes a `conversation.id`. Pass it as `conversation` on a later turn to continue instead of using a specific response id: ```json { "model": "subq-savant-1.4", "input": "What is my name?", "conversation": "conv_abc123" } ``` Use one or the other, not both — sending both `conversation` and `previous_response_id` returns `400`. **Key behaviors:** - History is **branch-safe**: branching from an older `previous_response_id` creates a new conversation branch rather than corrupting the existing chain. - `usage.input_tokens` reflects the full conversation history resent each turn, not just the new input. - Prior web searches are replayed into context so the model retains what it found. - If `previous_response_id` or `conversation` does not exist, the server returns `404` immediately, before inference. To manage the conversation itself — seed it with history up front, add or read back items, retag its metadata, or delete it — see the [Conversations API](/endpoints/conversations-api/). ## Streaming When `stream: true`, the response is SSE (`Content-Type: text/event-stream`). Lifecycle events are always present; tools add output-item events. **Lifecycle:** `response.created` → `response.reasoning_text.delta`… → `response.output_text.delta`… → `response.completed` **Output items (reasoning, and tools when they run):** `response.output_item.added` → item progress events → `response.output_item.done` ``` event: response.created data: { "type": "response.created", "sequence_number": 0, "response": { ... } } event: response.output_item.added data: { "type": "response.output_item.added", "sequence_number": 1, "output_index": 0, "item": { "id": "rs_019f...", "type": "reasoning", "status": "in_progress", "summary": [], "content": [] } } event: response.reasoning_text.delta data: { "type": "response.reasoning_text.delta", "sequence_number": 2, "item_id": "rs_019f...", "output_index": 0, "content_index": 0, "delta": "The user wants" } event: response.reasoning_text.done data: { "type": "response.reasoning_text.done", "sequence_number": 3, "item_id": "rs_019f...", "output_index": 0, "content_index": 0, "text": "The user wants a plain-language summary..." } event: response.output_item.done data: { "type": "response.output_item.done", "sequence_number": 4, "output_index": 0, "item": { "id": "rs_019f...", "type": "reasoning", "status": "completed", ... } } event: response.output_text.delta data: { "type": "response.output_text.delta", "sequence_number": 5, "item_id": "msg_019f...", "output_index": 1, "content_index": 0, "delta": "Self" } event: response.completed data: { "type": "response.completed", "sequence_number": 6, "response": { ... } } ``` | Event type | When | | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `response.created` | First. Skeleton response (`status: "in_progress"`). Use `response.id` for the next turn. | | `response.reasoning_text.delta` / `done` | Reasoning text, streamed before the answer as its own `reasoning` item. Keep it out of the answer you assemble. | | `response.output_text.delta` | Text chunk of assistant text: the final answer, or a preamble before tool calls. Concatenate `delta` values per output item. | | `response.completed` | Last. Full `output` and `usage`. | | `response.failed` | Last, in place of `response.completed`, when the request fails after the stream opens. `response.error` has the `code` and `message`. | | `response.output_item.added` / `done` | A structured output item (`reasoning`, `web_search_call`, or `function_call`) is created / finalized. | | `response.web_search_call.in_progress` / `searching` / `completed` | Status pings while a search runs. Queries appear on `output_item.done`. | | `response.function_call_arguments.delta` / `done` | Streamed `arguments` for a `function_call`. Concatenate `delta` values, then parse `done`'s `arguments` as JSON. | Items are ordered by `output_index`, incrementing per item in the order the model produced them. With no tools, the `reasoning` item is index `0` and the answer `message` is index `1`. Treat unknown event types as ignorable. The stream ends after `response.completed` — not `data: [DONE]`. A `: keepalive` comment is emitted every 15s while the model is slow. If the stream ends with `response.failed`, or closes without `response.completed`, treat it as an error. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/responses \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "model": "subq-savant-1.4", "input": "Summarize the major self-preferencing antitrust cases since 2010.", "stream": true } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const stream = await client.responses.create({ model: "subq-savant-1.4", input: "Summarize the major self-preferencing antitrust cases since 2010.", stream: true }); let fullText = ""; let responseId = null; for await (const event of stream) { if (event.type === "response.created") { responseId = event.response.id; continue; } if (event.type === "response.output_text.delta") { fullText += event.delta; process.stdout.write(event.delta); continue; } if (event.type === "response.completed") { // event.response has full output and usage continue; } } console.log(); // newline after streamed tokens console.log(fullText); console.log(responseId); // use as previous_response_id on the next turn ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) stream = client.responses.create( model="subq-savant-1.4", input="Summarize the major self-preferencing antitrust cases since 2010.", stream=True, ) full_text = "" response_id = None for event in stream: if event.type == "response.created": response_id = event.response.id continue if event.type == "response.output_text.delta": full_text += event.delta print(event.delta, end="", flush=True) continue if event.type == "response.completed": # event.response has full output and usage continue print() print(full_text) print(response_id) # use as previous_response_id on the next turn ``` ## Structured outputs Set `text.format` to constrain the model's output — see [Structured outputs](/using-the-api/structured-outputs/) for schema design guidance. Three modes are supported: | Mode | Shape | Guarantee | | ---------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------- | | `text` (default) | `{ "type": "text" }` | Unconstrained text. | | `json_object` | `{ "type": "json_object" }` | Output is valid JSON, but not constrained to any schema. | | `json_schema` | `{ "type": "json_schema", "name": "...", "strict": true, "schema": { ... } }` | Output conforms to the supplied JSON Schema. | Note the **flattened** shape: `name`, `strict`, and `schema` sit directly on `text.format` — unlike Chat Completions, where they nest under `response_format.json_schema`. ```json { "model": "subq-savant-1.4", "input": "RFI-042 from Structural: Confirm rebar grade for Level 3 slab. Spec section 03 20 00 says Grade 60. Reply needed by 2026-07-18 before pour.", "text": { "format": { "type": "json_schema", "name": "rfi_extract", "strict": true, "schema": { "type": "object", "properties": { "rfi_id": { "type": "string" }, "from_trade": { "type": "string" }, "question": { "type": "string" }, "spec_section": { "type": "string" }, "due_date": { "type": "string" } }, "required": ["rfi_id", "from_trade", "question", "spec_section", "due_date"], "additionalProperties": false } } } } ``` Example output, in `content[0].text` of the `message` item (parse the string to get the object): ```json { "rfi_id": "RFI-042", "from_trade": "Structural", "question": "Confirm rebar grade for Level 3 slab. Spec section 03 20 00 says Grade 60.", "spec_section": "03 20 00", "due_date": "2026-07-18" } ``` The structured JSON arrives as ordinary assistant text in the `message` item, not at a fixed index — [select it by `type`](#extracting-the-assistant-text), then parse `content[0].text` to get the object. `json_schema` guarantees a valid shape; for reliable field values, put the facts in `input` and ask the model to extract them (as above). `json_object` mode does not require the word "JSON" in your prompt. For a yes/no, category, or rating judgment with probabilities, use the [Decisions API](/endpoints/decisions-api/). ## Errors ```json { "error": { "message": "Response 'resp_xxx' not found.", "type": "server_error", "code": "response_not_found" } } ``` Use `code` for programmatic handling — `message` text may change. Shared codes with Chat Completions include `invalid_api_key`, `insufficient_credits`, `validation_error`, `rate_limit_exceeded`, and `model_not_allowed` (`403`, your API key or plan doesn't have access to the model). The full shared list, including model and rate-limit errors, is under [Chat Completions errors](/endpoints/chat-completions-api/#errors). Responses-specific: | HTTP | `code` | Meaning | | ---- | ------------------------ | --------------------------------------------------------------------------------------------------------------- | | 400 | `validation_error` | `input_file` is missing `file_id`, or the part used unsupported inline `file_data` | | 400 | `validation_error` | `input_image` is missing `file_id`. Inline `image_url` is not accepted; upload the image and pass its `file_id` | | 400 | `unsupported_file_type` | `input_file` points at an uploaded image; send it as [`input_image`](#uploaded-images) | | 400 | `unsupported_file_type` | `input_image` points at a document; send it as `input_file` | | 400 | `unsupported_value` | `reasoning.effort` is `none`. Reasoning cannot be turned off; see [Reasoning effort](#reasoning-effort) | | 404 | `response_not_found` | `previous_response_id` does not exist in the store | | 404 | `conversation_not_found` | `conversation` does not exist or belongs to another organization | | 404 | `file_not_found` | `file_id` does not exist or is owned by another organization | See the [Conversations API](/endpoints/conversations-api/#errors) for conversation-specific error codes. ## Next steps - [Conversations API](/endpoints/conversations-api/) — manage conversation history as a stored resource. - [Function calling](/using-the-api/function-calling/) — tool calling concepts and the Chat Completions tool shape. - [Structured outputs](/using-the-api/structured-outputs/) — schema design for `text.format`. - [Sending files](/using-the-api/file-inputs/) — `input_file` vs Chat Completions `file` parts. - [Files API](/endpoints/files-api/) — upload and manage files referenced by `file_id`. - [Chat Completions API](/endpoints/chat-completions-api/) — stateless requests where you send the full `messages` array. - [Models](/using-the-api/models/) — model IDs, context windows, and pricing. --- title: Conversations API description: Manage conversation history as a stored resource — create, retrieve, update, delete, and manage the items inside it. --- > Status: Preview Use the Conversations API to create, inspect, retag, and delete stored conversations — and the items inside them. How long that history stays is covered in [Data retention](/using-the-api/data-retention/). These are storage operations — no inference runs. Continue a conversation directly from `/v1/responses` with the [`conversation`](/endpoints/responses-api/#request-body) field, or without a stored resource at all via [`previous_response_id`](/endpoints/responses-api/#multi-turn-conversations). ## Endpoints | Method | Path | Description | | -------- | ----------------------------------------------------- | -------------------------------- | | `POST` | `/v1/conversations` | Create a conversation | | `GET` | `/v1/conversations/{conversation_id}` | Retrieve a conversation | | `POST` | `/v1/conversations/{conversation_id}` | Update a conversation's metadata | | `DELETE` | `/v1/conversations/{conversation_id}` | Delete a conversation | | `POST` | `/v1/conversations/{conversation_id}/items` | Add items to a conversation | | `GET` | `/v1/conversations/{conversation_id}/items` | List a conversation's items | | `GET` | `/v1/conversations/{conversation_id}/items/{item_id}` | Retrieve an item | | `DELETE` | `/v1/conversations/{conversation_id}/items/{item_id}` | Delete an item | ## The conversation object Every endpoint except delete returns a conversation object: ```json { "id": "conv_abc123", "object": "conversation", "created_at": 1751484000, "metadata": { "department": "cardiology", "acuity": "unconfirmed" } } ``` | Field | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `id` | string | Conversation ID (`conv_...`). | | `object` | string | Always `"conversation"`. | | `created_at` | integer | Unix timestamp (seconds) of creation. Unchanged on update. | | `metadata` | object | String-to-string tags. Always an object (`{}` if untagged, never `null`). Up to 16 keys; keys up to 64 characters, values up to 512. | ## Create a conversation ``` POST /v1/conversations ``` All fields are optional. An empty body creates an untagged conversation. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/conversations \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "metadata": { "department": "cardiology", "acuity": "unconfirmed" } } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const conversation = await client.conversations.create({ metadata: { department: "cardiology", acuity: "unconfirmed" }, }); console.log(conversation.id); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) conversation = client.conversations.create( metadata={"department": "cardiology", "acuity": "unconfirmed"}, ) print(conversation.id) ``` Seed it with prior history by passing `items` — up to 20 user messages, text only (see [Items](#items) to add more later): ```json { "metadata": { "department": "cardiology" }, "items": [ { "role": "user", "content": "Patient reports chest pain since this morning." } ] } ``` Orgs configured for [zero data retention](/using-the-api/data-retention/#zero-data-retention) cannot create conversations (`403` `zero_data_retention`). Send the full input on each `/v1/responses` request instead. ## Retrieve a conversation ``` GET /v1/conversations/{conversation_id} ``` ```bash title="cURL" curl --request GET \ --url https://api.subq.ai/v1/conversations/conv_abc123 \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const conversation = await client.conversations.retrieve( process.env.SUBQ_CONVERSATION_ID ?? "conv_abc123", ); console.log(conversation.metadata); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) conversation = client.conversations.retrieve( os.getenv("SUBQ_CONVERSATION_ID", "conv_abc123") ) print(conversation.metadata) ``` Returns the [conversation object](#the-conversation-object). An unknown id, or one that belongs to another organization, returns `404` `conversation_not_found`. ## Update a conversation ``` POST /v1/conversations/{conversation_id} ``` `metadata` is required and **replaces** the stored tags. Resend every key you want to keep; send `{}` to clear them. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/conversations/conv_abc123 \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --header 'Content-Type: application/json' \ --data ' { "metadata": { "department": "cardiology", "acuity": "urgent" } } ' ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); // metadata replaces the stored tags entirely — resend every key you want to keep. const conversation = await client.conversations.update( process.env.SUBQ_CONVERSATION_ID ?? "conv_abc123", { metadata: { department: "cardiology", acuity: "urgent" } }, ); console.log(conversation.metadata); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) # metadata replaces the stored tags entirely — resend every key you want to keep. conversation = client.conversations.update( os.getenv("SUBQ_CONVERSATION_ID", "conv_abc123"), metadata={"department": "cardiology", "acuity": "urgent"}, ) print(conversation.metadata) ``` ## Delete a conversation ``` DELETE /v1/conversations/{conversation_id} ``` Deletes the conversation and every [item](#items) and response in it. Irreversible. ```bash title="cURL" curl --request DELETE \ --url https://api.subq.ai/v1/conversations/conv_abc123 \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const result = await client.conversations.delete( process.env.SUBQ_CONVERSATION_ID ?? "conv_abc123", ); console.log(result.deleted); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) result = client.conversations.delete( os.getenv("SUBQ_CONVERSATION_ID", "conv_abc123") ) print(result.deleted) ``` ```json { "id": "conv_abc123", "object": "conversation.deleted", "deleted": true } ``` ## Items List, add, retrieve, or delete the individual messages, function calls, and web searches inside a conversation. | Method | Path | Description | | -------- | ----------------------------------------------------- | ---------------- | | `POST` | `/v1/conversations/{conversation_id}/items` | Add items | | `GET` | `/v1/conversations/{conversation_id}/items` | List items | | `GET` | `/v1/conversations/{conversation_id}/items/{item_id}` | Retrieve an item | | `DELETE` | `/v1/conversations/{conversation_id}/items/{item_id}` | Delete an item | Add items the same way you [seed a conversation](#create-a-conversation) — `role: "user"`, text only: ```json { "items": [ { "role": "user", "content": "Follow-up: any allergies on file?" } ] } ``` Reasoning and function-call outputs aren't individually addressable — they stay attached to their parent message. List paginates with `limit` (1–100, default 20), `order`, and an `after` cursor, same as [Files](/endpoints/files-api/#list-files). Delete returns the parent conversation object, not a deletion envelope. ## Errors ```json { "error": { "message": "Conversation 'conv_abc123' not found.", "type": "invalid_request_error", "code": "conversation_not_found" } } ``` | HTTP | `code` | Meaning | | ---- | ------------------------ | ------------------------------------------------------------------------- | | 401 | `invalid_api_key` | Missing or invalid Bearer token | | 404 | `conversation_not_found` | Id doesn't exist or belongs to another organization | | 404 | `item_not_found` | Item doesn't exist in the conversation, or isn't individually addressable | | 403 | `zero_data_retention` | Org cannot store conversations | | 403 | `access_denied` | API key does not belong to an organization | | 503 | `authorization_failed` | Key lookup temporarily unavailable; retry | ## Related - [Responses API](/endpoints/responses-api/) — continue a stored conversation directly with the `conversation` field, or chain turns with `previous_response_id`; every response includes a `conversation` field either way. --- title: Files API description: Upload, list, retrieve, and delete org-scoped files for use with Chat Completions and Responses. --- > Status: Preview Use the Files API to upload and manage documents and images for your organization. Files are org-scoped — a file is only visible to the organization that created it. After uploading a document, pass its `file_id` in an `input_file` part on the [Responses API](/endpoints/responses-api/#uploaded-files-file_id). For PDFs, you can also pass the ID in a nested `file` part on [Chat Completions](/endpoints/chat-completions-api/#uploaded-files-file_id). Uploaded images are supported through flat Chat Completions `file` parts and Responses [`input_image`](/endpoints/responses-api/#uploaded-images) parts. See [Sending files](/using-the-api/file-inputs/) for examples. ## Endpoints | Method | Path | Description | | -------- | --------------------- | ------------------------- | | `POST` | `/v1/files` | Upload a file (multipart) | | `GET` | `/v1/files` | List the org's files | | `GET` | `/v1/files/{file_id}` | Retrieve one file | | `DELETE` | `/v1/files/{file_id}` | Delete a file | ## Limits - **Max size:** 50 MiB per file, or 10 MiB for an image. - **Purpose:** `assistants` (only value accepted today). - **Supported types:** plain text (`.txt`, `.md`, `.csv`, `.tsv`), JSON / JSONL, XML, PDF, Word (`.doc`, `.docx`), and PNG, JPEG, or WebP images. Images are stored as-is, with no text extraction. ## File object | Field | Type | Description | | ------------ | -------------- | ------------------------------------------------------------------------------ | | `id` | string | File identifier (`file_…`). Use as `file_id` in Chat Completions or Responses. | | `object` | string | Always `"file"`. | | `bytes` | number | Size in bytes. | | `created_at` | number | Unix timestamp (seconds) when the file was created. | | `expires_at` | number or null | Expiration timestamp, if any. | | `filename` | string | Original file name. | | `purpose` | string | Intended purpose (`assistants`). | | `status` | string or null | Lifecycle status (see below). | ### Statuses | Status | Meaning | | ----------- | -------------------------------------------------------------------------------------------------- | | `uploaded` | Bytes stored and validated. Non-text files may still be extracting text. | | `processed` | Content available for Chat Completions and Responses. Text and image files reach this immediately. | | `error` | Text extraction failed. A later retry can flip it back to `processed`. | ## Upload file ``` POST /v1/files ``` Upload bytes through the API as `multipart/form-data`. | Field | Required | Description | | --------- | -------- | --------------------- | | `file` | Yes | The file part. | | `purpose` | Yes | Must be `assistants`. | Setting the part's `Content-Type` is optional. A part sent with no type, `text/plain`, or `application/octet-stream` gets the type SubQ detects from the file's bytes and filename. Any other type must be one of the [supported types](#limits). Either way, a file whose bytes don't match a supported type returns `400`; see [Errors](#errors). Word files need a `.doc` or `.docx` filename. ```bash title="cURL" curl --request POST \ --url https://api.subq.ai/v1/files \ --header "Authorization: Bearer $SUBQ_API_KEY" \ --form purpose=assistants \ --form file='@./report.pdf' ``` ```ts title="TypeScript" import { createReadStream } from "node:fs"; import OpenAI, { toFile } from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const file = await client.files.create({ file: await toFile(createReadStream("./report.pdf"), "report.pdf", { type: "application/pdf", }), purpose: "assistants", }); console.log(file.id); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) with open("./report.pdf", "rb") as handle: file = client.files.create(file=handle, purpose="assistants") print(file.id) ``` ### Response ```json { "id": "file_abc123", "object": "file", "bytes": 12345, "created_at": 1753742400, "expires_at": null, "filename": "report.pdf", "purpose": "assistants", "status": "uploaded" } ``` ### Uploading multiple files Each request uploads one file — call the endpoint once per file and run the calls concurrently rather than looping with `await` one at a time: ```ts title="TypeScript" import { createReadStream } from "node:fs"; import OpenAI, { toFile } from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); async function uploadFile(path: string, contentType: string) { return client.files.create({ file: await toFile(createReadStream(path), path.split("/").pop(), { type: contentType, }), purpose: "assistants", }); } // Each request uploads one file — fire the calls concurrently rather than // looping with `await` one at a time. const uploads = [ { path: "./report.pdf", contentType: "application/pdf" }, { path: "./meeting-notes.txt", contentType: "text/plain" }, ]; const files = await Promise.all( uploads.map(({ path, contentType }) => uploadFile(path, contentType)), ); files.forEach((file, i) => console.log(`${uploads[i].path} -> ${file.id}`)); ``` ```py title="Python" import asyncio import os from openai import AsyncOpenAI client = AsyncOpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) async def upload_file(path): with open(path, "rb") as handle: return await client.files.create(file=handle, purpose="assistants") async def upload_multiple(paths): # Each request uploads one file — gather the calls concurrently rather # than awaiting one at a time. return await asyncio.gather(*(upload_file(path) for path in paths)) paths = ["./report.pdf", "./meeting-notes.txt"] files = asyncio.run(upload_multiple(paths)) for path, file in zip(paths, files): print(f"{path} -> {file.id}") ``` ## List files ``` GET /v1/files ``` | Param | Type | Default | Description | | --------- | ------- | ------- | ---------------------------------------- | | `limit` | integer | `20` | Page size (`1`–`10000`). | | `order` | string | `desc` | Sort by creation time: `asc` or `desc`. | | `after` | string | — | Keyset cursor; start after this file id. | | `purpose` | string | — | Optional filter (`assistants`). | ```bash title="cURL" curl --request GET \ --url 'https://api.subq.ai/v1/files?limit=20&order=desc' \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const files = await client.files.list({ limit: 20, order: "desc" }); console.log(files.data); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) files = client.files.list(limit=20, order="desc") print(files.data) ``` ### Response ```json { "object": "list", "data": [ { "id": "file_abc123", "object": "file", "bytes": 12345, "created_at": 1753742400, "expires_at": null, "filename": "report.pdf", "purpose": "assistants", "status": "processed" } ], "first_id": "file_abc123", "last_id": "file_abc123", "has_more": false } ``` Paginate with `last_id` as the next `after` value until `has_more` is `false`. ## Retrieve file ``` GET /v1/files/{file_id} ``` ```bash title="cURL" curl --request GET \ --url https://api.subq.ai/v1/files/file_abc123 \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const file = await client.files.retrieve(process.env.SUBQ_FILE_ID ?? "file_abc123"); console.log(file); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) file = client.files.retrieve(os.getenv("SUBQ_FILE_ID", "file_abc123")) print(file) ``` Returns the File object, or `404` if missing or owned by another org. ## Delete file ``` DELETE /v1/files/{file_id} ``` Removes stored bytes and metadata. ```bash title="cURL" curl --request DELETE \ --url https://api.subq.ai/v1/files/file_abc123 \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const result = await client.files.delete(process.env.SUBQ_FILE_ID ?? "file_abc123"); console.log(result.deleted); ``` ```py title="Python" client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) result = client.files.delete(os.getenv("SUBQ_FILE_ID", "file_abc123"), extra_body={}) print(result.deleted) ``` ### Response ```json { "id": "file_abc123", "object": "file", "deleted": true } ``` ## Errors Errors use the OpenAI-compatible shape: ```json { "error": { "message": "No such File object: file_abc123", "type": "invalid_request_error", "code": "not_found", "param": null } } ``` | HTTP | `code` | When | | ----- | ----------------------- | --------------------------------------------------------------------------------- | | `400` | `validation_error` | Missing or invalid params | | `400` | `unsupported_file_type` | The bytes and filename don't identify a supported type | | `400` | `invalid_file_content` | Declared or named as a PNG, JPEG, or WebP image, but the bytes aren't that format | | `401` | `invalid_api_key` | Missing or invalid API key | | `403` | `org_suspended` | Organization is suspended or inactive | | `404` | `not_found` | File missing or owned by another org | | `413` | `file_too_large` | Upload exceeds 50 MiB, or 10 MiB for an image | ## Related - [Sending files](/using-the-api/file-inputs/) — referencing an uploaded file in a request - [Chat Completions API](/endpoints/chat-completions-api/) — `file` parts on `messages` - [Responses API](/endpoints/responses-api/) — `input_file` parts on `input` --- title: Models API description: List the model IDs available to your API key. --- Use the Models API to list the model IDs available to your API key. ## List models ``` GET /v1/models ``` ### Request ```bash title="cURL" curl --request GET \ --url https://api.subq.ai/v1/models \ --header "Authorization: Bearer $SUBQ_API_KEY" ``` ```ts title="TypeScript" import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.SUBQ_API_KEY, baseURL: "https://api.subq.ai/v1", }); const models = await client.models.list(); console.log(models.data.map((model) => model.id)); ``` ```py title="Python" import os from openai import OpenAI client = OpenAI( api_key=os.environ["SUBQ_API_KEY"], base_url="https://api.subq.ai/v1", ) models = client.models.list() print([model.id for model in models.data]) ``` ### Response The response follows the OpenAI-compatible list shape. Use a returned `id` with the endpoint that supports that model. ```json { "object": "list", "data": [ { "id": "subq-savant-1.4", "name": "SubQ Savant 1.4", "object": "model", "created": 0, "owned_by": "subquadratic" }, { "id": "subq-snap-1.3", "name": "SubQ Snap 1.3", "object": "model", "created": 0, "owned_by": "subquadratic" } ] } ``` For each model's endpoints, inputs, and pricing, see [Models](/using-the-api/models/). --- title: Use Savant in a coding agent description: Use SubQ Savant as the model in OpenCode, VS Code, Codex, and other coding agents. --- Any coding agent with an OpenAI-compatible provider setting can run on SubQ Savant (Preview) using these three values: | Setting | Value | | -------- | ------------------------ | | Base URL | `https://api.subq.ai/v1` | | API key | Your SubQ API key | | Model | `subq-savant-latest` | ## OpenCode SubQ ships with OpenCode. Connect it from the CLI: 1. Launch OpenCode: ```bash opencode ``` 2. Run `/connect`. 3. Select **SubQ**. 4. Paste your SubQ API key. 5. Select the model (currently **SubQ Savant 1.4**). 6. Select **Default** for **variant**. Once your key is saved, OpenCode uses SubQ Savant by default. Ask it to confirm with a check prompt: ```text Review this repository for error-handling gaps, edge cases, and maintainability issues, and list the highest-impact fixes. ``` ## VS Code These steps use the Chat (GitHub Copilot) in VS Code 1.148.0. On Copilot Business or Enterprise, an admin must first allow **Bring Your Own Language Model Key in VS Code**. 1. Open **Chat: Chat Settings** from the Command Palette and check `chat.agentHost.byokModels.enabled`. If it isn't already enabled, turn it on and restart VS Code. 2. Open **Chat: Manage Language Models** from the Command Palette, select **Add Models**, and choose **Custom Endpoint**. 3. Enter `SubQ` as the group name, add a display name, enter your SubQ API key, and select **Chat Completions** as the API type. 4. VS Code opens `chatLanguageModels.json`. In the `SubQ` group, set the `models` array to this; leave the rest of the file as is: ```json expand "models": [ { "id": "subq-savant-latest", "name": "SubQ Savant", "url": "https://api.subq.ai/v1/chat/completions", "toolCalling": true, "vision": true, "thinking": true, "maxInputTokens": 3872000, "maxOutputTokens": 128000 } ] ``` - `maxInputTokens` and `maxOutputTokens` add up to Savant's 4M context. - `thinking` stops VS Code from sending a `temperature`, which Savant rejects unless it's `1`. - Don't add a key here. The file's own `apiKey` line already points to the key from step 3. 5. Confirm the session target below the chat input is set to **Copilot**. Open the model picker in the chat input (for example, from **Copilot Fusion**), switch to the **SubQ** tab at the top, and select **SubQ Savant**. 6. Run a quick check in chat to verify end-to-end setup: ```text Review this repository for error-handling gaps, edge cases, and maintainability issues, and list the highest-impact fixes. ``` ## Codex These steps use the Codex CLI 0.173. 1. Store `SUBQ_API_KEY` in its own file and load it from your shell profile: ```bash mkdir -p ~/.config/subq echo 'export SUBQ_API_KEY="your_api_key_here"' > ~/.config/subq/env chmod 600 ~/.config/subq/env echo '[ -f "$HOME/.config/subq/env" ] && source "$HOME/.config/subq/env"' >> ~/.zshrc source ~/.zshrc ``` On bash, use `~/.bashrc` instead of `~/.zshrc`. 2. Create a model catalog for Savant (requires `jq`). This writes a catalog entry to `~/.codex/subq-models.json` with a 4M context window and sets the default reasoning level to `low`: ```bash codex debug models --bundled | jq '{models: [.models[0] | .slug = "subq-savant-latest" | .display_name = "SubQ Savant" | .context_window = 4000000 | .max_context_window = 4000000 | .default_reasoning_level = "low" | .supported_reasoning_levels = [ {effort: "low", description: "Fastest"}, {effort: "high", description: "Deeper"}, {effort: "max", description: "Deepest"}] | .service_tiers = [] | .default_service_tier = null | .additional_speed_tiers = [] | .apply_patch_tool_type = null | .supports_reasoning_summary_parameter = false | .support_verbosity = false]}' > ~/.codex/subq-models.json ``` 3. Add SubQ as a provider in `~/.codex/config.toml`. Keep the first three lines above `[model_providers.subq]`: ```toml title="~/.codex/config.toml" expand model = "subq-savant-latest" model_provider = "subq" model_catalog_json = "/Users/you/.codex/subq-models.json" [model_providers.subq] name = "SubQ" base_url = "https://api.subq.ai/v1" env_key = "SUBQ_API_KEY" wire_api = "responses" ``` - `model_catalog_json` needs the full path to the file from step 2. Replace `/Users/you` with your home directory (run `echo $HOME`). - `env_key` takes the variable's name, not the key itself. 4. If you've used Codex before, exit any open sessions and restart its background server to pick up the new config: ```bash codex app-server daemon restart ``` 5. Run a quick check from your project root to verify end-to-end setup: ```bash codex "Review this repository for error-handling gaps, edge cases, and maintainability issues, and list the highest-impact fixes." ```