import json, os, httpx
with httpx.stream(
"POST", "https://api.onecortex.io/v1/agents/agt_.../invoke",
headers={"Authorization": f"Bearer {os.environ['ONECORTEX_API_KEY']}"},
json={"prompt": "hello", "stream": True},
) as response:
event = None
for line in response.iter_lines():
if line.startswith("event: "):
event = line[7:]
elif line.startswith("data: "):
data = json.loads(line[6:])
if event == "text":
print(data["delta"], end="", flush=True)
elif event == "tool_call_start":
print(f"[calling {data['name']}]")
elif event == "done":
print()
elif event == "error":
# Handle this, or a failure looks like an empty success.
raise RuntimeError(data["message"])
const response = await fetch('https://api.onecortex.io/v1/agents/agt_.../invoke', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.ONECORTEX_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: 'hello', stream: true }),
})
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
// Frames are separated by a blank line. A partial frame stays buffered.
const frames = buffer.split('\n\n')
buffer = frames.pop() ?? ''
for (const frame of frames) {
const event = frame.match(/^event: (.*)$/m)?.[1]
const data = frame.match(/^data: (.*)$/m)?.[1]
if (!event || !data) continue
if (event === 'text') process.stdout.write(JSON.parse(data).delta)
if (event === 'tool_call_start') console.log(`[calling ${JSON.parse(data).name}]`)
if (event === 'done') console.log()
// Handle this, or a failure looks like an empty success.
if (event === 'error') throw new Error(JSON.parse(data).message)
}
}
curl -N https://api.onecortex.io/v1/agents/agt_.../invoke \
-H "Authorization: Bearer $ONECORTEX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"hello","stream":true}'
{
"status": "completed",
"result": "<string>",
"events": [
{
"v": 1,
"type": "text",
"delta": "<string>"
}
],
"sessionId": "<string>",
"agentId": "<string>",
"versionNumber": 123,
"requestId": "<string>",
"durationMs": 123,
"interrupts": [
{
"id": "<string>",
"reason": "<string>",
"message": "<string>",
"responseSchema": {},
"expiresAt": "2023-11-07T05:31:56Z"
}
],
"error": {
"code": "<string>",
"message": "<string>"
}
}{
"error": {
"code": "invalid_request",
"message": "Request must include a 'prompt' field, or a 'resume' to answer a paused run.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "unauthenticated",
"message": "A valid Onecortex API key is required.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "not_found",
"message": "That agent does not exist.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "rate_limited",
"message": "Too many requests. Try again in 3 seconds.",
"requestId": "req_01K0000000000000000000000"
}
}{
"status": "failed",
"result": "",
"error": {
"code": "agent_error",
"message": "ValueError: the agent was asked to raise"
},
"events": [],
"sessionId": "01K0000000000000000000000",
"agentId": "agt_01K0000000000000000000000",
"versionNumber": 1,
"requestId": "req_01K0000000000000000000000",
"durationMs": 31
}{
"error": {
"code": "agent_unavailable",
"message": "This agent is not available right now. Try again.",
"requestId": "req_01K0000000000000000000000"
}
}Invoke an agent
Send a prompt to a deployed agent. With stream true, or Accept: text/event-stream, the response is a stream of server sent events, one per event, ending in exactly one done, interrupt or error. Otherwise it is one JSON body once the run is over.
A run that ends in interrupt paused to ask a person something. Answer it with resume and the same sessionId: see Human in the loop.
A stream that has started has sent 200 OK and cannot change it: a failure after that arrives as event: error. Handle it.
Every field beyond prompt, sessionId, stream, messages and resume reaches the agent unchanged, as params.
The most common errors are listed here. Every code, its status and what to do is on Errors.
import json, os, httpx
with httpx.stream(
"POST", "https://api.onecortex.io/v1/agents/agt_.../invoke",
headers={"Authorization": f"Bearer {os.environ['ONECORTEX_API_KEY']}"},
json={"prompt": "hello", "stream": True},
) as response:
event = None
for line in response.iter_lines():
if line.startswith("event: "):
event = line[7:]
elif line.startswith("data: "):
data = json.loads(line[6:])
if event == "text":
print(data["delta"], end="", flush=True)
elif event == "tool_call_start":
print(f"[calling {data['name']}]")
elif event == "done":
print()
elif event == "error":
# Handle this, or a failure looks like an empty success.
raise RuntimeError(data["message"])
const response = await fetch('https://api.onecortex.io/v1/agents/agt_.../invoke', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.ONECORTEX_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: 'hello', stream: true }),
})
const reader = response.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
// Frames are separated by a blank line. A partial frame stays buffered.
const frames = buffer.split('\n\n')
buffer = frames.pop() ?? ''
for (const frame of frames) {
const event = frame.match(/^event: (.*)$/m)?.[1]
const data = frame.match(/^data: (.*)$/m)?.[1]
if (!event || !data) continue
if (event === 'text') process.stdout.write(JSON.parse(data).delta)
if (event === 'tool_call_start') console.log(`[calling ${JSON.parse(data).name}]`)
if (event === 'done') console.log()
// Handle this, or a failure looks like an empty success.
if (event === 'error') throw new Error(JSON.parse(data).message)
}
}
curl -N https://api.onecortex.io/v1/agents/agt_.../invoke \
-H "Authorization: Bearer $ONECORTEX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"hello","stream":true}'
{
"status": "completed",
"result": "<string>",
"events": [
{
"v": 1,
"type": "text",
"delta": "<string>"
}
],
"sessionId": "<string>",
"agentId": "<string>",
"versionNumber": 123,
"requestId": "<string>",
"durationMs": 123,
"interrupts": [
{
"id": "<string>",
"reason": "<string>",
"message": "<string>",
"responseSchema": {},
"expiresAt": "2023-11-07T05:31:56Z"
}
],
"error": {
"code": "<string>",
"message": "<string>"
}
}{
"error": {
"code": "invalid_request",
"message": "Request must include a 'prompt' field, or a 'resume' to answer a paused run.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "unauthenticated",
"message": "A valid Onecortex API key is required.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "not_found",
"message": "That agent does not exist.",
"requestId": "req_01K0000000000000000000000"
}
}{
"error": {
"code": "rate_limited",
"message": "Too many requests. Try again in 3 seconds.",
"requestId": "req_01K0000000000000000000000"
}
}{
"status": "failed",
"result": "",
"error": {
"code": "agent_error",
"message": "ValueError: the agent was asked to raise"
},
"events": [],
"sessionId": "01K0000000000000000000000",
"agentId": "agt_01K0000000000000000000000",
"versionNumber": 1,
"requestId": "req_01K0000000000000000000000",
"durationMs": 31
}{
"error": {
"code": "agent_unavailable",
"message": "This agent is not available right now. Try again.",
"requestId": "req_01K0000000000000000000000"
}
}Authorizations
Path Parameters
Body
At most 1 MB. Carries a prompt, a resume, or both. Any other field reaches the agent unchanged, as params.
Response
The run completed, or paused with an interrupt. JSON, or a stream of events.