跳到正文

AI 运行时

多供应商 LLM 对话、嵌入、视觉、图像生成、语音与实时会话。

概览

基础路径: /v1/ai
Python 命名空间: ai
text
# Python
from infrai import ai

# TypeScript
import { InfraiClient } from "@infrai/sdk";
const client = new InfraiClient({ apiKey: process.env.INFRAI_API_KEY! });
// → client.ai

方法

ai.chat

POST /v1/ai/chat

多供应商对话补全,支持基于质量的路由、工具、结构化输出、缓存与批处理模式。

Python

python
ai.chat(prompt, *, model=None, vendor=None, task="general", prefer="balanced", stream=False, response_format=None, tools=None, cache_strategy="vendor", batch_mode=False, max_cost_multiplier=1.5, timeout_seconds=60, idempotency_key=None)

TypeScript

typescript
client.ai.chat(opts: ChatOptions): Promise<ChatResult>

参数

名称类型必填说明
messagesstring | ChatMessage[]
必填
提示字符串,或角色/内容消息列表。
modelstring可选显式模型 id;跳过 task/prefer 路由。
vendorstring可选固定某个 AI 供应商。
task"general" | "reasoning" | "coding" | "long_context"可选用途轴(general/reasoning/coding/long_context);路由到对应模型家族。
prefer"balanced" | "cheapest" | "smartest"可选优化轴:balanced(最佳性价比)| cheapest | smartest。
temperaturenumber可选采样温度。
max_tokensnumber可选生成的最大 token 数。
toolsTool[]可选工具/函数调用定义。
response_format{ type: "json_object" | "text" | "json_schema" }可选强制结构化输出(JSON 对象或 schema)。
cache_strategy"vendor" | "infrai" | "none"可选使用哪一层缓存。
batch_modeboolean可选以批处理任务运行以获得折扣价。
max_cost_multipliernumber可选相对主供应商的故障切换成本上限。
streamboolean可选设为 true 启用流式;请使用流式方法。
idempotency_keystring可选可选去重 key;相同重试将返回同一结果。

返回

ChatResult { content, finish_reason, usage, metadata }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

# stream=True asks the gateway to deliver the completion incrementally.
result = ai.chat(
    "Tell me a 50-word story about a curious raccoon.",
    prefer="balanced",
    stream=True,
)
print(result.get("text") or result.get("content"))
print("request_id:", result["_metadata"].get("request_id"))
print("vendor:", result["_metadata"].get("vendor"))

ai.chat

POST /v1/ai/chat

以 Server-Sent Events 流式返回对话 token;按到达顺序遍历分片。

Python

python
ai.chat(prompt, *, stream=True)  # iterate chunks

TypeScript

typescript
client.ai.streamChat(opts: ChatOptions): AsyncIterable<ChatStreamChunk>

参数

名称类型必填说明
messagesstring | ChatMessage[]
必填
提示字符串,或角色/内容消息列表。
signalAbortSignal可选用于取消流的 AbortSignal。

返回

AsyncIterable<ChatStreamChunk { delta, finish_reason, index }>

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

for chunk in ai.chat("Tell me a 50-word story about a curious raccoon.", stream=True):
    print(chunk.delta.content or "", end="", flush=True)

ai.embed

POST /v1/ai/embed

创建文本嵌入,支持单条或批量。

Python

python
ai.embed.create(text, *, model=None, vendor=None, dimensions=None, idempotency_key=None)

TypeScript

typescript
client.ai.embed(opts: EmbedOptions): Promise<EmbedResult>

参数

名称类型必填说明
inputstring | string[]
必填
要嵌入的文本或文本列表。
modelstring可选显式模型 id;跳过 task/prefer 路由。
dimensionsnumber可选目标嵌入维度数。
idempotency_keystring可选可选去重 key;相同重试将返回同一结果。

返回

EmbedResult { embeddings, model, usage, metadata }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

