Instructions for AI Assistants

Rules for generating correct and functional NeuralAI API integration code

How to generate correct API code

An AI assistant can generate working NeuralAI API integrations by following these rules:

Always use api_key in the header or JSON body — never hardcoded in public sources. The unified endpoint is https://app.neuralaiweb.com/functions/neuralaiPublicApi.

The body is JSON: { "api_key": "nai_...", "prompt": "..." }. For structured output, add response_json_schema (object, not array).

One single endpoint for everything: the orchestrator detects intent (chat, image, video, music, seek, code) automatically. No different URLs per service.

Dynamic behavior (dynamic_mode): add "dynamic_mode": true to the body to enable real-time adaptation to user mood, technical level and format (+5 tokens, charged only on successful responses). To keep it permanently on, include the parameter in every request; to disable it permanently, omit it or set false. The detected profile comes back in result.dynamic ("AI Mind" panel). Details and code in the Dynamic Behavior section (/api-docs/dynamic-mode).

Verify the key scopes (chat, image, video, music, search, upload, server_virtual). Without the required scope, the API returns 403.

Generate complete copy-paste code: curl, fetch (JS), requests (Python). Include error handling (try/catch, status != 200) and timeout.

For file upload use multipart/form_data with "file" field. For RAG on documents, first UploadFile then pass file_url in the prompt.

Always set a timeout on requests (60s for chat, 120s for media generation, 300s for video). Without a timeout the request hangs indefinitely. Handle HTTP 504 with retry and exponential backoff.

To maintain conversation context use session_id (automatic, server-side) or conversation_history (manual, localStorage). With memory present, concatenation is ALWAYS active: the prompt includes condensed summary, topic register and the last 3 messages, with a flat +1 token surcharge per request. See the Conversation Memory section for details and code.

To export professional PDF documents (A4 with cover, tables, code, sources and page numbering) use generate_pdf: true with the markdown in the prompt field. Optional parameters: pdf_title, pdf_subtitle, pdf_language, pdf_sources, pdf_format ("document" A4 or "presentation" 16:9 slides) and pdf_brand (name on cover, author and footer; default: the one set on the API key, otherwise NeuralAI). The response includes result.pdf_url and result.pdf_pages. Cost: 5 tokens per A4 document (they cover the storage credits of the generated file), 90 per every 10 pages for the presentation.

For images, pass image_quality in the JSON body: "512" (~0.25 MP, 40 tokens), "1K" (~1 MP, 60 tokens, default) or "2K" (~4 MP, 90 tokens). If omitted, quality is auto-detected from the prompt (e.g. "high quality" → 2K, "thumbnail" → 512). For videos, pass resolution: "720p" (default) or "1080p" (+50% tokens).

For videos, handle the timeout with RESUME: if the response contains error_code "video_generation_timeout" and video_operation_name, resend the same request adding the video_operation_name parameter — the API resumes polling the same video generation operation, without starting a new paid generation: the tokens have already been charged upfront and the RESUME is included in the price — developers who don't implement the retry loop lose the tokens already paid. ALWAYS include this retry (2-3 attempts) in video integration code.

For PDFs (generate_pdf: true) handle pending automatically: if the response contains result.pdf_pending: true and result.pdf_job_id, the PDF is still generating — repeat the same request adding the poll_pdf_job_id parameter until result.pdf_url arrives (recommended loop: 12 attempts, ~10s interval). Polling is free: the presentation surcharge is charged only on delivery. Without the loop the PDF is never delivered.

Automatically generated PDF presentations (chat, seek_normal, seek_large, deep_research with presentation intent) follow the same pending pattern: if the response contains result.pdf_pending: true + result.pdf_job_id, repeat the same request with poll_pdf_job_id until result.pdf_url arrives — free polling, the surcharge is paid only on delivery.

