NeuroAPI
Best practicesExamples

Examples

Copy-paste recipes for Q&A, multi-turn chat, streaming, retries, mode selection, system prompts, structured output, and a thin TypeScript client.

Each recipe targets https://api.neurobro.ai/api/v1 and assumes NEUROAPI_KEY holds your secret. Recipes only call /agent/ask and /health; pair them with the API reference for the full request and response schemas.

1. Simple Q&A (sync)

Use the sync path when the answer is short and you don't need to render tokens as they arrive.

curl -s https://api.neurobro.ai/api/v1/agent/ask \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $NEUROAPI_KEY" \
  -d '{"prompt": "Summarise the latest macroeconomic outlook for the eurozone in one sentence."}' | jq
const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.NEUROAPI_KEY!,
  },
  body: JSON.stringify({
    prompt: "Summarise the latest macroeconomic outlook for the eurozone in one sentence.",
  }),
})
const { answer, request_id, usage } = await res.json()
import os, httpx

res = httpx.post(
    "https://api.neurobro.ai/api/v1/agent/ask",
    headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
    json={"prompt": "Summarise the latest macroeconomic outlook for the eurozone in one sentence."},
    timeout=300,
)
data = res.json()

The response is a single AgentAskResponse document with answer, mode, request_id, and usage.

2. Multi-turn chat

The API is stateless - the caller owns the conversation. Pass prior turns in message_history on every request. Roles are "user" and "assistant". "system", "developer", "tool", and "function" turns are accepted but ignored; send instructions in system_prompt.

curl -s https://api.neurobro.ai/api/v1/agent/ask \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $NEUROAPI_KEY" \
  -d '{
    "prompt": "How did their gross margins evolve over the same period?",
    "message_history": [
      {"role": "user", "content": "Compare AAPL and MSFT on FY2024 earnings growth."},
      {"role": "assistant", "content": "Both delivered double-digit YoY revenue growth, with..."}
    ]
  }' | jq
type Turn = { role: "user" | "assistant"; content: string }

async function ask(prompt: string, history: Turn[]) {
  const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": process.env.NEUROAPI_KEY!,
    },
    body: JSON.stringify({ prompt, message_history: history }),
  })
  return res.json()
}
import os, httpx

def ask(prompt: str, history: list[dict]) -> dict:
    res = httpx.post(
        "https://api.neurobro.ai/api/v1/agent/ask",
        headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
        json={"prompt": prompt, "message_history": history},
        timeout=300,
    )
    return res.json()

Persist the transcript on your side, and trim the oldest turns once the combined token budget gets large. message_history accepts at most 50 messages.

3. Streaming via Server-Sent Events

Pass "stream": true and the response is text/event-stream. Every event is a data: line holding one JSON object; the stream ends with data: [DONE]\n\n. The X-Request-Id response header carries the same id you'd see in a sync response - capture it for support tickets.

A typical stream looks like this:

data: {"type":"status_update","data":{"answer":null,"usage":null}}
data: {"type":"status_update","data":{"answer":{"chunk":{"content":"NVDA is "}},"usage":null}}
data: {"type":"status_update","data":{"answer":{"chunk":{"content":"holding above"}},"usage":null}}
data: {"type":"status_update","data":{"answer":null,"usage":{"prompt_tokens":124,"completion_tokens":256,"cached_tokens":80,"cost_units":2}}}
data: {"type":"complete","data":{"answer":null,"usage":null}}
data: [DONE]
  • type is status_update while the agent works and complete once the answer is finished.
  • data.answer.chunk.content is the next piece of the answer text. Append the pieces in order to build the full answer. data.answer is null on progress events that carry no text.
  • data.usage arrives once, near the end, with the same fields as usage on a non-streaming response.
  • If the run fails, the last event is data: {"type":"error","message":"agent run failed"} and there is no [DONE]. Only [DONE] means the answer is complete.
curl -N https://api.neurobro.ai/api/v1/agent/ask \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $NEUROAPI_KEY" \
  -d '{"prompt": "Walk me through a top-down technical read on NVDA right now.", "stream": true}'
const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.NEUROAPI_KEY!,
  },
  body: JSON.stringify({
    prompt: "Walk me through a top-down technical read on NVDA right now.",
    stream: true,
  }),
})

const requestId = res.headers.get("x-request-id")
const reader = res.body!.getReader()
const decoder = new TextDecoder()
let buffer = ""

