#Agents API
Chat with an AI Studio agent from your own server, using an agent API key. You can get a whole reply in one response, or stream it as it is written, and you can keep conversations going across requests.
{BASE_URL} = https://studio.scaletechsolutions.ai/api/v1#Endpoints
| Method | Path | Purpose |
|---|---|---|
POST | /public/agents/{agent_id}/chat | Send a message and wait for the full reply |
POST | /public/agents/{agent_id}/stream | Send a message and stream the reply as server-sent events |
POST | /public/agents/{agent_id}/sessions | Start a new conversation |
GET | /public/agents/{agent_id}/sessions/all | List this key's conversations |
GET | /public/agents/{agent_id}/sessions/{session_id}/messages | Read one conversation's history |
Links to files the agent makes, images and cited documents are plain URLs that need no key. See Files, images and cited documents.
#Authentication
Every request needs the agent's API key:
Authorization: Bearer <agent api key>A key works for exactly one agent, and {agent_id} in the path must be that agent. See Authentication. These errors can come from any endpoint on this page:
| Status | detail | Cause | What to do |
|---|---|---|---|
| 401 | "Not authenticated" | No Authorization: Bearer header | Send the key. |
| 401 | "Invalid or revoked API key" | Unknown or revoked key | Use a valid key. |
| 403 | "This API key does not have access to this agent." | {agent_id} is not the key's agent | Use the key's agent id. |
| 404 | "Agent not found." | The agent was deleted or deactivated, or the key's creator lost access to it | Ask the agent's owner. |
| 422 | validation error list | A path parameter, query parameter or body field has the wrong type, or a required field is missing | Fix the request. |
#Sessions
A session is one conversation. The agent remembers earlier messages in the same session.
- You don't have to create sessions yourself. If you send a message without
session_id, a new session is created and its id comes back in the response (or as the first stream event). Store that id and send it with the next message. - A session belongs to the API key that created it. Only that key can continue it, list it or read its history. Any other key, even one for the same agent, gets
404 "Session not found.". The owner's own chats in the AI Studio app are never reachable through the API. - If you rotate keys, sessions stay with the old key. See Rotating a key.
- A turn that fails is removed from the session's history, so you can send the same message again.
#Send a message and wait for the reply
{BASE_URL}/public/agents/{agent_id}/chatRuns one turn of the agent and returns the whole reply when it is done. A turn can take a long time if the agent uses tools; set your HTTP client's timeout accordingly, or use the stream endpoint.
Request body
| Field | Type | Required | Meaning |
|---|---|---|---|
message | string | yes | What the user says to the agent. |
session_id | integer | no | The session to continue. Omit it to start a new session. |
timezone | string | no | The user's IANA time zone, for example Europe/Berlin. The agent is told the user's current local date and time. An unknown name is ignored. |
location | string | no | Free text, for example Berlin, Germany. Used only together with timezone. |
context | object | no | Facts about the caller for this turn only, for example {"customer_id": "C-91", "plan": "pro"}. Added to the agent's instructions as "external context". Not saved in the history, so send it with every message that needs it. |
curl -X POST "{BASE_URL}/public/agents/42/chat" \
-H "Authorization: Bearer $AI_STUDIO_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{
"message": "Which invoices are overdue?",
"session_id": 1187,
"timezone": "Asia/Kolkata",
"location": "Ahmedabad, India",
"context": {"customer_id": "C-91"}
}'| Field | Type | Meaning |
|---|---|---|
response | string | The agent's reply. Can be empty, for example when the turn ends with a question in user_choice. |
session_id | integer | The session this turn belongs to. If you didn't send one, this is the new session. |
sources | array | Knowledge base documents the reply drew on. [] if none. See Sources. |
user_choice | object or null | Set when the agent ended its turn by asking the user to pick an option. See Questions with options. |
| Status | Body | Cause | What to do |
|---|---|---|---|
| 402 | {"detail": "This agent is unavailable right now. Please try again later.", "code": "..."} | A spending limit is reached. See Spending limits. | Try again later, after the limit resets. |
| 404 | {"detail": "Session not found."} | session_id does not exist, belongs to another agent, or was not created by this key | Start a new session. |
| 500 | {"detail": "An error occurred during agent execution."} | The run failed, for example the AI provider was unavailable | Retry. If it keeps failing, report the time, agent id and session id. |
If you omitted session_id and the turn then fails with a 500, the new session was still created but holds no messages.
#Stream a reply
{BASE_URL}/public/agents/{agent_id}/streamSame request as /chat, but the reply arrives as server-sent events while the agent works. Use it when a person is waiting, or when a proxy between you and AI Studio might time out a long request.
curl -N -X POST "{BASE_URL}/public/agents/42/stream" \
-H "Authorization: Bearer $AI_STUDIO_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{"message": "Summarise this week'\''s overdue invoices"}'Response 200 OK, Content-Type: text/event-stream:
data: {"type": "session", "session_id": 1188}
data: {"type": "tool_start", "tool": "rag_search", "input": {"query": "overdue invoices this week"}}
data: {"type": "tool_end", "tool": "rag_search"}
data: {"type": "sources", "knowledge_base_id": "...", "sources": [...]}
data: {"type": "text", "content": "Three invoices are "}
data: {"type": "text", "content": "overdue this week: ..."}Every event is data: followed by a JSON object and a blank line. The type field says what the event is. There are no event: or id: lines.
Errors before the stream starts are normal HTTP responses with a JSON body, not events:
| Status | Body | Cause |
|---|---|---|
| 402 | {"detail": "This agent is unavailable right now. Please try again later.", "code": "agent_budget_exceeded"} | The agent's spending limit, or this key's allowance on it, is reached |
| 404 | {"detail": "Session not found."} | session_id does not exist, belongs to another agent, or was not created by this key |
Once the stream has started, the status is always 200 and failures arrive as error events.
#Event types
You only need session, text and error to build a working chat. The others let you show what the agent is doing.
type | Fields | Meaning |
|---|---|---|
session | session_id (integer) | Always the first event. Store it if you started a new session. |
text | content (string) | A piece of the reply. Append it to what you have. A piece can be several words. |
thinking | content (string) | A piece of the model's reasoning, on models that expose it. Not part of the reply. |
tool_preparing | tool (string) | The model has started writing a call to this tool. A tool_start follows. |
tool_start | tool (string), input (object) | The agent called a tool with these arguments. |
tool_end | tool (string) | That tool finished. Its output is not sent. |
sub_agent_start | agent_name (string), input (object) | The agent handed part of the work to another agent. Its tool calls arrive as tool_start and tool_end until sub_agent_end. Its own text is not streamed. |
sub_agent_end | agent_name (string) | The other agent finished. |
skill_start | skill_name (string), input (object) | The agent loaded one of its skills (saved instructions). |
skill_end | skill_name (string) | Done loading the skill. |
sources | knowledge_base_id (string), sources (array) | Documents a search returned. Sent once per search, so the same document can appear in several events. See Sources. |
file | file_id, filename, mime_type, download_url (strings) | The agent made a file. One event per file. |
image | images (array of {id, filename, mime_type, download_url}) | The agent generated or edited images. |
chart | chart (object) | A chart for you to draw. See Charts. |
user_choice | question (string), options (array), multi (boolean) | The agent asks the user to choose. The turn ends here. See Questions with options. |
sandbox_limit | scope, resets_at, message (strings) | The agent tried to run code but the monthly code-running time is used up. The agent explains this in its reply. |
error | code (string), message (string) | The turn failed. Nothing from this turn is kept in the history. |
Which events you see depends on the agent's tools. Ignore event types you don't recognise, so new ones don't break your code.
#error event codes
code | Meaning | What to do |
|---|---|---|
ai_key_invalid | The AI provider rejected AI Studio's key for this model | Tell the agent's owner or your administrator. Retrying won't help. |
ai_rate_limited | The AI provider is receiving too many requests | Wait a moment and send the message again. |
ai_request_rejected | The AI provider refused this request. message may include the reason. | Read message. Change the request if you can, then retry. |
ai_unavailable | The AI provider failed or timed out | Retry shortly. |
agent_budget_exceeded | The agent reached its spending limit | Try again after the limit resets. |
agent_allowance_exceeded | This key used up the allowance the agent's owner gave it | Try again after the limit resets, or ask the owner to raise it. |
org_budget_exceeded | The organization of the key's creator reached its spending limit | Try again after the limit resets. |
org_member_limit_exceeded | The key's creator reached their personal spending cap | Try again after the limit resets. |
chat_failed | Any other failure | Retry. If it keeps happening, report it with the time, agent id and session id. |
For spending-limit codes, message is always "This agent is unavailable right now. Please try again later.". Branch on code, not on message.
#Read the stream
const res = await fetch(`${BASE_URL}/public/agents/${agentId}/stream`, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ message: "Hello" }),
});
for await (const chunk of res.body) process.stdout.write(chunk); // raw events#Start a session
{BASE_URL}/public/agents/{agent_id}/sessionsCreates an empty session. You only need this if you want to set a title, or to have the id before the first message. Otherwise just send a message without session_id.
| Field | Type | Required | Meaning |
|---|---|---|---|
title | string | no | A label for the conversation. Defaults to "Public API Session". |
Send {} for no title. The body itself is required.
curl -X POST "{BASE_URL}/public/agents/42/sessions" \
-H "Authorization: Bearer $AI_STUDIO_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{"title": "Support ticket 8842"}'created_at is in UTC and has no time zone suffix.
#List sessions
{BASE_URL}/public/agents/{agent_id}/sessions/allLists the sessions this key created for the agent, newest first.
| Name | Type | Default | Meaning |
|---|---|---|---|
skip | integer, 0 or more | 0 | How many sessions to skip, for paging. |
limit | integer, 1 to 100 | 50 | How many sessions to return. |
curl "{BASE_URL}/public/agents/42/sessions/all?skip=0&limit=20" \
-H "Authorization: Bearer $AI_STUDIO_AGENT_KEY"A limit outside 1 to 100 or a negative skip is a 422.
#Read a conversation's history
{BASE_URL}/public/agents/{agent_id}/sessions/{session_id}/messagesReturns every message in a session, oldest first. Use it to show a conversation again after a reload, or to get files and charts after a /chat call.
curl "{BASE_URL}/public/agents/42/sessions/1187/messages" \
-H "Authorization: Bearer $AI_STUDIO_AGENT_KEY"{
"session_id": 1187,
"messages": [
{
"role": "user",
"content": "Which invoices are overdue?",
"created_at": "2026-11-27T10:21:02.118402+00:00",
"attachments": [], "files": [], "charts": [],
"tools_used": [], "sub_agents_used": [], "used_skill": [],
"sources": [], "code_runs": [], "thinking": null
},
{
"role": "assistant",
"content": "Three invoices are overdue: INV-1042, INV-1057 and INV-1060.",
"created_at": "2026-11-27T10:21:09.904551+00:00",
"attachments": [], "files": [], "charts": [], "images": [],
"tools_used": ["rag_search"],
"sub_agents_used": [], "used_skill": [],
"sources": [ { "index": 1, "document_id": "c1b2b054-...", "filename": "invoices-q3.pdf", "pages": [2, 4] } ],
"code_runs": [], "thinking": null, "user_choice": null
}
]
}A new session with no messages returns "messages": [].
| Field | Type | Meaning |
|---|---|---|
role | string | "user" or "assistant". |
content | string | The message text. An assistant message can have empty content if it only carries files, images, charts or a user_choice. |
created_at | string or null | When the message was saved, in UTC. |
attachments | array | Always [] for sessions created through this API, which has no file upload. |
files | array | Files the agent made in this reply: {id, filename, mime_type, download_url}. The id field is id here and file_id in the stream's file event. |
images | array | Assistant messages only. Images the agent made. |
charts | array | Chart objects, the same as the stream's chart event. See Charts. |
tools_used | array of strings | Names of the tools the agent used for this reply. |
sub_agents_used | array | Other agents it handed work to: {agent_name, tools_used}, plus agent_id when known. |
used_skill | array of strings | Names of skills it loaded. |
sources | array | Knowledge base documents cited, merged and numbered. See Sources. |
code_runs | array | Code the agent ran: {language, code, exit_code, timed_out, stdout, stderr, files, error}. |
thinking | string or null | The model's reasoning for this reply, on models that expose it. |
user_choice | object or null | Assistant messages only. A question with options the agent asked. |
Download links are signed again on every call, so a link from the history always works even if the one you got during the stream has expired.
| Status | detail | Cause |
|---|---|---|
| 404 | "Session not found." | The session does not exist, belongs to another agent, or was not created by this key |
#Response details
#Sources
When the agent searches a knowledge base, the documents it found are returned as sources. In the /chat response and the history they are merged per document and numbered from 1. In the stream, each sources event lists what one search returned, not yet merged.
| Field | Type | Meaning |
|---|---|---|
index | integer | Citation number (merged lists only). |
document_id | string | The document's id. |
filename | string | The document's file name. |
pages | array of integers | Pages the cited text came from. Can be empty. |
url | string or null | A signed link to AI Studio's copy of the document. Valid for 6 hours. Opens inline in a browser. |
web_url | string or null | The original file at the provider, for documents synced from a cloud folder. null for uploaded documents. |
provider | string or null | Where a synced document came from, for example onedrive. null for uploaded documents. |
In the stream, source objects can carry more fields than this table lists. Rely only on these.
#Charts
A chart is data for you to draw with your own chart library. AI Studio does not render it.
| Field | Type | Meaning |
|---|---|---|
chart_type | string | The kind of chart, for example bar. |
title | string | The chart's title. |
data | array of objects | The rows. |
encoding | object | Which row field goes on which channel, for example {"x": "month", "y": "revenue"}. |
options | object | Extra display options. Can be {}. |
#Questions with options
Some agents can stop and ask the user to choose. The turn then ends with a user_choice (an event in the stream, a field in the /chat response and in the history):
{
"question": "Which report do you want?",
"options": [
"Weekly",
{"label": "Monthly", "description": "Includes the trend chart"}
],
"multi": false
}Each option is either a string or an object with label and description. multi is true when the user may pick more than one. To answer, send the chosen label (or labels) as the next message in the same session.
#Files, images and cited documents
Links in file and image events, in files and images in the history, and in a source's url, point at AI Studio and carry a signed token. They need no API key or login, so you can fetch them from your server or hand them to a user's browser.
| Link | Path | Valid for | Served as |
|---|---|---|---|
| A file or image the agent made | GET {BASE_URL}/agents/generated-files/{file_id}?token=... | 30 days | A download (Content-Disposition: attachment) |
| A cited knowledge base document | GET {BASE_URL}/agents/kb-documents/{document_id}?token=... | 6 hours | Inline, so a browser can show it |
| Status | detail | Cause | What to do |
|---|---|---|---|
| 401 | "Invalid or expired token" | The token expired or doesn't match the file | Read the session history to get a fresh link. |
| 404 | "File not found" | The file no longer exists | None. |
#Spending limits
The agent's owner can set daily or monthly spending limits on the agent, and an allowance per API key. The organization of the key's creator can also have limits. When a blocking limit is reached, new turns are refused until the limit resets (at the start of the next UTC day or month). A turn that is already running finishes.
Public callers are never told amounts or reset times. You get:
- Before a turn starts, from
/chator/stream:402with{"detail": "This agent is unavailable right now. Please try again later.", "code": "agent_budget_exceeded"}. This check covers the agent's limit and your key's allowance, and usesagent_budget_exceededfor both. - Once the turn starts (organization limits, or a limit reached in the meantime): from
/chat, the same402withcodeset toagent_budget_exceeded,org_budget_exceededororg_member_limit_exceeded; from/stream, anerrorevent with one of the error codes.
#Database access
An agent can be given access to a PostgreSQL database its owner connected to AI Studio. Through the API, the agent can query such a database only when both are true:
- the API key was created by the agent's owner, and
- the owner granted that database to this agent.
A key created by someone the agent was shared with never gets database access. Through the API, database access is always read-only: the tools that insert, update or delete rows are never available, whatever the grant allows. If the agent hands work to another agent, that agent needs its own grant.
Anything the agent reads from the database can appear in its reply and in tool_start inputs (for example the SQL it ran). Treat the key accordingly. See Databases.
#Who the agent runs as
Every turn runs as the user who created the API key. The agent uses that user's connected apps and knowledge bases as configured on the agent, and spending is recorded against that user and the key. See What one key can access.