开始吧

API 快速入门

开始使用 Ninja 的 API,为您的 AI 产品提供无与伦比的速度、可扩展性和可靠性。

了解更多

注册

在以下网址注册 super.myninja.ai 开始使用我们的 API。

您可以免费注册或订阅 Ultra 或 Business 套餐。Ultra 和 Business 允许您无限制地进入游乐场,尝试我们的旗舰产品、推理和深度研究 LLM*

当你准备好从探索转向执行时,购买积分即可开始构建 AI 产品和体验,用于编程、写作等。

* 受滥用阈值限制

购买积分

  • 注册后 super.myninja.ai,转到左侧面板并单击 API 图标

    Image of user navigating to the api management page
  • 然后去 “订阅和积分”

    Image of user navigating to the API keys & credits page
  • 在下面 “你的积分,” 点击 “购买积分”

    Image of the API credits section in Ninja AI
  • “自动付款金额” 字段中,输入您想购买的积分金额 (最低 30 美元)

    Image of a user setting their credit amount for their auto-pay agreement in Ninja AI
  • “自动付款门槛” 字段,设置阈值金额,当您的余额降至该金额以下时,我们将重新充值 “自动付款金额”。这样可以确保你不会用完积分或你的API密钥停止工作 (最低 25 美元)

    Image of a user setting their threshold amount for their auto-pay agreement in Ninja AI
  • 选择您的首选付款方式,然后单击 “确认并付款。” 然后,您将被重定向到 Stripe 账单屏幕以完成付款。

    Image of different payment vendors provided to users when purchasing API credits

生成 API 密钥

  • 购买积分后,前往 “管理您的 API 密钥” 的部分 API 密钥和积分页面

    Image of user navigating to the API keys & credits page
  • 点击 “创建新密钥” 按钮。

    Image of manage your API keys section in Ninja AI
  • “姓名” 字段中,输入密钥的名称(例如 生产密钥) 然后单击 “创建密钥”

    Image of naming process for an API key generated by Ninja AI
  • 生成密钥后, 复制它 并将其保存在安全的地方,因为任何有访问权限的人都可以使用它。如果需要,你可以 再生 一把新钥匙。

    Image of an API key generated with Ninja AI

使用 Ninja API

概览

基本网址:
https://api.myninja.ai/v1

身份验证:
所有请求都需要在标头中传递 API 密钥,如下所示<token-key>您的身份验证令牌在哪里:
授权:持有人 <token-key>

终端节点:
帖子 /chat/补全
此端点接受聊天请求并根据指定模型流式传输响应。

型号:
目前可用的型号包括:
忍者深度研究
忍者超级特工:涡轮增压
忍者超级特工:apex
忍者超级特工:推理

可以通过提供以下选项来选择这些模型 模型 请求正文中的参数。

请求格式

Ninja API 遵循 OpenAI API 规范 密切地。请求 JSON 对象包含:

型号(字符串):
要使用的模型标识符(例如 “忍者深度研究”)。

消息(数组):
消息对象数组。每个对象都遵循以下格式:

JSON

{ "role": "user", "content": "Your query here." }
  

流(布尔值):
当设置为 真的,API 使用流式响应进行响应。

stream_options(对象):
其他直播选项,例如 “包含_用法”:正确 包括代币使用详情。

extra_headers(对象):
Ninja API 要求的任何额外标头(目前没有)

请求示例 (json)

JSON