read: while (true) {
  const { value, done } = await reader.read()
  if (done) break
  buffer += decoder.decode(value, { stream: true })

  let nl: number
  while ((nl = buffer.indexOf("\n\n")) !== -1) {
    const frame = buffer.slice(0, nl)
    buffer = buffer.slice(nl + 2)
    const payload = frame.startsWith("data: ") ? frame.slice(6) : frame
    if (payload === "[DONE]") break read
    const event = JSON.parse(payload)
    if (event.type === "error") throw new Error(event.message)
    process.stdout.write(event.data.answer?.chunk.content ?? "")
  }
}
import json, os, httpx

with httpx.stream(
    "POST",
    "https://api.neurobro.ai/api/v1/agent/ask",
    headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
    json={
        "prompt": "Walk me through a top-down technical read on NVDA right now.",
        "stream": True,
    },
    timeout=None,
) as res:
    request_id = res.headers.get("x-request-id")
    for line in res.iter_lines():
        if not line.startswith("data: "):
            continue
        payload = line[len("data: "):]
        if payload == "[DONE]":
            break
        event = json.loads(payload)
        if event["type"] == "error":
            raise RuntimeError(event["message"])
        answer = event["data"]["answer"]
        if answer:
            print(answer["chunk"]["content"], end="", flush=True)

Ignore event types and fields you don't recognize. New ones may be added without notice.

4. Retry with exponential backoff

This recipe retries 429 (rate-limited) and 503 (at capacity), honors Retry-After, and caps retries. Errors lists every retryable status. A quota 429 only clears at X-Quota-Reset, so backing off won't help there. Never retry blindly on 500: /agent/ask is not idempotent unless you send an Idempotency-Key.

async function askWithRetry(body: unknown, attempt = 0): Promise<Response> {
  const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": process.env.NEUROAPI_KEY!,
    },
    body: JSON.stringify(body),
  })

  const retryAfter = res.headers.get("retry-after")
  // A quota_exceeded 429 has no Retry-After, so it is not retried.
  const retryable =
    (res.status === 429 && retryAfter !== null) || res.status === 503
  if (retryable && attempt < 3) {
    const hinted = Number(retryAfter ?? "0")
    const backoff = hinted > 0 ? hinted : 2 ** attempt
    await new Promise((r) => setTimeout(r, backoff * 1000))
    return askWithRetry(body, attempt + 1)
  }
  return res
}
import os, time, httpx

def ask_with_retry(body: dict, attempt: int = 0) -> httpx.Response:
    res = httpx.post(
        "https://api.neurobro.ai/api/v1/agent/ask",
        headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
        json=body,
        timeout=300,
    )
    retry_after = res.headers.get("retry-after")
    # A quota_exceeded 429 has no Retry-After, so it is not retried.
    retryable = (res.status_code == 429 and retry_after) or res.status_code == 503
    if retryable and attempt < 3:
        hinted = int(retry_after or 0)
        backoff = hinted if hinted > 0 else 2 ** attempt
        time.sleep(backoff)
        return ask_with_retry(body, attempt + 1)
    return res

If retries are exhausted, surface X-Request-Id to your operators. It's the first thing NeuroAPI support asks for.

5. Picking a mode

Each mode has its own price: fast costs 1 cost_units per call, smart 2, and max 8. The cost_units field on each successful response is what you were charged, and Pricing has the full table. max needs Pro or Enterprise; on the Starter plan it returns 403 mode_not_in_plan.

ModeWhat it's for
fastQuick answers with core market knowledge. Good for asset checks, market sentiment, and high-volume financial Q&A.
smart (default)Deeper reasoning and more market context for complex questions. Good for technical analysis, trade setups, and fundamental stock research.
maxThe deepest research: multi-asset investigations and fundamental analysis with broad market coverage.

When you don't pick, the server defaults to smart. Choose explicitly in production code so behavior doesn't drift if the default ever changes.

6. Steer the agent with a system prompt

Pass system_prompt to shape the agent's tone, role, or output format. It layers on top of the built-in instructions and can't override the agent's persona or safety guardrails.

curl -s https://api.neurobro.ai/api/v1/agent/ask \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $NEUROAPI_KEY" \
  -d '{
    "prompt": "How is the EUR/USD pair looking this week?",
    "mode": "smart",
    "system_prompt": "You are a concise FX strategist. Lead with a one-line bias (long/short/neutral), then three supporting bullets. Flag any figure you are not confident about."
  }' | jq
