AI 运行时
核心 LLM 推理(对话、嵌入、视觉、图像生成、语音 TTS/ASR)与 OpenAI 兼容:用官方 openai SDK 指向 infrai 的 base_url 即可调用。此处列出的是 infrai 原生扩展:批处理、成本/Token 工具、rerank、图像超分、TTS 音色与实时语音会话。
OpenAI 兼容端点
核心 AI 推理(对话、embedding、文生图、语音合成、语音识别、内容审核、模型目录)走标准 OpenAI API 接口——把 OpenAI SDK 指向 infrai 的 base URL 即可。完整示例 → 在找 chat、embeddings、图像或语音?它们由 OpenAI 兼容 API 提供——把 OpenAI SDK 指向 infrai →
| 端点 | infrai 能力 | 用途 |
|---|---|---|
POST /v1/chat/completions | ai.chat | 对话补全——文本、视觉与工具调用,支持流式。 |
POST /v1/embeddings | ai.embed | 文本向量,用于检索与 RAG。 |
POST /v1/images/generations | ai.image | 根据文本提示生成图像。 |
POST /v1/audio/speech | ai.tts | 文本转语音——合成语音音频。 |
POST /v1/audio/transcriptions | ai.asr | 语音转文本——转写音频文件。 |
POST /v1/moderations | ai.moderation | 判定内容是否违反使用政策。 |
GET /v1/models | ai.models.list | 列出所有已验证、可路由厂商提供的模型。 |
GET /v1/models/{model} | ai.models.get | 获取单个模型的详情(定价、上下文、可用性)。 |
1. 概览
https://api.infrai.cc/v1/aiAuthorization: Bearer $INFRAI_API_KEY# Call any /v1/ai capability over raw HTTP — no SDK to install.
# curl:
curl https://api.infrai.cc/v1/ai/... \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json"2. 方法 (11)
2.1ai.batch.submit
提交一批 AI 请求作为单个异步批处理任务,批量模式按成本原价透传。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
requests | BatchRequestItem[] | 必填 | 批处理请求条目数组,每条含 capability 与 body。≥ 1 item |
batch_timeout | string | 可选 | 批处理的最长完成时限(如 24h),超时未完成的条目按失败处理。default: "24h"e.g. 1h |
metadata | Record<string, unknown> | 可选 | 附加到批处理任务上的自定义键值元数据。 |
idempotency_key | string | 可选 | 可选去重 key;相同重试将返回同一结果。 |
返回
BatchSubmitResult { batch_id, state, total_count, estimated_eta?, estimated_cost_usd? }| 名称 | 类型 | 说明 |
|---|---|---|
batch_id | string | batch job的唯一标识符pattern: ^batch_[A-Za-z0-9]{20,}$ |
state | "connecting" | "queued" | "in_progress" | "completed" | "failed" | "expired" | "cancelled" | 当前生命周期状态 |
total_count | integer | 跨所有页的总条目数≥ 1 |
estimated_eta | string | null | 批处理预计剩余时间format: date-time |
estimated_cost_usd | number | null | 批处理预估总费用(美元)≥ 0 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/batch/submit \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"requests": [{}]}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/submit",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'requests': [{}]},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/submit",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"requests": [{}]}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/submit",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"requests": [{}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"requests": [{}]}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/batch/submit", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/submit"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"requests\": [{}]}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/batch/submit");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"requests\": [{}]}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/submit");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"requests\": [{}]}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/submit")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"requests": [{}]}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/batch/submit")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"requests": [{}]}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.2ai.batch.status
查询批处理任务的状态、进度与已完成/失败计数。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
batch_id | string | 必填 | 目标批处理任务的 ID。 |
返回
BatchStatus { batch_id, state, progress, total_count, completed_count, failed_count, created_at, total_cost_usd? }| 名称 | 类型 | 说明 |
|---|---|---|
batch_id | string | batch job的唯一标识符pattern: ^batch_[A-Za-z0-9]{20,}$ |
state | "connecting" | "queued" | "in_progress" | "completed" | "failed" | "expired" | "cancelled" | 当前生命周期状态 |
progress | number | 异步操作进度(0.0 到 1.0)0–1 |
total_count | integer | 跨所有页的总条目数≥ 0 |
completed_count | integer | 批处理中已完成条目数≥ 0 |
failed_count | integer | 批处理中失败条目数≥ 0 |
created_at | string | 资源创建时间(ISO 8601)format: date-time |
estimated_completion_at | string | null | 批处理预计完成时间(ISO 8601)format: date-time |
actual_completion_at | string | null | 批处理实际完成时间(ISO 8601)format: date-time |
total_cost_usd | number | null | 批处理总费用(美元)≥ 0 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X GET https://api.infrai.cc/v1/ai/batch/status/ID \
-H "Authorization: Bearer $INFRAI_API_KEY"# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/status/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/status/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/status/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.infrai.cc/v1/ai/batch/status/ID", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/status/ID"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("GET"), "https://api.infrai.cc/v1/ai/batch/status/ID");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/status/ID");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/status/ID")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.infrai.cc/v1/ai/batch/status/ID")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.3ai.batch.results
分页拉取批处理任务的逐条结果。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
batch_id | string | 必填 | 目标批处理任务的 ID。 |
cursor | string | 可选 | 分页游标:传入上一页返回的 next_cursor 获取下一页。 |
limit | number | 可选 | 单页返回条数上限。 |
返回
BatchResultsPage { items, total_count, next_cursor?, download_url? }| 名称 | 类型 | 说明 |
|---|---|---|
items | object[] | 本页结果条目数组 |
items[].request_index | integer | 在原始 requests 数组中的索引。≥ 0 |
items[].ok | boolean | 操作是否成功 |
items[].result | any | ok=true 时的能力结果(ChatResult / EmbeddingResult)。 |
items[].error | object | null | 操作失败时的错误消息 |
items[].error.code | string | 来自 registry.yaml 的稳定标识符。 |
items[].error.http_status | integer | Webhook 投递尝试的 HTTP 状态码400–599 |
items[].error.message | string | 可读提示。 |
items[].error.docs_url | string | 此错误码的文档 URLformat: uri |
items[].error.code_detail | string | 子分类(如钱包上限原因)。 |
items[].error.retryable | boolean | 错误是否可重试 |
items[].error.retry_after_ms | integer | 建议重试延迟(毫秒)≥ 0 |
items[].error.param | string | 验证失败的参数(如适用)。 |
items[].error.trace_id | string | 分布式追踪标识符 |
items[].error.request_id | string | 服务端分配的追踪请求标识符 |
total_count | integer | 跨所有页的总条目数≥ 0 |
next_cursor | string | null | 传入 results() 以获取下一页;null 表示结束。 |
download_url | string | null | 大型结果集的批量下载引用(JSONL);结果内联时为 null。format: uri |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X GET https://api.infrai.cc/v1/ai/batch/results/ID \
-H "Authorization: Bearer $INFRAI_API_KEY"# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/results/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/results/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/results/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.infrai.cc/v1/ai/batch/results/ID", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/results/ID"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("GET"), "https://api.infrai.cc/v1/ai/batch/results/ID");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/results/ID");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/results/ID")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.infrai.cc/v1/ai/batch/results/ID")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.4ai.batch.list
分页列出本账户的全部批处理任务。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
cursor | string | 可选 | 分页游标:传入上一页返回的 next_cursor 获取下一页。 |
limit | number | 可选 | 单页返回条数上限。 |
返回
BatchListResult { batches, total_count, next_cursor? }| 名称 | 类型 | 说明 |
|---|---|---|
batches | object[] | batch summary objects列表 |
batches[].batch_id | string | batch job的唯一标识符pattern: ^batch_[A-Za-z0-9]{20,}$ |
batches[].state | "connecting" | "queued" | "in_progress" | "completed" | "failed" | "expired" | "cancelled" | 此资源当前的生命周期状态 |
batches[].progress | number | 异步操作进度(0.0 到 1.0)0–1 |
batches[].total_count | integer | 所有页的条目总数≥ 0 |
batches[].completed_count | integer | completed items in the batch数量≥ 0 |
batches[].failed_count | integer | failed items in the batch数量≥ 0 |
batches[].created_at | string | 此资源创建的 ISO 8601 时间戳format: date-time |
batches[].estimated_completion_at | string | null | 批处理预计完成时间(ISO 8601)format: date-time |
batches[].actual_completion_at | string | null | 批处理实际完成的 ISO 8601 时间戳format: date-time |
batches[].total_cost_usd | number | null | 批处理总成本(美元)≥ 0 |
total_count | integer | 跨所有页的总条目数≥ 0 |
next_cursor | string | null | 传入 list() 以获取下一页;null 表示结束。 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X GET https://api.infrai.cc/v1/ai/batch/list \
-H "Authorization: Bearer $INFRAI_API_KEY"# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/list",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/list",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/list",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.infrai.cc/v1/ai/batch/list", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/list"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("GET"), "https://api.infrai.cc/v1/ai/batch/list");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/list");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/list")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.infrai.cc/v1/ai/batch/list")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.5ai.batch.cancel
取消一个进行中的批处理任务。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
batch_id | string | 必填 | 要取消的批处理任务的 ID。 |
idempotency_key | string | 可选 | 可选去重 key;相同重试将返回同一结果。 |
返回
BatchStatus { batch_id, state, ... }| 名称 | 类型 | 说明 |
|---|---|---|
batch_id | string | batch job的唯一标识符pattern: ^batch_[A-Za-z0-9]{20,}$ |
state | "connecting" | "queued" | "in_progress" | "completed" | "failed" | "expired" | "cancelled" | 当前生命周期状态 |
progress | number | 异步操作进度(0.0 到 1.0)0–1 |
total_count | integer | 跨所有页的总条目数≥ 0 |
completed_count | integer | 批处理中已完成条目数≥ 0 |
failed_count | integer | 批处理中失败条目数≥ 0 |
created_at | string | 资源创建时间(ISO 8601)format: date-time |
estimated_completion_at | string | null | 批处理预计完成时间(ISO 8601)format: date-time |
actual_completion_at | string | null | 批处理实际完成时间(ISO 8601)format: date-time |
total_cost_usd | number | null | 批处理总费用(美元)≥ 0 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/batch/cancel/ID \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"batch_id": "sample"}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'batch_id': 'sample'},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"batch_id": "sample"}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"batch_id": "sample"}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"batch_id": "sample"}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/batch/cancel/ID", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/cancel/ID"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"batch_id\": \"sample\"}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/batch/cancel/ID");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"batch_id\": \"sample\"}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/cancel/ID");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"batch_id\": \"sample\"}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/cancel/ID")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"batch_id": "sample"}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/batch/cancel/ID")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"batch_id": "sample"}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.6ai.batch.export
将批处理结果导出为 jsonl 或 csv 文件并返回下载任务。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
batch_id | string | 必填 | 要导出的批处理任务的 ID。pattern: ^batch_[A-Za-z0-9]{20,}$ |
format | "jsonl" | "csv" | 可选 | 导出文件格式:jsonl 或 csv。default: "jsonl" |
conversation_id | string | 可选 | 可选,仅导出指定会话的结果。 |
metadata | Record<string, unknown> | 可选 | 附加到导出任务上的自定义键值元数据。 |
idempotency_key | string | 可选 | 可选去重 key;相同重试将返回同一结果。 |
返回
ExportJob { export_id, state, format?, download_url?, expires_at?, created_at }| 名称 | 类型 | 说明 |
|---|---|---|
export_id | string | export job的唯一标识符pattern: ^exp_[A-Za-z0-9]{20,}$ |
state | "queued" | "in_progress" | "completed" | "failed" | "expired" | 当前生命周期状态 |
format | "jsonl" | "csv" | 输出或输入格式(如 json、csv、png)default: "jsonl" |
download_url | string | null | state=completed 时填充。format: uri |
expires_at | string | null | 资源或令牌过期时间(ISO 8601)format: date-time |
created_at | string | 资源创建时间(ISO 8601)format: date-time |
error | object | null | 操作失败时的错误消息 |
error.code | string | 来自 registry.yaml 的稳定标识符。 |
error.http_status | integer | Webhook 投递尝试的 HTTP 状态码400–599 |
error.message | string | 可读提示。 |
error.docs_url | string | 此错误码的文档 URLformat: uri |
error.code_detail | string | 子分类(如钱包上限原因)。 |
error.retryable | boolean | 错误是否可重试 |
error.retry_after_ms | integer | 建议重试延迟(毫秒)≥ 0 |
error.param | string | 验证失败的参数(如适用)。 |
error.trace_id | string | 分布式追踪标识符 |
error.request_id | string | 服务端分配的追踪请求标识符 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/batch/export/ID \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/export/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/export/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/export/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/batch/export/ID", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/batch/export/ID"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/batch/export/ID");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/batch/export/ID");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/batch/export/ID")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/batch/export/ID")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.7ai.cost.estimate
在调用前估算一次 AI 请求的 token 数与分项成本。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | string | ChatMessage[] | 必填 | 用于估算的消息,可为字符串或消息数组。≥ 1 item |
model | string | 可选 | 显式模型 id;跳过 task/prefer 路由。default: "openai/gpt-4o" |
expected_output_tokens | number | 可选 | 预期的输出 token 数,用于估算输出侧成本。≥ 0default: 500 |
cache_strategy | "vendor" | "infrai" | "none" | 可选 | 使用哪一层缓存。default: "vendor" |
batch_mode | boolean | 可选 | 以批处理任务运行以获得折扣价。default: false |
tools | Tool[] | 可选 | 工具/函数调用定义。 |
返回
CostEstimate { model, vendor, vendor_region?, prompt_tokens, expected_output_tokens, breakdown }| 名称 | 类型 | 说明 |
|---|---|---|
model | string | 此估算的目标已解析模型 ID。 |
vendor | string | 将服务此请求的供应商。 |
vendor_region | "china" | "western" | 服务供应商所在地区(决定加价幅度)。 |
prompt_tokens | integer | tokens in the prompt数量≥ 0 |
expected_output_tokens | integer | 预估的输出 token 数≥ 0 |
breakdown | object | 按组件的成本分解 |
breakdown.currency | "USD" | "CNY" | ISO 4217 货币代码(如 USD、CNY) |
breakdown.input_cost | number | 输入 token 成本(美元)≥ 0 |
breakdown.output_cost | number | 输出 token 成本(美元)≥ 0 |
breakdown.markup | number | 供应商成本之上的加价≥ 0 |
breakdown.cache_discount | number | 缓存命中折扣(美元)≥ 0 |
breakdown.batch_discount | number | 批处理折扣(美元)≥ 0 |
breakdown.failover_adjustment | number | 供应商故障转移导致的成本调整 |
breakdown.final | number | 所有调整后的最终成本(美元)≥ 0 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/cost/estimate \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "system"}]}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/cost/estimate",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'messages': [{'role': 'system'}]},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/estimate",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/estimate",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"messages": [{"role": "system"}]}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/cost/estimate", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/cost/estimate"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"messages\": [{\"role\": \"system\"}]}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/cost/estimate");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"messages\": [{\"role\": \"system\"}]}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/cost/estimate");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"messages\": [{\"role\": \"system\"}]}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/cost/estimate")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"messages": [{"role": "system"}]}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/cost/estimate")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"messages": [{"role": "system"}]}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.8ai.cost.compare
对同一请求在多个模型上估算并对比成本。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | string | ChatMessage[] | 必填 | 用于对比估算的消息,可为字符串或消息数组。≥ 1 item |
models | string[] | 可选 | 参与成本对比的模型 ID 列表。 |
expected_output_tokens | number | 可选 | 预期的输出 token 数,用于估算输出侧成本。≥ 0default: 500 |
cache_strategy | "vendor" | "infrai" | "none" | 可选 | 使用哪一层缓存。default: "vendor" |
batch_mode | boolean | 可选 | 以批处理任务运行以获得折扣价。default: false |
tools | Tool[] | 可选 | 工具/函数调用定义。 |
返回
{ estimates: CostEstimate[] }示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/cost/compare \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "system"}]}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/cost/compare",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'messages': [{'role': 'system'}]},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/compare",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/compare",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"messages": [{"role": "system"}]}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/cost/compare", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/cost/compare"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"messages\": [{\"role\": \"system\"}]}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/cost/compare");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"messages\": [{\"role\": \"system\"}]}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/cost/compare");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"messages\": [{\"role\": \"system\"}]}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/cost/compare")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"messages": [{"role": "system"}]}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/cost/compare")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"messages": [{"role": "system"}]}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.9ai.tokens.count
统计一组消息在指定模型下的输入 token 数。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | string | ChatMessage[] | 必填 | 要统计 token 数的消息,可为字符串或消息数组。≥ 1 item |
model | string | 可选 | 显式模型 id;跳过 task/prefer 路由。 |
tools | Tool[] | 可选 | 工具/函数调用定义。 |
返回
TokenCountResult { prompt_tokens, model }| 名称 | 类型 | 说明 |
|---|---|---|
prompt_tokens | integer | 总提示 token,含工具定义开销。≥ 0 |
model | string | 计数所使用的分词模型。 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/tokens/count \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "system"}]}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/tokens/count",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'messages': [{'role': 'system'}]},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/tokens/count",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/tokens/count",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"messages": [{"role": "system"}]}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/tokens/count", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/tokens/count"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"messages\": [{\"role\": \"system\"}]}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/tokens/count");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"messages\": [{\"role\": \"system\"}]}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/tokens/count");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"messages\": [{\"role\": \"system\"}]}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/tokens/count")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"messages": [{"role": "system"}]}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/tokens/count")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"messages": [{"role": "system"}]}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.10ai.image.upscale
将图片按 2 倍或 4 倍无损放大。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
image | string | 必填 | 待放大的源图片,URL 或 base64。e.g. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg== |
factor | 2 | 4 | 可选 | 放大倍数,2 或 4。default: 2 |
idempotency_key | string | 可选 | 可选去重 key;相同重试将返回同一结果。 |
返回
ImageUpscaleResult { image, original_size, new_size }| 名称 | 类型 | 说明 |
|---|---|---|
image | object | 用于处理的图片数据或引用 |
image.b64_json | string | 放大后图片的 Base64 编码字节(内联;无状态透传)。 |
image.width | integer | -≥ 1 |
image.height | integer | -≥ 1 |
image.mime_type | string | -e.g. image/png |
image.image_id | string | null | 仅当调用方传入 store:true 时设置;默认无状态转换时为 null。 |
image.url | string | null | 存储后生成的 Infrai CDN URL;默认 null。format: uri |
original_size | string | 变换前的原始图片尺寸e.g. 1024x1024 |
new_size | string | 变换后的新图片尺寸e.g. 2048x2048 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X POST https://api.infrai.cc/v1/ai/image/upscale \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}'# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/image/upscale",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'image': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/image/upscale",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}),
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/image/upscale",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/ai/image/upscale", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/image/upscale"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"image\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\"}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/ai/image/upscale");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"image\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\"}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/image/upscale");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"image\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\"}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/image/upscale")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}'
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/ai/image/upscale")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}2.11ai.tts.voices
分页列出文本转语音可用的音色列表。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
vendor | string | 可选 | 固定使用某个供应商,而非自动路由。 |
返回
VoiceListResult { items, count, next_cursor? }| 名称 | 类型 | 说明 |
|---|---|---|
items | object[] | 本页结果条目数组 |
items[].voice_id | string | - |
items[].vendor | string | - |
items[].name | string | null | - |
items[].model | string | null | 此语音合成时应搭配的供应商模型。 |
items[].language | string | null | BCP-47 语言标签。 |
items[].languages | string[] | null | 供应商为此语音公布的支持语言或地区。 |
items[].gender | string | null | - |
items[].preview_url | string | null | -format: uri |
items[].is_default | boolean | 未指定语音时,synthesize() 是否使用此供应商默认语音。 |
next_cursor | string | null | 传入 voices() 以获取下一页;null 表示结束。 |
count | integer | 跨所有页的总条目数≥ 0 |
示例
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."curl -X GET https://api.infrai.cc/v1/ai/tts/voices \
-H "Authorization: Bearer $INFRAI_API_KEY"# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/tts/voices",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/tts/voices",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/tts/voices",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.infrai.cc/v1/ai/tts/voices", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/ai/tts/voices"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("GET"), "https://api.infrai.cc/v1/ai/tts/voices");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/ai/tts/voices");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/ai/tts/voices")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
res = http.request(req)
puts res.body// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.get("https://api.infrai.cc/v1/ai/tts/voices")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}高级:指定 vendor
默认情况下 infrai 会把每次调用智能路由到最佳可用供应商——无需自己挑选 vendor。作为高级逃生口,本能力支持可选的 vendor 入参以锁定某个供应商。本能力当前所有可用 vendor 可通过该能力 id 对应的 discovery 端点实时获取——参见 discovery API。
GET /v1/discovery/{capability}ai.image.upscale
ai.tts.voices
3. 全部能力
本模块全部已路由能力——完整的对外 REST 契约。上方方法是带讲解的入门示例,此表是完整参考。
ai.asrPOST /v1/audio/transcriptionsSpeech-to-text — transcribe an audio file (multipart or base64 JSON).
参数 (4)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
file | string | 必填 | Audio file to transcribe when using multipart/form-data.format: binary |
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
language | string | 可选 | ISO-639-1 language hint. |
response_format | "json" | "text" | "srt" | "verbose_json" | "vtt" | 可选 |
ai.batch.cancelPOST /v1/ai/batch/cancel/{id}Cancel an in-progress batch job (idempotent).
参数 (3)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
id | string | 必填 | Path parameter. |
batch_id | string | 必填 | Id of the batch job to cancel. |
idempotency_key | string | null | 可选 | Client-provided idempotency key; prevents duplicate execution on retry |
ai.batch.exportPOST /v1/ai/batch/export/{id}Export batch results to a JSONL or CSV file and return a download job.
参数 (6)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
id | string | 必填 | Path parameter. |
batch_id | string | null | 可选 | Target batch for ai.batch.export.pattern: ^batch_[A-Za-z0-9]{20,}$ |
conversation_id | string | null | 可选 | Target conversation for ai.chat.history.export; null = all history. |
format | "jsonl" | "csv" | 可选 | Output or input format (e.g. json, csv, png)default: "jsonl" |
idempotency_key | string | null | 可选 | Client-provided idempotency key; prevents duplicate execution on retry |
metadata | object | null | 可选 | Arbitrary key-value metadata attached to this resource |
ai.batch.listGET /v1/ai/batch/listList all batch jobs on the account with pagination.
无请求参数。
ai.batch.resultsGET /v1/ai/batch/results/{id}Fetch per-item results of a batch job with pagination.
参数 (1)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
id | string | 必填 | Path parameter. |
ai.batch.statusGET /v1/ai/batch/status/{id}Get a batch job's status, progress, and completed/failed counts.
参数 (1)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
id | string | 必填 | Path parameter. |
ai.batch.submitPOST /v1/ai/batch/submitSubmit a batch of AI requests as one async batch job (billed at cost pass-through with no markup).
参数 (5)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
requests | object[] | 必填 | Each item is a ChatRequest / EmbeddingRequest payload.≥ 1 item |
batch_timeout | string | 可选 | Maximum wall-clock the batch may run before expiring.default: "24h"e.g. 1h |
metadata | object | null | 可选 | Arbitrary key-value metadata attached to this resource |
idempotency_key | string | null | 可选 | Client-provided idempotency key; prevents duplicate execution on retry |
store | boolean | 可选 | Opt in to RETAIN the produced asset/record in Infrai's own store (default false = stateless passthrough: process, return inline, keep nothing). When true, Infrai persists the asset, bills a self-hosted storage line item and applies a retention TTL — and only then do the *.list/get/delete read caps see it.default: false |
ai.chatPOST /v1/chat/completionsChat completions — text, vision and tool calls, with streaming.
参数 (8)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
messages | object[] | 必填 | OpenAI chat messages: a list of {role, content}. |
temperature | number | 可选 | |
max_tokens | integer | 可选 | |
top_p | number | 可选 | |
stream | boolean | 可选 | Server-Sent Events streaming when true. |
tools | object[] | 可选 | |
response_format | object | 可选 |
ai.cost.comparePOST /v1/ai/cost/compareEstimate and compare the cost of the same request across multiple models.
参数 (7)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | object[] | 必填 | Chat messages to price (same shape as ai.chat); cost is estimated from their token count.≥ 1 item |
model | string | null | 可选 | Single model to estimate. Used by ai.cost.estimate. Explicit model_id is allowed here (selection semantics).default: "openai/gpt-4o" |
models | string[] | null | 可选 | Models to compare. Used by ai.cost.compare; result is sorted ascending by final cost. |
expected_output_tokens | integer | 可选 | Assumed completion length for the estimate.≥ 0default: 500 |
cache_strategy | "vendor" | "infrai" | "none" | 可选 | Cache strategy hint (none, exact, semantic)default: "vendor" |
batch_mode | boolean | 可选 | When true, applies the 50% batch discount to the estimate.default: false |
tools | object[] | null | 可选 | Tool/function definitions for the model to call |
ai.cost.estimatePOST /v1/ai/cost/estimateEstimate token counts and itemized cost for an AI request before calling it.
参数 (7)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | object[] | 必填 | Chat messages to price (same shape as ai.chat); cost is estimated from their token count.≥ 1 item |
model | string | null | 可选 | Single model to estimate. Used by ai.cost.estimate. Explicit model_id is allowed here (selection semantics).default: "openai/gpt-4o" |
models | string[] | null | 可选 | Models to compare. Used by ai.cost.compare; result is sorted ascending by final cost. |
expected_output_tokens | integer | 可选 | Assumed completion length for the estimate.≥ 0default: 500 |
cache_strategy | "vendor" | "infrai" | "none" | 可选 | Cache strategy hint (none, exact, semantic)default: "vendor" |
batch_mode | boolean | 可选 | When true, applies the 50% batch discount to the estimate.default: false |
tools | object[] | null | 可选 | Tool/function definitions for the model to call |
ai.embedPOST /v1/embeddingsText embeddings for search and RAG.
参数 (4)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
input | string | string[] | 必填 | Text string or array of strings to embed. |
encoding_format | "float" | "base64" | 可选 | |
dimensions | integer | 可选 |
ai.imagePOST /v1/images/generationsImage generation from a text prompt.
参数 (5)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
prompt | string | 必填 | Text prompt describing the image. |
n | integer | 可选 | |
size | string | 可选 | Image size such as '1024x1024'. |
response_format | "url" | "b64_json" | 可选 |
ai.image.upscalePOST /v1/ai/image/upscaleUpscale an image losslessly by 2x or 4x with an AI model (idempotent). To transform an EXISTING image otherwise use the image.* module.
参数 (8)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
image | string | 必填 | URL / file path / base64 of the source image.e.g. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg== |
factor | 2 | 4 | 可选 | Upscale factor (e.g. 2 or 4)default: 2 |
model | string | null | 可选 | Model identifier to use for generation |
vendor | string | null | 可选 | Vendor that handled or will handle this request |
timeout_seconds | integer | 可选 | Maximum execution time in seconds1–600default: 120 |
idempotency_key | string | null | 可选 | Client-provided idempotency key; prevents duplicate execution on retry |
metadata | object | null | 可选 | Arbitrary key-value metadata attached to this resource |
store | boolean | 可选 | Opt in to RETAIN the produced asset/record in Infrai's own store (default false = stateless passthrough: process, return inline, keep nothing). When true, Infrai persists the asset, bills a self-hosted storage line item and applies a retention TTL — and only then do the *.list/get/delete read caps see it.default: false |
ai.models.getGET /v1/models/{model}Retrieve one model's details (pricing, context, availability).
参数 (1)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 必填 | Path parameter. |
ai.models.listGET /v1/modelsList every model a verified, routable vendor serves.
无请求参数。
ai.moderationPOST /v1/moderationsClassify whether content violates usage policy.
参数 (2)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
input | string | string[] | 必填 | Text string or array of strings to moderate. |
ai.rerankPOST /v1/ai/rerankReorder a list of candidate documents by relevance to a query, returning each candidate's original index and a vendor relevance score. Real vendor dispatch: Cohere rerank, Qwen/DashScope gte-rerank. Replaces the previous original-order mock.
参数 (5)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
query | string | 必填 | Search query string for reranking≥ 1 chars |
candidates | string[] | 必填 | Documents to score against the query; the response returns them reordered by relevance.≥ 1 item |
top_k | integer | 可选 | Number of top results to return≥ 1default: 10 |
model | string | 可选 | Optional model pin (e.g. rerank-english-v3.0, gte-rerank). |
vendor | "cohere" | "jina" | "qwen" | 可选 | Optional vendor pin. |
ai.tokens.countPOST /v1/ai/tokens/countCount input tokens for a set of messages under a given model.
参数 (3)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | object[] | 必填 | Chat messages to tokenize (same shape as ai.chat), including tool-definition overhead.≥ 1 item |
model | string | null | 可选 | Tokenizer model; null = default. Determines which encoding is used. |
tools | object[] | null | 可选 | Tool definitions; their serialized overhead is included in the count. |
ai.ttsPOST /v1/audio/speechText-to-speech — synthesize spoken audio (binary body).
参数 (5)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 可选 | Model to use. 'auto' (default) lets infrai smart-route across healthy vendors; 'vendor/model' pins a specific vendor and model.e.g. auto |
input | string | 必填 | The text to synthesize. |
voice | string | 必填 | Voice id such as 'alloy'. |
response_format | string | 可选 | Audio format such as 'mp3' or 'wav'. |
speed | number | 可选 |
ai.tts.voicesGET /v1/ai/tts/voicesList available text-to-speech voices with pagination.
无请求参数。
ai.voice.sessionPOST /v1/ai/voice/sessionMint a short-lived token for an AI realtime VOICE/multimodal conversation session (e.g. OpenAI Realtime). NOT pub/sub channel auth — see realtime.token.issue.
参数 (6)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | null | 可选 | Realtime voice model; null lets the server pick a default. |
voice | string | null | 可选 | Voice id/name to use for the session. |
vendor | string | null | 可选 | Pin to a specific vendor; disables failover. |
instructions | string | null | 可选 | System instructions for the realtime session. |
modalities | string[] | null | 可选 | Enabled modalities (e.g. text, audio). |
idempotency_key | string | null | 可选 | Client-provided idempotency key; prevents duplicate execution on retry |
4. 完整示例
本模块的生产级端到端范例:先一次性配置,再运行业务流程,尽量覆盖本模块的多数 API。
单文件可运行 Python 程序(仅标准库、无 SDK):拷贝后填入 INFRAI_API_KEY 运行,即可按真实业务流逐步体验本模块核心 API——每一步都真实调用并计费,后续步骤复用前一步返回的真实字段。12 行 helper 就是全部集成代码。
#!/usr/bin/env python3
"""Infrai · ai-runtime — runnable real-app example (single file, zero deps).
Copy this file, set your key, run it: every step is a REAL call to
api.infrai.cc, billed at the real (tiny) per-call price, printing the
live JSON response. Get a key at https://infrai.cc/login (Google/
GitHub sign-in grants $2 free credit); add funds at
https://infrai.cc/billing. No SDK — the 12-line helper below is the
entire integration."""
import json
import os
from urllib import error, request
KEY = os.environ.get("INFRAI_API_KEY") or "ifr_..." # <- your key
BASE = "https://api.infrai.cc"
# Same raw HTTPS POST/GET as every per-method example on this page —
# wrapped once for reuse. There is nothing else to it: no SDK.
def infrai(method, path, body=None):
req = request.Request(
BASE + path, method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json"})
try:
with request.urlopen(req, timeout=60) as r:
return json.loads(r.read())
except error.HTTPError as e:
return json.loads(e.read())
def show(label, resp):
print(f"\n== {label} ==")
print(json.dumps(resp, indent=2, ensure_ascii=False))
return resp
# 1) chat — POST /v1/chat/completions (OpenAI-compatible)
ask1 = input("Ask the model anything: ").strip()
r1 = show("chat", infrai("POST", "/v1/chat/completions", {"model":"auto","messages":[{"role":"user","content":ask1}]}))
# 2) embeddings — POST /v1/embeddings (OpenAI-compatible)
r2 = show("embeddings", infrai("POST", "/v1/embeddings", {"model":"auto","input":"Infrai is the standard library for AI-built apps."}))
# 3) ai.cost.estimate — POST /v1/ai/cost/estimate · Estimate token counts and itemized cost for an AI request before calling it.
r3 = show("ai.cost.estimate", infrai("POST", "/v1/ai/cost/estimate", {"messages":[{"role":"system"}]}))
一次性前置(每个范例都假定已完成):
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."# 1) Auth: every call is a raw HTTPS request to the Infrai gateway carrying
# only your project key. No SDK, no install.
# Get your key: sign in with Google/GitHub at https://infrai.cc/login for a
# project key + $2 free credit (email sign-in starts at $0). On 402
# INSUFFICIENT_CREDIT, add funds at https://infrai.cc/billing (or POST
# /v1/account/topup and open the returned checkout_url).
export INFRAI_API_KEY="ifr_..." # from https://infrai.cc/login
# 2) ai.batch.submit
curl -X POST https://api.infrai.cc/v1/ai/batch/submit \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"requests": [{}]}'
# 3) ai.batch.status
curl -X GET https://api.infrai.cc/v1/ai/batch/status/ID \
-H "Authorization: Bearer $INFRAI_API_KEY"
# 4) ai.batch.results
curl -X GET https://api.infrai.cc/v1/ai/batch/results/ID \
-H "Authorization: Bearer $INFRAI_API_KEY"
# 5) ai.batch.list
curl -X GET https://api.infrai.cc/v1/ai/batch/list \
-H "Authorization: Bearer $INFRAI_API_KEY"
# 6) ai.batch.cancel
curl -X POST https://api.infrai.cc/v1/ai/batch/cancel/ID \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"batch_id": "sample"}'
# 7) ai.batch.export
curl -X POST https://api.infrai.cc/v1/ai/batch/export/ID \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'
# 8) ai.cost.estimate
curl -X POST https://api.infrai.cc/v1/ai/cost/estimate \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "system"}]}'
# 1) Auth: every call is a raw HTTPS request carrying only your project key.
# No SDK to install — just the `requests` library.
import os, requests
BASE = "https://api.infrai.cc"
HEADERS = {
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
"Content-Type": "application/json",
}
# 2) ai.batch.submit
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/submit",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'requests': [{}]},
)
resp.raise_for_status()
print(resp.json())
# 3) ai.batch.status
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/status/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())
# 4) ai.batch.results
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/results/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())
# 5) ai.batch.list
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.get(
"https://api.infrai.cc/v1/ai/batch/list",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
)
resp.raise_for_status()
print(resp.json())
# 6) ai.batch.cancel
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'batch_id': 'sample'},
)
resp.raise_for_status()
print(resp.json())
# 7) ai.batch.export
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/batch/export/ID",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={},
)
resp.raise_for_status()
print(resp.json())
# 8) ai.cost.estimate
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/ai/cost/estimate",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'messages': [{'role': 'system'}]},
)
resp.raise_for_status()
print(resp.json())
// 1) Auth: every call is a raw HTTPS request carrying only your project key.
// No SDK to install — just the built-in fetch().
const BASE = "https://api.infrai.cc";
const HEADERS = {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
};
// 2) ai.batch.submit
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/submit",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"requests": [{}]}),
},
);
console.log(await resp.json());
// 3) ai.batch.status
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/status/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());
// 4) ai.batch.results
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/results/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());
// 5) ai.batch.list
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/list",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
console.log(await resp.json());
// 6) ai.batch.cancel
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"batch_id": "sample"}),
},
);
console.log(await resp.json());
// 7) ai.batch.export
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/export/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
},
);
console.log(await resp.json());
// 8) ai.cost.estimate
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/estimate",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
console.log(await resp.json());
// 1) Auth: every call is a raw HTTPS request carrying only your project key.
// No SDK to install — just the built-in fetch(), typed.
const BASE = "https://api.infrai.cc";
const HEADERS: Record<string, string> = {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
};
// 2) ai.batch.submit
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/submit",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"requests": [{}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 3) ai.batch.status
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/status/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 4) ai.batch.results
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/results/ID",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 5) ai.batch.list
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/list",
{
method: "GET",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
},
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 6) ai.batch.cancel
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/cancel/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"batch_id": "sample"}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 7) ai.batch.export
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/batch/export/ID",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);
// 8) ai.cost.estimate
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/ai/cost/estimate",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"messages": [{"role": "system"}]}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);