Agents

#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

MethodPathPurpose
POST/public/agents/{agent_id}/chatSend a message and wait for the full reply
POST/public/agents/{agent_id}/streamSend a message and stream the reply as server-sent events
POST/public/agents/{agent_id}/sessionsStart a new conversation
GET/public/agents/{agent_id}/sessions/allList this key's conversations
GET/public/agents/{agent_id}/sessions/{session_id}/messagesRead 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:

StatusdetailCauseWhat to do
401"Not authenticated"No Authorization: Bearer headerSend the key.
401"Invalid or revoked API key"Unknown or revoked keyUse a valid key.
403"This API key does not have access to this agent."{agent_id} is not the key's agentUse the key's agent id.
404"Agent not found."The agent was deleted or deactivated, or the key's creator lost access to itAsk the agent's owner.
422validation error listA path parameter, query parameter or body field has the wrong type, or a required field is missingFix 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

POST{BASE_URL}/public/agents/{agent_id}/chat

Runs 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

FieldTypeRequiredMeaning
messagestringyesWhat the user says to the agent.
session_idintegernoThe session to continue. Omit it to start a new session.
timezonestringnoThe 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.
locationstringnoFree text, for example Berlin, Germany. Used only together with timezone.
contextobjectnoFacts 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"}
      }'
FieldTypeMeaning
responsestringThe agent's reply. Can be empty, for example when the turn ends with a question in user_choice.
session_idintegerThe session this turn belongs to. If you didn't send one, this is the new session.
sourcesarrayKnowledge base documents the reply drew on. [] if none. See Sources.
user_choiceobject or nullSet when the agent ended its turn by asking the user to pick an option. See Questions with options.
StatusBodyCauseWhat 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 keyStart a new session.
500{"detail": "An error occurred during agent execution."}The run failed, for example the AI provider was unavailableRetry. 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

POST{BASE_URL}/public/agents/{agent_id}/stream

Same 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.

Your server AI Studio Agent and tools POST /stream {message, session_id} run one turn data: {"type":"session"} tool_start {tool, input} tool call tool_end {tool} sources {knowledge_base_id, sources} text {content} text {content} (repeats) No "done" event: the server closes the response when the turn is over. On failure the last event is "error"
Events arrive as server-sent events. Only session, text and error are needed for a working chat.

Errors before the stream starts are normal HTTP responses with a JSON body, not events:

StatusBodyCause
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.