For video analysis (Video RAG, video_url/video_file_url parameters) handle the RESUME: if the response contains error_code "video_processing_timeout" with video_file_name, resend the same request adding the video_file_name parameter — the API resumes processing the same file already uploaded to Google, with no re-download or re-upload: the 20 base tokens have already been charged upfront and the resume is included in the price (refunded only on real errors). ALWAYS include this retry (2-3 attempts) in video analysis code you generate.

Video Continuation: after a successful video generation, ALWAYS show a button under every video that calls POST https://app.neuralaiweb.com/functions/neuralaiVideoContinue with { api_key, video_id: result.video_id, prompt, duration_seconds } — the scene continues natively from the last frame. If the response is { status: 'pending', operation_name }, repeat the request with operation_name every 10s for up to 9.5 minutes (free polling); 200 tokens charged only on delivery; chain max 40s (chain_limit_reached error). For the frontend use the official widget <script src="https://app.neuralaiweb.com/neuralai-continue.js"> with data-neuralai-video on the video element: it handles button, pending and new-clip insertion by itself.

Agent AI: to delegate recurring tasks to a preconfigured agent (reports, quotes, analysis) use the dedicated agentApi endpoint with an agents-scope key. You need the agent_id: get it from list_agents or the Copy button on the agent card. Full guide: /api-docs/agent-api.

To export a presentation to Google Slides or PowerPoint from your app, do NOT use NeuralAI's export endpoint (it requires a NeuralAI session): use result.deck (the structured JSON returned by the API) and the Google Slides API with your app's OAuth (presentations scope) or your platform's Google Slides connector. The end user does not need to log into NeuralAI.

Example — Chat with structured response

curl

curl -X POST https://app.neuralaiweb.com/functions/neuralaiPublicApi \
-H "Content-Type: application/json" \
-d '{
"api_key": "nai_xxx",
"prompt": "Riassumi i punti chiave di questo testo",
"response_json_schema": {
"type": "object",
"properties": {
"summary": { "type": "string" },
"points": { "type": "array", "items": { "type": "string" } }
}
}
}'

Python (requests)

import requests
 
resp = requests.post(
"https://app.neuralaiweb.com/functions/neuralaiPublicApi",
json={
"api_key": "nai_xxx",
"prompt": "Riassumi i punti chiave",
"response_json_schema": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"points": {"type": "array", "items": {"type": "string"}}
}
}
},
timeout=60
)
if resp.ok:
data = resp.json()
print(data.get("result", data))
else:
print("Errore", resp.status_code, resp.text)

Agent AI — ready-made instructions for AI code chats

If you use an AI code assistant (AI chat in your editor or IDE), paste this block into the conversation context: it contains the endpoint, operations, billing rules and a ready example — the assistant will immediately generate correct integration code for the agents.

Instruction to paste into the AI code chat

TASK: integrate Neuralai Agent AI via API.
 
ENDPOINT: POST https://app.neuralaiweb.com/functions/agentApi
AUTH: header "x-api-key: nai_..." (key with "agents" scope)
or body field api_key. Body is JSON: { "operation": "...", ... }
 
OPERATIONS:
list_agents -> my agents, each with "id"
get_agent { agent_id } -> full agent detail
create_agent { name, role, synthesis, general_prompt, ... }
update_agent { agent_id, ...fields }
delete_agent { agent_id }
execute { agent_id, input, mode: "task"|"playground", session_id? }
list_tasks { agent_id?, limit? } -> execution history
get_task { task_id } -> full result
get_cad_job { job_id } -> 3D model job status + file URLs
get_calc_job { job_id } -> calculation job status + report/files
 