# Embed text once for semantic search / RAG, then rank by cosine similarity.
result = ai.embed.create("What animal has clever paws?")
data = result.get("data") or result.get("embeddings") or []
vector = data[0].get("embedding") if data and isinstance(data[0], dict) else data[0]
print("dimensions:", len(vector or []))

ai.image

POST /v1/ai/image

在多家图像供应商之间,根据文本提示生成图像。

Python

python
ai.image.generate(prompt, *, size=None, n=None, model=None, vendor=None, prefer="balanced")

TypeScript

typescript
client.ai.image(opts: ImageOptions): Promise<{ images }>

参数

名称类型必填说明
promptstring
必填
目标图像的文本描述。
sizestring可选输出尺寸,例如 1024x1024。
nnumber可选要生成的图像数量。
prefer"balanced" | "cheapest" | "smartest"可选优化轴:balanced(最佳性价比)| cheapest | smartest。

返回

{ images: Array<{ url, b64? }> }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

result = ai.image.generate(
    "A watercolor raccoon reading a book under a maple tree",
    size="1024x1024",
    n=1,
    prefer="balanced",
)
images = result.get("images") or result.get("data") or []
print("first url:", images[0].get("url") if images else None)

ai.vision

POST /v1/ai/vision

结合提示对一张或多张图像进行推理。

Python

python
ai.vision(prompt=..., images=[...], model=None, vendor=None)

TypeScript

typescript
client.ai.vision(opts: VisionOptions): Promise<ChatResult>

参数

名称类型必填说明
promptstring
必填
目标图像的文本描述。
imagesArray<{ url } | { base64, mime? }>
必填
图像引用,URL 或 base64。

返回

ChatResult

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

r = ai.vision(prompt="What's in this image?",
              images=[{"url": "https://example.com/photo.jpg"}])
print(r.get("content") or r.get("text"))

ai.tts

POST /v1/ai/tts

将文本合成为语音音频。

Python

python
ai.tts(input=..., voice=None, model=None, vendor=None, format=None)

TypeScript

typescript
client.ai.tts(opts: TtsOptions): Promise<{ audio_url, format }>

参数

名称类型必填说明
inputstring
必填
要合成为语音的文本。
voicestring可选使用的音色 id。
format"mp3" | "wav" | "ogg" | "pcm"可选输出音频格式。

返回

{ audio_url, format }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

r = ai.tts(input="Hello from Infrai.", voice="alloy", format="mp3")
print("audio url:", r.get("audio_url"))

ai.asr

POST /v1/ai/asr

将音频转写为文本,可选语言提示。

Python

python
ai.asr(audio=..., language=None, model=None, vendor=None)

TypeScript

typescript
client.ai.asr(opts: AsrOptions): Promise<{ text, language, segments? }>

参数

名称类型必填说明
audio{ url } | { base64, mime? }
必填
音频引用,URL 或 base64。
languagestring可选语言提示,例如 en 或 zh。

返回

{ text, language, segments? }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

r = ai.asr(audio={"url": "https://example.com/clip.mp3"}, language="en")
print("transcript:", r.get("text"))

ai.realtime.token

POST /v1/ai/realtime/token

为 WebRTC 实时会话签发短时令牌。

Python

python
ai.realtime.token(model=None, voice=None, ttl_seconds=None)

TypeScript

typescript
client.ai.liveToken(opts): Promise<LiveSessionToken>

参数

名称类型必填说明
modelstring可选显式模型 id;跳过 task/prefer 路由。
voicestring可选使用的音色 id。
ttl_secondsnumber可选过期前的有效时长(秒)。

返回

LiveSessionToken { session_id, ice_servers, token, expires_at }

示例

一次性前置(每个范例都假定已完成):

bash
pip install infrai
# one-time auth (no secret needed): anonymous account + trial, writes ~/.infrai/credentials
python -c "from infrai import infra; infra.activate()"
# returning user instead: export INFRAI_API_KEY=ifr_pk_proj_...
python
from infrai import ai

tok = ai.realtime.token(ttl_seconds=300)
print("session:", tok.get("session_id"), "| expires:", tok.get("expires_at"))