typeFieldsMeaning
sessionsession_id (integer)Always the first event. Store it if you started a new session.
textcontent (string)A piece of the reply. Append it to what you have. A piece can be several words.
thinkingcontent (string)A piece of the model's reasoning, on models that expose it. Not part of the reply.
tool_preparingtool (string)The model has started writing a call to this tool. A tool_start follows.
tool_starttool (string), input (object)The agent called a tool with these arguments.
tool_endtool (string)That tool finished. Its output is not sent.
sub_agent_startagent_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_endagent_name (string)The other agent finished.
skill_startskill_name (string), input (object)The agent loaded one of its skills (saved instructions).
skill_endskill_name (string)Done loading the skill.
sourcesknowledge_base_id (string), sources (array)Documents a search returned. Sent once per search, so the same document can appear in several events. See Sources.
filefile_id, filename, mime_type, download_url (strings)The agent made a file. One event per file.
imageimages (array of {id, filename, mime_type, download_url})The agent generated or edited images.
chartchart (object)A chart for you to draw. See Charts.
user_choicequestion (string), options (array), multi (boolean)The agent asks the user to choose. The turn ends here. See Questions with options.
sandbox_limitscope, 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.
errorcode (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

codeMeaningWhat to do
ai_key_invalidThe AI provider rejected AI Studio's key for this modelTell the agent's owner or your administrator. Retrying won't help.
ai_rate_limitedThe AI provider is receiving too many requestsWait a moment and send the message again.
ai_request_rejectedThe AI provider refused this request. message may include the reason.Read message. Change the request if you can, then retry.
ai_unavailableThe AI provider failed or timed outRetry shortly.
agent_budget_exceededThe agent reached its spending limitTry again after the limit resets.
agent_allowance_exceededThis key used up the allowance the agent's owner gave itTry again after the limit resets, or ask the owner to raise it.
org_budget_exceededThe organization of the key's creator reached its spending limitTry again after the limit resets.
org_member_limit_exceededThe key's creator reached their personal spending capTry again after the limit resets.
chat_failedAny other failureRetry. 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

POST{BASE_URL}/public/agents/{agent_id}/sessions

Creates 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.

FieldTypeRequiredMeaning
titlestringnoA 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

GET{BASE_URL}/public/agents/{agent_id}/sessions/all

Lists the sessions this key created for the agent, newest first.

NameTypeDefaultMeaning
skipinteger, 0 or more0How many sessions to skip, for paging.
limitinteger, 1 to 10050How 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

GET{BASE_URL}/public/agents/{agent_id}/sessions/{session_id}/messages

Returns 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": [].

FieldTypeMeaning
rolestring"user" or "assistant".
contentstringThe message text. An assistant message can have empty content if it only carries files, images, charts or a user_choice.
created_atstring or nullWhen the message was saved, in UTC.
attachmentsarrayAlways [] for sessions created through this API, which has no file upload.
filesarrayFiles 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.
imagesarrayAssistant messages only. Images the agent made.
chartsarrayChart objects, the same as the stream's chart event. See Charts.
tools_usedarray of stringsNames of the tools the agent used for this reply.
sub_agents_usedarrayOther agents it handed work to: {agent_name, tools_used}, plus agent_id when known.
used_skillarray of stringsNames of skills it loaded.
sourcesarrayKnowledge base documents cited, merged and numbered. See Sources.
code_runsarrayCode the agent ran: {language, code, exit_code, timed_out, stdout, stderr, files, error}.
thinkingstring or nullThe model's reasoning for this reply, on models that expose it.
user_choiceobject or nullAssistant 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.

StatusdetailCause
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.

FieldTypeMeaning
indexintegerCitation number (merged lists only).
document_idstringThe document's id.
filenamestringThe document's file name.
pagesarray of integersPages the cited text came from. Can be empty.
urlstring or nullA signed link to AI Studio's copy of the document. Valid for 6 hours. Opens inline in a browser.
web_urlstring or nullThe original file at the provider, for documents synced from a cloud folder. null for uploaded documents.
providerstring or nullWhere 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.

FieldTypeMeaning
chart_typestringThe kind of chart, for example bar.
titlestringThe chart's title.
dataarray of objectsThe rows.
encodingobjectWhich row field goes on which channel, for example {"x": "month", "y": "revenue"}.
optionsobjectExtra 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.

LinkPathValid forServed as
A file or image the agent madeGET {BASE_URL}/agents/generated-files/{file_id}?token=...30 daysA download (Content-Disposition: attachment)
A cited knowledge base documentGET {BASE_URL}/agents/kb-documents/{document_id}?token=...6 hoursInline, so a browser can show it
StatusdetailCauseWhat to do
401"Invalid or expired token"The token expired or doesn't match the fileRead the session history to get a fresh link.
404"File not found"The file no longer existsNone.

#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.

Checked before each turn Agent limitset by the ownerdaily or monthly Key allowanceset by the ownerper API key Organizationset by an adminwhole org Member limitset by an adminkey creator Turn runsall clear Any limit reached: 402, or an error event Limits reset at the start of the next UTC day or month.
A turn already running always finishes. Public callers never see amounts or reset times.

Public callers are never told amounts or reset times. You get:

  • Before a turn starts, from /chat or /stream: 402 with {"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 uses agent_budget_exceeded for both.
  • Once the turn starts (organization limits, or a limit reached in the meantime): from /chat, the same 402 with code set to agent_budget_exceeded, org_budget_exceeded or org_member_limit_exceeded; from /stream, an error event 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.

AI Studio developer documentation. Times are UTC and IDs are opaque strings.