RULES:
- 3D CAD agents: create an agent whose general_prompt instructs it to end
the technical sheet with the [[GENERACAD:Title]] marker and set
allowed_tools: ["cad"] (or [] = all tools). On execute, when the marker is
emitted the response includes deliverable { type: "cad", job_id }:
poll get_cad_job every 5-10s (2-5 min for simple models, up to 14 min for complex ones) until status "succeeded" —
result.files contains publicly downloadable URLs (STL, STEP, DWG/DXF,
GLB). 40 tokens charged at submission, refunded if generation fails.
- Calculation agents: create an agent whose general_prompt instructs it to
end the response with the [[GENERACALC:Title]] marker and set
allowed_tools: ["calcolo"] (or [] = all tools). On execute, when the marker
is emitted the response includes deliverable { type: "calc", job_id }:
poll get_calc_job every 5-10s (2-4 min) until status "succeeded" —
result contains report (markdown), results and downloadable files (plots,
calcolo.py, relazione.md). Optional "lang" field on execute (e.g. "it",
"en") sets the report language. 30 tokens charged at submission, refunded
if the calculation fails.
- Get the real agent_id from list_agents (or the Copy button on the
agent card in the Neuralai app, /agent-ai). Never invent an agent_id.
- mode "task": one-shot run, result saved in history
(data.response, data.task_id).
- mode "playground": conversational; reuse data.session_id to continue.
- Cost: 15 tokens per run (+30 if knowledge context > 40k chars,
+5 with dynamic mode). Atomic charge, automatic refund on failure.
- Always set a request timeout (120s); retry HTTP 504 with backoff.
- Store the API key server-side only (env var), never in client code.
 
VIDEO CONTINUATION (native):
After a successful video generation, ALWAYS render a "Continue" button
under every video. It calls:
POST https://app.neuralaiweb.com/functions/neuralaiVideoContinue
body: { api_key, video_id: result.video_id, prompt, duration_seconds: 4|6|8|10 }
- Response success: { video_url, video_id, google_video_uri, chain_seconds }
— pass video_id again as video_id to chain the next continuation.
- Response { status: "pending", operation_name } → resend the request with
operation_name every 10s, up to 9.5 minutes (free polling).
- 200 tokens charged only on delivery; chain max 40 seconds total
(error chain_limit_reached). Frontend shortcut: the official widget
<script src="https://app.neuralaiweb.com/neuralai-continue.js"> with
data-neuralai-video="<video_id>" on the video container.
 
EXAMPLE (JavaScript):
const res = await fetch("https://app.neuralaiweb.com/functions/agentApi", {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": API_KEY },
body: JSON.stringify({ operation: "execute", agent_id: AGENT_ID,
input: "Prepara il report di oggi", mode: "task" })
});
const data = await res.json();
if (data.success) console.log(data.response);

Conversation Memory & Concatenation

How to maintain context between API requests with the NeuralAI orchestrator

How concatenation works

The NeuralAI API maintains context between requests with server-side per-session memory. On every response the session automatically updates a condensed summary (2-3 sentences) and a register of covered topics; together with the last 3 messages, this information is injected into the prompt of subsequent requests. Concatenation is automatic whenever memory exists (session_id or conversation_history): no configuration required.

1. Detection

The API detects whether memory exists: active session_id or non-empty conversation_history

2. Memory

Condensed summary, topic register and last 3 messages are injected into the prompt

3. Response

Gemini generates the response with full conversation context

Mode 1: session_id (Automatic)

Add the session_id parameter to the payload. The API automatically saves and retrieves history from the database. Zero client-side management.

JavaScript (fetch)

const res = await fetch(
"https://app.neuralaiweb.com/functions/neuralaiPublicApi",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: "nai_xxx",
prompt: "E quella precedente?",
session_id: "my-unique-session-123"
})
}
);
const data = await res.json();

Mode 2: conversation_history (Manual)

Send the array of previous messages directly in the payload. Ideal for apps that already manage history in localStorage.

JavaScript (localStorage)

// Salva cronologia in localStorage
const hist = JSON.parse(
localStorage.getItem("chat_hist") || "[]"
);
 
const res = await fetch(
"https://app.neuralaiweb.com/functions/neuralaiPublicApi",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: "nai_xxx",
prompt: userMessage,
conversation_history: hist
})
}
);
const data = await res.json();
 