const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.NEUROAPI_KEY!,
  },
  body: JSON.stringify({
    prompt: "How is the EUR/USD pair looking this week?",
    mode: "smart",
    system_prompt:
      "You are a concise FX strategist. Lead with a one-line bias (long/short/neutral), then three supporting bullets. Flag any figure you are not confident about.",
  }),
})
const { answer } = await res.json()
import os, httpx

res = httpx.post(
    "https://api.neurobro.ai/api/v1/agent/ask",
    headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
    json={
        "prompt": "How is the EUR/USD pair looking this week?",
        "mode": "smart",
        "system_prompt": (
            "You are a concise FX strategist. Lead with a one-line bias "
            "(long/short/neutral), then three supporting bullets. Flag any "
            "figure you are not confident about."
        ),
    },
    timeout=300,
)
answer = res.json()["answer"]

Keep it short and declarative - a sentence or two naming the role and the shape you want. The response is a normal AgentAskResponse; the steered text is in answer.

7. Structured output with a JSON Schema

Pass output_schema - a JSON Schema with an object root - to get an object in that shape back instead of prose. The result lands in output and answer is null (exactly one is ever set), so your code consumes it directly without parsing free text.

Structured output is non-streaming only. The agent fetches live data before it fills your schema, so a call usually takes 10-60 seconds, longer on max. A non-streaming run stops at 5 minutes, so set your client timeout to 300 seconds.

curl -s https://api.neurobro.ai/api/v1/agent/ask \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $NEUROAPI_KEY" \
  -d '{
    "prompt": "Give me a structured read on Bitcoin right now.",
    "mode": "max",
    "output_schema": {
      "type": "object",
      "properties": {
        "stance": { "type": "string", "enum": ["bullish", "bearish", "neutral"] },
        "conviction": { "type": "number", "description": "0-1 confidence" },
        "support": { "type": "number" },
        "resistance": { "type": "number" },
        "summary": { "type": "string" }
      },
      "required": ["stance", "conviction", "support", "resistance", "summary"],
      "additionalProperties": false
    }
  }' | jq .output
type MarketRead = {
  stance: "bullish" | "bearish" | "neutral"
  conviction: number
  support: number
  resistance: number
  summary: string
}

const res = await fetch("https://api.neurobro.ai/api/v1/agent/ask", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.NEUROAPI_KEY!,
  },
  body: JSON.stringify({
    prompt: "Give me a structured read on Bitcoin right now.",
    mode: "max",
    output_schema: {
      type: "object",
      properties: {
        stance: { type: "string", enum: ["bullish", "bearish", "neutral"] },
        conviction: { type: "number", description: "0-1 confidence" },
        support: { type: "number" },
        resistance: { type: "number" },
        summary: { type: "string" },
      },
      required: ["stance", "conviction", "support", "resistance", "summary"],
      additionalProperties: false,
    },
  }),
})

const { output } = (await res.json()) as { output: MarketRead }
console.log(output.stance, output.conviction)
import os, httpx

schema = {
    "type": "object",
    "properties": {
        "stance": {"type": "string", "enum": ["bullish", "bearish", "neutral"]},
        "conviction": {"type": "number", "description": "0-1 confidence"},
        "support": {"type": "number"},
        "resistance": {"type": "number"},
        "summary": {"type": "string"},
    },
    "required": ["stance", "conviction", "support", "resistance", "summary"],
    "additionalProperties": False,
}

res = httpx.post(
    "https://api.neurobro.ai/api/v1/agent/ask",
    headers={"X-API-Key": os.environ["NEUROAPI_KEY"]},
    json={
        "prompt": "Give me a structured read on Bitcoin right now.",
        "mode": "max",
        "output_schema": schema,
    },
    timeout=120,
)
output = res.json()["output"]  # a dict in your schema's shape

The response carries the object on output:

{
  "answer": null,
  "output": {
    "stance": "bullish",
    "conviction": 0.62,
    "support": 58000,
    "resistance": 72000,
    "summary": "Holding above the 50-day average with improving spot demand."
  },
  "mode": "max",
  "request_id": "1c9d44f5-2f0e-4c6b-9b2a-8b3a2f0e1d7e",
  "usage": { "prompt_tokens": 210, "completion_tokens": 24, "cached_tokens": 0, "cost_units": 8 }
}

Two failure modes the API rejects up front, before any quota is spent:

  • output_schema together with "stream": true returns 400 - structured output is non-streaming only.
  • A schema that can't drive structured output - a non-object root, an empty {}, or otherwise malformed - returns 422.