{
  "model": "ninja-super-agent:turbo",
  "messages": [
    {
      "role": "user",
      "content": "What is the significance of birefringence in materials science? Can you provide a detailed explanation including its applications and how it is measured?"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}
  

回应

API 返回的是一条流 ChatCompletionChunk 对象。每个区块可能包含:

内容:
完成文本,可能包括 XML 封装的推理步骤。

引文:
支持所提供理由的网址列表。

使用信息:
令牌使用情况统计信息 if “包含_用法”:正确 已指定。

客户端代码可以处理这些区块以显示丰富的响应,其中包括:

推理步骤: 从 XML 段中提取和格式化。

引文: 显示为编号列表。

使用情况统计: 显示输入和输出标记。

示例代码示例

Python

import time
import xml.etree.ElementTree as ET
from uuid import uuid4
from openai import OpenAI, Stream
from openai.types import CompletionUsage
from openai.types.chat import ChatCompletionChunk

# Initialize the OpenAI client with your API key and base URL.
client = OpenAI(api_key="PUT_YOUR_API_KEY_HERE", base_url="https://api.myninja.ai/v1")

def print_reasoning_step(reasoning_step: str):
    step = ET.fromstring(reasoning_step)
    print(f"[{step.find('header').text}]\n{step.find('content').text}\n")

def print_citations(citations: list[str]):
    width = len(str(len(citations)))
    print("[Citations]")
    for n, citation in enumerate(citations, 1):
        print(f"{n:{width}}. {citation}")
    print()

def print_content(content: str):
    print(content, end="", flush=True)

def print_usage(usage: CompletionUsage):
    print(
        f"\n\n| Input tokens: {usage.prompt_tokens:,} "
        f"| Output tokens: {usage.completion_tokens:,} ",
        end="",
        flush=True,
    )

def main():
    query = (
        "I am an advanced snowboarder and want a good all-mountain snowboard and new boots and "
        "I'd like to spend no more than $1000 all in. Also look at trends and reviews and give "
        "me options that are currently trendy and cool and have high reviews."
    )

    start_time = time.time()
    
    response: Stream[ChatCompletionChunk] = client.chat.completions.create(
        model="ninja-deep-research",
        messages=[
            {"role": "user", "content": query},
        ],
        stream=True,
        stream_options={
            "include_usage": True,
        },
    )

    for chunk in response:
        for choice in chunk.choices:
            if content := choice.delta.content:
                if content.startswith("<step>"):
                    print_reasoning_step(content)
                else:
                    print_content(content)

        if citations := chunk.model_extra.get("citations"):
            print_citations(citations)
        elif usage := chunk.usage:
            print_usage(usage)

    elapsed_time = time.time() - start_time
    print(f"| Elapsed: {elapsed_time:.1f} seconds |")

if __name__ == "__main__":
    main()
  
cURL

curl -N https://api.myninja.ai/v1/chat/completions \
  -H "Authorization: Bearer PUT_YOUR_API_KEY_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ninja-super-agent:turbo",
    "messages": [
      {
        "role": "user",
        "content": "What is the significance of birefringence in materials science? Can you provide a detailed explanation including its applications and how it is measured?"
      }
    ],
    "stream": true,
    "stream_options": {
      "include_usage": true
    }
  }'
Java

HttpResponse<String> response = Unirest.post("https://api.myninja.ai/v1/chat/completions")
  .header("Authorization", "Bearer PUT_YOUR_API_KEY_HERE")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
  
JavaScript

const options = {
  method: 'POST',
  headers: {
    Authorization: 'Bearer PUT_YOUR_API_KEY_HERE',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    model: "ninja-super-agent:turbo",
    messages: [
      {
        role: "user",
        content: "What is the significance of birefringence in materials science? Can you provide a detailed explanation including its applications and how it is measured?"
      }
    ],
    stream: true,
    stream_options: {
      include_usage: true
    }
  })
};

fetch('https://api.myninja.ai/v1/chat/completions', options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));
  
Go

package main

import (
  "bufio"
  "bytes"
  "fmt"
  "io"
  "log"
  "net/http"
)

func main() {
  url := "https://api.myninja.ai/v1/chat/completions"

  jsonStr := ` + "`" + `{
    "model": "ninja-super-agent:turbo",
    "messages": [
      {
        "role": "user",
        "content": "What is the significance of birefringence in materials science? Can you provide a detailed explanation including its applications and how it is measured?"
      }
    ],
    "stream": true,
    "stream_options": {
      "include_usage": true
    }
  }` + "`" + `

  req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonStr)))
  if err != nil {
    log.Fatalf("Error creating request: %v", err)
  }

  req.Header.Set("Authorization", "Bearer PUT_YOUR_API_KEY_HERE")
  req.Header.Set("Content-Type", "application/json")

  client := &http.Client{}
  resp, err := client.Do(req)
  if err != nil {
    log.Fatalf("Error sending request: %v", err)
  }
  defer resp.Body.Close()

  if resp.StatusCode != http.StatusOK {
    log.Fatalf("Request failed with status: %s", resp.Status)
  }

  reader := bufio.NewReader(resp.Body)
  for {
    line, err := reader.ReadBytes('\n')
    if err != nil {
      if err == io.EOF {
        break
      }
      log.Fatalf("Error reading response: %v", err)
    }
    fmt.Print(string(line))
  }
}
  