// Aggiorna cronologia
hist.push({ role: "user", content: userMessage });
hist.push({
role: "assistant",
content: data.result?.response || ""
});
localStorage.setItem(
"chat_hist", JSON.stringify(hist.slice(-10))
);

Session reset (reset: true) and automatic TTL

Send reset: true together with session_id to completely clear the memory: the session is deleted from the database, the received history is ignored, and the response contains a fresh session_id in the session_id field. Sessions inactive for more than 30 days are automatically deleted anyway.

JavaScript (reset)

const res = await fetch(
"https://app.neuralaiweb.com/functions/neuralaiPublicApi",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: "nai_xxx",
prompt: "Nuova conversazione, partiamo da zero",
session_id: oldSessionId,
reset: true // Azzera la sessione DB + history ricevuta
})
}
);
const data = await res.json();
const newSessionId = data.session_id; // Nuova sessione pulita

Conversation context cost

Every request with active context (session memory or non-empty conversation_history) applies a flat +1 token surcharge, added to the base cost of the operation. The surcharge is recorded in the usage logs (metadata.context_surcharge).

+1 🪙

per request with active memory

0 🪙

first request of the session (no memory)

Cost optimization

  • ✓The +1 token applies ONLY when memory exists: the first request of a session costs the same as a single call.
  • ✓Only the last 3 messages are sent to the LLM (not the entire history), reducing input tokens.
  • ✓The condensed summary and topic register provide continuity beyond the sliding window, without growing the context indefinitely.
  • ✓The session_id mode saves up to 20 messages in the DB (rolling window), with automatic cleanup of the oldest.

Complete example: Chat with session_id (Python)

Python (requests)

import requests
import uuid
 
API_URL = "https://app.neuralaiweb.com/functions/neuralaiPublicApi"
API_KEY = "nai_xxx"
SESSION_ID = str(uuid.uuid4()) # Unico per conversazione
 
def send_message(prompt: str) -> str:
resp = requests.post(API_URL, json={
"api_key": API_KEY,
"prompt": prompt,
"session_id": SESSION_ID # L'API gestisce la cronologia
}, timeout=60)
 
data = resp.json()
if data.get("status") == "success":
return data["result"].get("response", "")
else:
return f"Error: {data.get('error', 'unknown')}"
 
# Conversazione multi-turno — il contesto e automatico
print(send_message("Ciao, mi chiamo Marco"))
print(send_message("Come mi chiamo?")) # L'API ricorda "Marco"
print(send_message("Qual e il mio nome completo?"))

How to activate concatenation

Concatenation is automatically active when the orchestrator is active (force_intent empty or not specified). No additional configuration needed: just send session_id or conversation_history and the API does the rest.

force_intent = "" → Orchestrator active → Automatic concatenation

Layout Modes: Seek vs Chat

How to organize API results in two different visual modes

Seek Mode

