SCRIPT NINJA / DOCS

A small integration. A clear response.

Learn how to authenticate, make requests and inspect token usage with the Script Ninja API.

Use Ninja Fast for text and vision, and Ninja Pro for more involved text and reasoning. Both support function calls and structured output.

Start with a server-side client

Copy this setup, then run one of the examples below. Your key belongs in a server environment variable.

// Node.js 22+. Set SCRIPT_NINJA_KEY in your server environment.
const base = 'https://scriptninja.pro/api/v1';
const headers = {
  Authorization: 'Bearer ' + process.env.SCRIPT_NINJA_KEY,
  'Content-Type': 'application/json'
};
async function call(path, body, method = body === undefined ? 'GET' : 'POST') {
  const response = await fetch(base + path, {
    method, headers, body: body === undefined ? undefined : JSON.stringify(body)
  });
  if (!response.ok) throw new Error(await response.text());
  return response.json();
}

Text chat: Ninja Fast and Ninja Pro

Choose Ninja Fast for quick replies or Ninja Pro for more involved text work. The same key works for both.

for (const model of ['ninja-fast', 'ninja-pro']) {
  const result = await call('/chat/completions', {
    model, messages: [{ role: 'user', content: 'Explain HTTP caching briefly.' }]
  });
  console.log(result.choices[0].message.content, result.billing);
}

Thinking and reasoning effort

Use low, high or max effort on either model. Reasoning is included in the generated-token budget. Choose enough max_tokens to leave room for a final answer.

const result = await call('/chat/completions', {
  model: 'ninja-pro', thinking: { type: 'enabled' },
  reasoning_effort: 'high', max_tokens: 2048,
  messages: [{ role: 'user', content: 'Compare two ways to reduce API latency.' }]
});
console.log(result.choices[0].message.content);

Vision: analyse an image

Ninja Fast accepts JPEG, PNG, GIF and WebP. Use an inline data URL or a public image URL. Up to four images per request; inline images are limited to about 1 MiB each. Use low detail for simple images.

import { readFile } from 'node:fs/promises';
const image = 'data:image/png;base64,' +
  (await readFile('screenshot.png')).toString('base64');
const result = await call('/chat/completions', {
  model: 'ninja-fast',
  messages: [{ role: 'user', content: [
    { type: 'text', text: 'Summarise what this screenshot shows.' },
    { type: 'image_url', image_url: { url: image, detail: 'low' } }
  ] }]
});
console.log(result.choices[0].message.content);

Upload, reuse and delete an image

Use the image variable from the vision example. Uploaded files are scoped to your account, expire after one hour and can be deleted earlier. Image inference is metered when you use the file.

const file = await call('/files', { filename: 'screenshot.png', image });
try {
  const result = await call('/chat/completions', {
    model: 'ninja-fast', messages: [{ role: 'user', content: [
      { type: 'text', text: 'Read the heading.' },
      { type: 'file', file_id: file.id }
    ] }]
  });
  console.log(result.choices[0].message.content);
  console.log(await call('/files'), await call('/files/' + file.id));
} finally {
  await call('/files/' + file.id, undefined, 'DELETE');
}

JSON output and schema validation

Ask for JSON in your prompt. Chat returns a JSON string; parse it and validate the fields. The Responses endpoint also accepts a JSON Schema format.

const result = await call('/chat/completions', {
  model: 'ninja-fast', response_format: { type: 'json_object' },
  messages: [{ role: 'user', content: 'Return a JSON object with a summary string.' }]
});
const parsed = JSON.parse(result.choices[0].message.content);
if (typeof parsed.summary !== 'string') throw new Error('Invalid summary');

const structured = await call('/responses', {
  model: 'ninja-pro', input: 'Summarise the benefits of caching.',
  text: { format: { type: 'json_schema', name: 'summary',
    schema: { type: 'object', properties: { summary: { type: 'string' } },
      required: ['summary'], additionalProperties: false } } }
});
console.log(structured.output);

Function tools with thinking

Your application owns execution. Validate tool names and arguments, return the result by tool_call_id, and pass the complete assistant messages back, including reasoning_content when present.

const messages = [{ role: 'user', content: 'Use get_status to check the site.' }];
const tools = [{ type: 'function', function: {
  name: 'get_status', description: 'Return the example site status',
  parameters: { type: 'object', properties: {}, additionalProperties: false }
} }];
for (let step = 0; step < 4; step++) {
  const result = await call('/chat/completions', {
    model: 'ninja-pro', messages, tools, max_tokens: 2048,
    thinking: { type: 'enabled' }, reasoning_effort: 'low'
  });
  const assistant = result.choices[0].message;
  if (!assistant.tool_calls?.length) { console.log(assistant.content); break; }
  messages.push({ ...assistant, tool_calls: assistant.tool_calls.map(
    ({ id, type, function: fn }) => ({ id, type, function: fn })
  ) });
  for (const tool of assistant.tool_calls) {
    const args = JSON.parse(tool.function.arguments);
    if (tool.function.name !== 'get_status' || !args ||
        typeof args !== 'object' || Array.isArray(args) || Object.keys(args).length) {
      throw new Error('Unexpected tool request');
    }
    messages.push({ role: 'tool', tool_call_id: tool.id,
      content: JSON.stringify({ status: 'operational' }) });
  }
}