C#

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace NinjaApiExample
{
  class Program
  {
    static async Task Main(string[] args)
    {
      var url = "https://api.myninja.ai/v1/chat/completions";
      var apiKey = "PUT_YOUR_API_KEY_HERE";

      using var client = new HttpClient();
      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      var payload = new
      {
        model = "ninja-super-agent:turbo",
        messages = new[]
        {
          new { role = "user", content = "What is the significance of birefringence in materials science? Can you provide a detailed explanation including its applications and how it is measured?" }
        },
        stream = true,
        stream_options = new { include_usage = true }
      };

      var jsonPayload = JsonSerializer.Serialize(payload);
      var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

      try
      {
        var response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
      }
      catch (HttpRequestException e)
      {
        Console.WriteLine("Request error: " + e.Message);
      }
    }
  }
}
  

定价

模式

输入价格/ 每 M 个代币

产出价格/ 每 M 个代币

价格/ 任务

Qwen 3 Coder 480B (Cerebras)

Ninja Cline AI Studio 的默认设置

1.50 美元

标准模式

质量和速度的平衡
默认:
GLM 4.6
深度编码器:
GLM 4.6

1.00 美元

复杂模式

适用于复杂任务的最高质量的 LLM
默认:
十四行诗 4.5
深度编码器
十四行诗 4.5

1.50 美元

快速模式

世界上最快的总代理
默认:
GLM 4.6*
深度研究:
Qwen Model Logo
Qwen3—235B*
深度编码器:
GLM 4.6
*由 Cerebras 提供支持
Cerebras logo

1.50 美元

模式

输入价格/ 每 M 个代币

产出价格/ 每 M 个代币

价格/ 任务

Qwen 3 Coder 480B (Cerebras)

Ninja Cline AI Studio 的默认设置

3.75 美元

3.75 美元

标准模式

质量和速度的平衡
默认:
GLM 4.6
深度编码器:
GLM 4.6

1.50 美元

1.50 美元

复杂模式

适用于复杂任务的最高质量的 LLM
默认:
十四行诗 4.5
深度编码器
十四行诗 4.5

4.50 美元

22.50 美元

快速模式

世界上最快的总代理
默认:
GLM 4.6*
深度研究:
Qwen Model Logo
Qwen3—235B*
深度编码器:
GLM 4.6
*由 Cerebras 提供支持
Cerebras logo

3.75 美元

3.75 美元

模型

输入价格/ 每 M 个代币

产出价格/ 每 M 个代币

涡轮 1.0

0.11 美元

0.42 美元

Apex 1.0

0.88 美元

7.00 美元

推理 2.0

0.38 美元

1.53 美元

深度研究 2.0

1.40 美元

5.60 美元

速率限制

Ninja AI 对每个模型的推理请求实施速率限制,以确保开发人员能够尝试最快的推理。

模型

每分钟请求次数 (转速)

涡轮 1.0

50

Apex 1.0

20

推理 2.0

30

深度研究 2.0

5

经常问的问题

根据我们最常被问到的问题,您需要了解以下有关Ninja的API的信息。

如何提高我的自动付款门槛和金额?

  • 在 Ninja 中,转到左侧面板并单击 API 管理图标

  • 在下面 “你的积分,” 点击 “管理积分”

  • “自动付款金额” 字段中,输入您想要增加的积分金额 (最低 30 美元)

  • “自动付款门槛” 字段,编辑阈值金额,当您的余额降至该金额以下时,我们将重新充值 “自动付款金额”。这样可以确保您的积分不会耗尽或您的API密钥停止使用(最低25美元)。

  • 点击 “保存更改” 进行确认。

如何取消我的自动付款协议?

  • 在 Ninja 中,转到左侧面板并单击 API 管理图标

  • 选择 “API 密钥和积分” 然后去 “你的积分” 部分。

  • 在下面 “你的积分,” 点击 “更多选项”

  • 选择 “取消自动支付积分”(最低 30 美元)

  • 点击 “删除自动付款” 进行确认。

如何删除 API 密钥?

  • 在 Ninja 中,转到左侧面板并单击 API 管理图标

  • 选择 “API 密钥和积分,” 然后去 “API 密钥”

  • 找到你的 API 密钥并选择右边的垃圾桶图标。

  • 点击 “删除 API 密钥” 进行确认。

如何查看每个 API 请求的使用情况?

  • 在 Ninja 中,转到左侧面板并单击 API 管理图标

  • 然后点击 “API 使用情况”

  • “API 使用情况” 页面,您将看到一个表格,其中显示了每个 API 的以下详细信息:

    • 密钥名称

    • 模型

    • 输入和输出标记

    • 投入和产出成本

    • 请求的时间戳

    • 总成本