The result is single: each new search replaces the previous one. Ideal for web searches, media generation, and one-shot queries.

  • ✓ One result at a time
  • ✓ Clean and focused layout
  • ✓ Input always at top
  • Chat Mode

    Results accumulate as chat messages. Each prompt + response forms a message pair. After the first search, the input field moves below the results.

  • ✓ Visual history as chat
  • ✓ Input below results after first search
  • ✓ Use session_id for automatic context
  • Implementation

    The implementation requires a mode selector and two conditional layouts. In chat mode, messages are accumulated in an array and the input moves below after the first message.

    JavaScript (React + NeuralAI API)

    import { useState, useRef, useEffect } from "react";
     
    const API_URL = "https://app.neuralaiweb.com/functions/neuralaiPublicApi";
    const API_KEY = "nai_xxx";
     
    export default function NeuralAIChat() {
    const [viewMode, setViewMode] = useState("seek"); // "seek" | "chat"
    const [prompt, setPrompt] = useState("");
    const [result, setResult] = useState(null);
    const [chatMessages, setChatMessages] = useState([]);
    const [loading, setLoading] = useState(false);
    const chatRef = useRef(null);
    const sessionId = useRef(crypto.randomUUID());
     
    // Auto-scroll in chat mode
    useEffect(() => {
    if (viewMode === "chat" && chatMessages.length > 0) {
    chatRef.current?.scrollTo({
    top: chatRef.current.scrollHeight,
    behavior: "smooth"
    });
    }
    }, [chatMessages, viewMode]);
     
    const handleRun = async () => {
    if (!prompt.trim()) return;
    setLoading(true);
    try {
    const res = await fetch(API_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
    api_key: API_KEY,
    prompt: prompt.trim(),
    session_id: sessionId.current
    })
    });
    const data = await res.json();
     
    if (viewMode === "chat") {
    // Accumulate as chat messages
    setChatMessages(prev => [...prev, {
    prompt: prompt.trim(),
    result: data
    }]);
    } else {
    // Replace single result
    setResult(data);
    }
    setPrompt("");
    } catch (err) {
    console.error(err);
    } finally {
    setLoading(false);
    }
    };
     
    const handleNewSearch = () => {
    setResult(null);
    setChatMessages([]);
    setPrompt("");
    sessionId.current = crypto.randomUUID();
    };
     
    return (
    <div className="space-y-4">
    {/* Mode selector */}
    <div className="flex gap-2">
    <button onClick={() => setViewMode("seek")}
    className={viewMode === "seek" ? "active" : ""}>
    Seek
    </button>
    <button onClick={() => setViewMode("chat")}
    className={viewMode === "chat" ? "active" : ""}>
    Chat
    </button>
    </div>
     
    {/* Chat messages (chat mode, after first message) */}
    {viewMode === "chat" && chatMessages.length > 0 && (
    <div ref={chatRef} className="space-y-6">
    {chatMessages.map((msg, i) => (
    <div key={i} className="space-y-2">
    {/* User bubble */}
    <div className="flex justify-end">
    <div className="bg-violet-100 px-4 py-2 rounded-2xl">
    {msg.prompt}
    </div>
    </div>
    {/* AI response */}
    <div className="flex gap-2">
    <div className="flex-1">
    {/* Render result here */}
    <pre>{JSON.stringify(msg.result, null, 2)}</pre>
    </div>
    </div>
    </div>
    ))}
    </div>
    )}
     
    {/* Input (always at top in seek, below in chat) */}
    <div className="space-y-2">
    <textarea
    value={prompt}
    onChange={e => setPrompt(e.target.value)}
    placeholder="Write your prompt..."
    rows={4}
    />
    <button onClick={handleRun} disabled={loading}>
    {loading ? "Processing..." : "Send"}
    </button>
    <button onClick={handleNewSearch}>New Search</button>
    </div>
     
    {/* Result (seek mode only) */}
    {viewMode === "seek" && result && (
    <div>
    <pre>{JSON.stringify(result, null, 2)}</pre>
    </div>
    )}
    </div>
    );
    }

    Mobile Optimization

    • ✓Use max-w-[85%] on user bubbles to prevent horizontal overflow
    • ✓Add overflow-hidden and min-w-0 on message containers
    • ✓The Mode selector should be compact (two buttons) to not take up too much space
    • ✓Auto-scroll to bottom of chat after each new message (scrollIntoView or scrollTop)

    🧠 Dynamic Behavior

    The chat adapts in real time to the user's profile: mood, technical level and preferred format.

    With dynamic_mode active, on every message the orchestrator runs a mini-analysis of the input and updates three context variables (mood, technical level, preferred format). The model reads the profile before generating the response and adapts tone, structure and language: empathic validation if the user is frustrated, essential bullet lists if in a hurry, simple analogies if a beginner, technical jargon if an expert. The detected profile comes back in result.dynamic, so you can build a visible "AI Mind" panel for your users.

    user_mood

    calmo · frustrato · entusiasta · di_fretta

    Mood detected from the text: frustrated → empathic opener and calm tone; in a hurry → no pleasantries, bullet lists only.

    technical_level

    principiante · intermedio · esperto

    Technical level based on the terms used: beginner → simple analogies and metaphors; expert → advanced jargon, straight to the point.

    response_format

    sintetico · dettagliato · elenco_puntato · metaforico

    Preferred response format: sintetico → 2-3 sentences; elenco_puntato → scannable lists; metaforico → explanations with analogies.

    How to enable or disable it — toggle in your code

    • JSON body parameter: dynamic_mode (boolean, default false — disabled).

    • dynamic_mode: true — enabled for the request. To keep it PERMANENTLY ON, include the parameter in every request of your app (or in your wrapper function, as in the example below).

    • dynamic_mode: false — PERMANENTLY OFF: omit the parameter entirely or set it to false. You decide the default behavior of your integration.

    • User toggle (example): read the end user's preference (e.g. localStorage or a setting in your app) and pass the value to the parameter, so the end user chooses.

    JavaScript — funzione wrapper con toggle

    // Wrapper: DYNAMIC_DEFAULT = true → attivo permanente; false → disattivo permanente
    const DYNAMIC_DEFAULT = true;
     
    async function askAI(prompt, { dynamic = DYNAMIC_DEFAULT } = {}) {
    const res = await fetch("https://app.neuralaiweb.com/functions/neuralaiPublicApi", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
    api_key: API_KEY,
    prompt: prompt,
    session_id: sessionId, // memoria conversazionale (opzionale)
    dynamic_mode: dynamic // toggle: true | false (default false)
    })
    });
    const data = await res.json();
    return data.result; // result.dynamic = profilo rilevato ("AI Mind")
    }
     
    // Toggle dell'utente finale nel tuo UI:
    // <Switch checked={userPref} onChange={(v) => askAI(p, { dynamic: v })} />

    curl

    curl -X POST https://app.neuralaiweb.com/functions/neuralaiPublicApi \
    -H "Content-Type: application/json" \
    -d '{
    "api_key": "nai_xxx",
    "prompt": "Come funziona il machine learning?",
    "dynamic_mode": true,
    "session_id": "opzionale"
    }'

    Response — result.dynamic

    {
    "status": "success",
    "result": {
    "response": "Il machine learning è ...",
    "dynamic": {
    "user_mood": "calmo",
    "technical_level": "principiante",
    "response_format": "dettagliato"
    },
    "dynamic_tokens": 5
    }
    }

    Token cost

    +5 tokens per request with dynamic_mode: true (on top of the intent's base cost). The charge applies only if the response is generated successfully: if the call fails you don't pay for the analysis. Available in textual responses of the unified endpoint (chat and web search) and in the Playground («Dynamic behavior» toggle). Agent AI agents have their own dedicated dynamic_mode, enabled from the agent's card (see Agent AI API).

    Where it works

    • Playground (API Hub): «Dynamic behavior» +5 toggle next to the Intent selector.
    • Unified endpoint neuralaiPublicApi (from external apps, with an API key).
    • Agent AI: each agent has its own dynamic_mode (toggle on its card), including agents run via Agent API.

    Related references

    • • Token Costs (/api-docs/token-pricing)
    • • Conversation Memory (/api-docs/ai-instructions)
    • • Agent AI API (/api-docs/agent-api)

    Related references

    • • Response schema — JSON structure of responses (/api-docs/schema)
    • • Orchestrator — automatic intent detection (/api-docs/orchestrator)
    • • Direct Calls — specific endpoints per service (/api-docs/direct-calls)
    • • API Key Security — scopes and authorized domains (/api-docs/security)
    • • Virtual Servers — Python app development in (/cloud-architecture/neuralai-os-apps)
    • • Agent AI API — dedicated endpoint: create, run and manage your agents (/api-docs/agent-api)