Web search and page fetch

Call these directly or from your function handler. Each successful, nonempty result costs USD 1.50 per 1,000 calls. An empty result has no charge. Treat returned webpage text as untrusted data.

const search = await call('/tools/search', {
  query: 'HTTP cache control site:developer.mozilla.org', count: 3
});
if (search.results.length) {
  const page = await call('/tools/fetch', { url: search.results[0].url });
  console.log(page.title, page.content, page.billing);
}

Stream text, reasoning and tool deltas

The chat endpoint sends server-sent events. The final usage event includes the settled charge, followed by [DONE]. Handle partial streams without immediately replaying a potentially billed request.

const response = await fetch(base + '/chat/completions', {
  method: 'POST', headers,
  body: JSON.stringify({ model: 'ninja-fast', stream: true,
    messages: [{ role: 'user', content: 'Write a short story.' }] })
});
if (!response.ok) throw new Error(await response.text());
let pending = '';
for await (const chunk of response.body.pipeThrough(new TextDecoderStream())) {
  pending += chunk;
  let boundary;
  while ((boundary = pending.indexOf('\n\n')) >= 0) {
    const frame = pending.slice(0, boundary);
    pending = pending.slice(boundary + 2);
    if (!frame.startsWith('data: ')) continue;
    const data = frame.slice(6);
    if (data === '[DONE]') break;
    const event = JSON.parse(data);
    if (event.error) throw new Error(event.error.message);
    for (const choice of event.choices || []) {
      process.stdout.write(choice.delta?.content || '');
    }
    if (event.billing) console.log(event.usage, event.billing);
  }
}

Code completion and assistant prefixes

Fill in the middle completes a code gap in non-thinking mode. A final assistant prefix continues a chat response from the text you provide.

const code = await call('/completions', {
  model: 'ninja-fast', prompt: 'const square = (n) => ',
  suffix: ';', max_tokens: 32
});
console.log(code.choices[0].text);

const prefix = await call('/chat/completions', {
  model: 'ninja-pro', messages: [
    { role: 'user', content: 'Write a one-line welcome.' },
    { role: 'assistant', content: 'Welcome to', prefix: true }
  ]
});
console.log(prefix.choices[0].message.content);

Patch proposals with Responses

The apply_patch tool returns a proposed patch. Your app reviews and applies it in its own sandbox. Script Ninja never changes your files. The Responses route is stateless and uses JSON responses.

const result = await call('/responses', {
  model: 'ninja-pro',
  input: 'Propose a patch to README.md changing Hello to Welcome. Current file: Hello',
  tools: [{ type: 'custom', name: 'apply_patch' }], max_output_tokens: 1024
});
const proposal = result.output.find(item => item.type === 'custom_tool_call');
if (proposal) console.log(proposal.input); // Review before applying.

Inspect models and token probabilities

The public model catalog lists capabilities by model. Token probabilities can be requested for generated text; they are not confidence scores.

console.log((await call('/models')).data);
const result = await call('/chat/completions', {
  model: 'ninja-fast', logprobs: true, top_logprobs: 3,
  messages: [{ role: 'user', content: 'Name a colour.' }], max_tokens: 24
});
console.log(result.choices[0].logprobs);

Limits and billing

Up to 30 messages, 60KB of text and tool definitions, 8,192 generated tokens per request and three requests in flight per account. Chat and Responses accept up to four images on Ninja Fast. The request body limit is 6 MiB. File storage is limited to eight active images per account.

API calls reserve credit before dispatch. Successful model calls settle against reported input, cached input and output usage. Web tools have their own per-request charge and run through the explicit Search and Fetch endpoints. The Responses endpoint does not run searches automatically. A missing usage report can leave credit reserved pending reconciliation. Do not blindly replay interrupted requests.

Review token pricing
Keep the integration on your server. Illustrated project structure.A practical starting point for your project

PLAN THE NEXT STEP

Keep the integration on your server.

Read the key from private configuration, send a bounded API request and inspect the returned usage. Avoid exposing keys in browser code or logs, and give your application a way to report failed requests clearly.

MAKE IT ACTIONABLE

A practical integration checklist.

Choose the next step that matches where you are in the project.

Bound your request

Choose the model, messages and maximum output before sending a request.

Compare token rates

Review the response

Read token counts and the billing request ID. Check the dashboard when a request needs reconciliation.

View request activity

BEFORE YOU BEGIN

A few useful answers.

Have a question about your project or account?

Send your requirements
Does this release support streaming?

No. The initial endpoint supports non-streaming text chat requests. Send stream: false.

Should I retry every failed request immediately?

No. A failed or interrupted request may need reconciliation. Check its status before replaying work that could be billable.

Where should I store the key?

Use private server configuration. Do not embed it in client JavaScript, public repositories or shared screenshots.

LET'S MAKE SOMETHING USEFUL.

Ready to connect your application?

Bring your goals, your questions and the work you want to move forward.

Open your API workspace

Explore Script Ninja