> ## Documentation Index
> Fetch the complete documentation index at: https://docs.onecortex.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 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` or `error`. Otherwise it is one JSON body once the run is over.

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` and `messages` reaches the agent unchanged, as `params`.




## OpenAPI

````yaml /openapi.yaml post /v1/agents/{agentId}/invoke
openapi: 3.1.0
info:
  title: Onecortex API
  version: '1'
  description: Invoke a deployed agent. This is the whole public API.
servers:
  - url: https://api.onecortex.io
security:
  - apiKey: []
paths:
  /v1/agents/{agentId}/invoke:
    post:
      summary: Invoke an agent
      description: >
        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` or `error`. Otherwise it is one
        JSON body once the run is over.


        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` and `messages`
        reaches the agent unchanged, as `params`.
      operationId: invokeAgent
      parameters:
        - name: agentId
          in: path
          required: true
          description: The agent's ID, from its page in the dashboard.
          schema:
            type: string
            example: agt_01K0000000000000000000000
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InvokeRequest'
            example:
              prompt: hello
      responses:
        '200':
          description: The run completed. JSON, or a stream of events.
          headers:
            X-Request-Id:
              $ref: '#/components/headers/RequestId'
            X-Onecortex-Session-Id:
              description: The session ID, echoed or generated.
              schema:
                type: string
            X-RateLimit-Remaining:
              description: Requests left in the organization's burst allowance.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvokeResponse'
            text/event-stream:
              schema:
                type: string
                description: >-
                  One frame per event: `event:` names its type and `data:` holds
                  the event as JSON. A `: ping` comment arrives every 15 seconds
                  while the agent is silent. See the event schemas under
                  components.
                example: >
                  event: text

                  data: {"v":1,"type":"text","delta":"You said: hello"}


                  event: done

                  data: {"v":1,"type":"done","result":"You said:
                  hello","sessionId":"01K...","versionNumber":1,"durationMs":212}
        '400':
          $ref: '#/components/responses/Error'
        '401':
          $ref: '#/components/responses/Error'
        '403':
          $ref: '#/components/responses/Error'
        '404':
          $ref: '#/components/responses/Error'
        '409':
          $ref: '#/components/responses/Error'
        '410':
          $ref: '#/components/responses/Error'
        '413':
          $ref: '#/components/responses/Error'
        '429':
          description: Over a rate limit. Wait for `Retry-After`.
          headers:
            Retry-After:
              description: Whole seconds to wait.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorBody'
        '500':
          $ref: '#/components/responses/Error'
        '502':
          description: >-
            The agent raised, or could not be read. A failed run's body is the
            invoke response, with `status` failed and `error` set.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/InvokeResponse'
                  - $ref: '#/components/schemas/ErrorBody'
        '503':
          $ref: '#/components/responses/Error'
      x-codeSamples:
        - lang: python
          label: Python
          source: |
            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"])
        - lang: javascript
          label: TypeScript
          source: >
            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)
              }
            }
        - lang: bash
          label: curl
          source: |
            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}'
components:
  schemas:
    InvokeRequest:
      type: object
      required:
        - prompt
      additionalProperties: true
      description: At most 1 MB. Any other field reaches the agent unchanged, as `params`.
      properties:
        prompt:
          type: string
          description: The input to the agent.
        sessionId:
          type: string
          minLength: 1
          maxLength: 256
          description: >-
            Your key for a conversation. Calls with the same one reach the same
            running instance. Generated when absent.
        stream:
          type: boolean
          description: True for server sent events. Absent, the `Accept` header decides.
        messages:
          type: array
          description: The conversation as you hold it, for an agent that reads history.
          items:
            type: object
            required:
              - role
              - content
            properties:
              role:
                type: string
              content:
                type: string
        metadata:
          type: object
          additionalProperties: true
          description: >-
            Anything the agent should see, at most 4 KB as JSON. Reaches the
            agent in `params`.
    InvokeResponse:
      type: object
      required:
        - status
        - result
        - events
        - sessionId
        - agentId
        - versionNumber
        - requestId
        - durationMs
      properties:
        status:
          type: string
          enum:
            - completed
            - failed
        result:
          type: string
          description: The whole reply. On a failed run, the text sent before it failed.
        error:
          type: object
          description: Present when `status` is failed.
          required:
            - code
            - message
          properties:
            code:
              type: string
            message:
              type: string
        events:
          type: array
          description: >-
            The tool calls, tool results and steps, in order. Text is in
            `result`.
          items:
            $ref: '#/components/schemas/Event'
        sessionId:
          type: string
        agentId:
          type: string
        versionNumber:
          type: integer
        requestId:
          type: string
        durationMs:
          type: integer
    ErrorBody:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
            - requestId
          properties:
            code:
              type: string
              enum:
                - validation_failed
                - invalid_request
                - unauthenticated
                - forbidden
                - organization_suspended
                - not_found
                - agent_not_ready
                - agent_not_deployed
                - agent_deleted
                - payload_too_large
                - rate_limited
                - internal_error
                - agent_error
                - upstream_error
                - service_unavailable
                - agent_unavailable
                - capacity_exceeded
            message:
              type: string
            details:
              type: object
              additionalProperties: true
            requestId:
              type: string
    Event:
      description: One event of a run. Every event carries `v`, which is 1, and `type`.
      oneOf:
        - $ref: '#/components/schemas/TextEvent'
        - $ref: '#/components/schemas/ToolCallStartEvent'
        - $ref: '#/components/schemas/ToolCallArgsEvent'
        - $ref: '#/components/schemas/ToolCallEndEvent'
        - $ref: '#/components/schemas/ToolResultEvent'
        - $ref: '#/components/schemas/StepEvent'
        - $ref: '#/components/schemas/DoneEvent'
        - $ref: '#/components/schemas/ErrorEvent'
    TextEvent:
      type: object
      required:
        - v
        - type
        - delta
      properties:
        v:
          const: 1
        type:
          const: text
        delta:
          type: string
    ToolCallStartEvent:
      type: object
      required:
        - v
        - type
        - id
        - name
      properties:
        v:
          const: 1
        type:
          const: tool_call_start
        id:
          type: string
        name:
          type: string
    ToolCallArgsEvent:
      type: object
      required:
        - v
        - type
        - id
        - delta
      properties:
        v:
          const: 1
        type:
          const: tool_call_args
        id:
          type: string
        delta:
          type: string
          description: A piece of the arguments
          as JSON text.: null
    ToolCallEndEvent:
      type: object
      required:
        - v
        - type
        - id
      properties:
        v:
          const: 1
        type:
          const: tool_call_end
        id:
          type: string
    ToolResultEvent:
      type: object
      required:
        - v
        - type
        - id
        - output
      properties:
        v:
          const: 1
        type:
          const: tool_result
        id:
          type: string
        output:
          type: string
          description: At most 64 KB.
        isError:
          type: boolean
    StepEvent:
      type: object
      required:
        - v
        - type
        - name
      properties:
        v:
          const: 1
        type:
          enum:
            - step_start
            - step_end
        name:
          type: string
    DoneEvent:
      type: object
      required:
        - v
        - type
        - result
      properties:
        v:
          const: 1
        type:
          const: done
        result:
          type: string
        sessionId:
          type: string
          description: On the stream only.
        versionNumber:
          type: integer
          description: On the stream only.
        durationMs:
          type: integer
          description: On the stream only.
    ErrorEvent:
      type: object
      required:
        - v
        - type
        - code
        - message
      properties:
        v:
          const: 1
        type:
          const: error
        code:
          type: string
        message:
          type: string
  headers:
    RequestId:
      description: The request's ID, `req_...`. Quote it to support.
      schema:
        type: string
  responses:
    Error:
      description: The request was refused before the run started.
      headers:
        X-Request-Id:
          $ref: '#/components/headers/RequestId'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBody'
  securitySchemes:
    apiKey:
      type: http
      scheme: bearer
      description: An Onecortex API key, `oc_live_...`, from API keys in the dashboard.

````