Designing the schema

  • Make every property required and set additionalProperties: false. On max, the model provider enforces a schema in this shape while the answer is written.
  • If the agent may not be able to source a value, allow null rather than making the field optional - {"type": ["number", "null"]} - so it can return null instead of a placeholder like 0.
  • For alternatives, use anyOf inside a property, never at the root. Avoid oneOf, allOf, and not: the provider can't enforce them.
  • Schemas are read as JSON Schema 2020-12, whatever $schema says.
  • References must name a definition in $defs ("$ref": "#/$defs/level"); definitions, recursive and remote references aren't supported. With zod-to-json-schema, set definitionPath: "$defs".
  • pattern and patternProperties aren't supported; describe the format you want in the field's description instead.
  • format (for example "date") and description guide the agent but aren't checked.
  • Limits: 20,000 characters of JSON (a non-ASCII character counts as up to six), 32 levels of nesting and 500 subschemas.

8. A thin TypeScript client

This wrapper handles auth, retry, sync calls, and streaming. Copy it into a single file. It has no dependencies.

neuroapi.ts
type Mode = "fast" | "smart" | "max"
type Turn = { role: "user" | "assistant"; content: string }

export class NeuroAPI {
  constructor(
    private apiKey: string,
    private baseUrl = "https://api.neurobro.ai/api/v1",
  ) {}

  async ask(input: { prompt: string; mode?: Mode; history?: Turn[] }) {
    const res = await this.send({ ...input, stream: false })
    if (!res.ok) throw await this.toError(res)
    return res.json() as Promise<{
      answer: string
      mode: Mode
      request_id: string
      usage: { prompt_tokens: number; completion_tokens: number; cached_tokens: number; cost_units: number }
    }>
  }

  async askStream(
    input: { prompt: string; mode?: Mode; history?: Turn[] },
    onChunk: (text: string) => void,
  ): Promise<{ requestId: string }> {
    const res = await this.send({ ...input, stream: true })
    if (!res.ok) throw await this.toError(res)

    const requestId = res.headers.get("x-request-id") ?? ""
    const reader = res.body!.getReader()
    const decoder = new TextDecoder()
    let buffer = ""

    while (true) {
      const { value, done } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })

      let nl: number
      while ((nl = buffer.indexOf("\n\n")) !== -1) {
        const frame = buffer.slice(0, nl)
        buffer = buffer.slice(nl + 2)
        const payload = frame.startsWith("data: ") ? frame.slice(6) : frame
        if (payload === "[DONE]") return { requestId }
        const event = JSON.parse(payload)
        if (event.type === "error") throw new Error(event.message)
        const text = event.data.answer?.chunk.content
        if (text) onChunk(text)
      }
    }
    return { requestId }
  }

  private async send(input: {
    prompt: string
    mode?: Mode
    history?: Turn[]
    stream: boolean
  }): Promise<Response> {
    const body = {
      prompt: input.prompt,
      mode: input.mode ?? "smart",
      message_history: input.history ?? [],
      stream: input.stream,
    }
    let attempt = 0
    while (true) {
      const res = await fetch(`${this.baseUrl}/agent/ask`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-API-Key": this.apiKey,
        },
        body: JSON.stringify(body),
      })
      const retryAfter = res.headers.get("retry-after")
      // A quota_exceeded 429 has no Retry-After, so it is not retried.
      const retryable =
        (res.status === 429 && retryAfter !== null) || res.status === 503
      if (retryable && attempt < 3) {
        const hinted = Number(retryAfter ?? "0")
        const backoff = hinted > 0 ? hinted : 2 ** attempt
        await new Promise((r) => setTimeout(r, backoff * 1000))
        attempt++
        continue
      }
      return res
    }
  }

  private async toError(res: Response): Promise<Error> {
    const requestId = res.headers.get("x-request-id") ?? "unknown"
    const detail = await res.text()
    return new Error(`NeuroAPI ${res.status} (request_id=${requestId}): ${detail}`)
  }
}

Usage:

const api = new NeuroAPI(process.env.NEUROAPI_KEY!)
const { answer } = await api.ask({
  prompt: "Give a quick read on the current crypto market pulse.",
})

await api.askStream(
  { prompt: "Stream a multi-asset macro brief.", mode: "max" },
  (chunk) => process.stdout.write(chunk),
)

What's next

On this page