Token导航 LogoToken导航

Agent Skill · 开发

cerebras-api(cerebras API 文档)

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

cerebras-api 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证为 MIT,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 18,332。

总安装 346周安装 14GitHub Stars 公开资料未说明下载 109核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:cerebras-api(cerebras API 文档)
来源仓库:https://github.com/diskd-ai/cerebras-api
仓库路径:skills/cerebras-api
安装命令:
npx skills add https://github.com/diskd-ai/cerebras-api --skill cerebras-api
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/diskd-ai/cerebras-api --skill cerebras-api

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

Cerebras API 提供世界最快的 AI 推理服务(2000+ tokens/s),兼容 OpenAI 接口。适用于需要高速模型推理、Python 或 TypeScript SDK 集成的开发场景。支持 Llama 3.1 8B 等生产级模型,但需注意部分模型将按计划淘汰。

安装前需确认 API 密钥来源及网络访问权限,避免在生产环境误用已弃用模型。建议从现有代码或 schema 中提取事实生成接口文档,避免虚构字段或错误码。

来源仓库内路径:skills/cerebras-api

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/diskd-ai/cerebras-api --skill cerebras-api;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

cerebras-api 怎么安装?

在终端执行 npx skills add https://github.com/diskd-ai/cerebras-api --skill cerebras-api。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

cerebras-api 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

cerebras-api 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

cerebras-api 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

cerebras-api 用的人多吗?

公开数据是累计安装 346 次,近一周安装 14 次,下载 109 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

cerebras-api 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
cerebras-api

cerebras API 文档 · 本页

346—接触敏感数据MIT通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Cerebras API

Cerebras provides the world's fastest AI inference (2,000+ tokens/s). OpenAI-compatible API with Python and TypeScript SDKs.

Quick Reference

ResourceLocation
API Base URLhttps://api.cerebras.ai/v1
Get API Keyhttps://cloud.cerebras.ai
Python SDKpip install cerebras_cloud_sdk
TypeScript SDKnpm install @cerebras/cerebras_cloud_sdk

Available Models

Deprecation Notice: qwen-3-32b and llama-3.3-70b are scheduled for deprecation on February 16, 2026.

Production Models

Fully supported for production use.

ModelModel IDParametersSpeed
Llama 3.1 8Bllama3.1-8b8B~2200 tok/s
Llama 3.3 70Bllama-3.3-70b70B~2100 tok/s
OpenAI GPT OSSgpt-oss-120b120B~3000 tok/s
Qwen 3 32Bqwen-3-32b32B~2600 tok/s

Preview Models

For evaluation only - may be discontinued with short notice.

ModelModel IDParametersSpeed
Qwen 3 235B Instructqwen-3-235b-a22b-instruct-2507235B~1400 tok/s
Z.ai GLM 4.7zai-glm-4.7355B~1000 tok/s

Migrating to GLM? See GLM 4.7 Migration Guide.

Model Selection Guide

Use CaseRecommended Model
Speed-critical (real-time chat)llama3.1-8b
Balanced (chat, coding, math)llama-3.3-70b
Hybrid reasoningqwen-3-32b
Multilingual, instruction followingqwen-3-235b-a22b-instruct-2507
Science, math, complex reasoninggpt-oss-120b
Agents, superior tool usezai-glm-4.7

Model Compression

All models are unpruned original versions. Precision varies:

ModelPrecisionWeights
llama3.1-8bFP16HuggingFace
llama-3.3-70bFP16HuggingFace
gpt-oss-120bFP16/FP8 (weights only)HuggingFace
qwen-3-32bFP16HuggingFace
qwen-3-235b-a22b-instruct-2507FP16/FP8 (weights only)HuggingFace
zai-glm-4.7FP16/FP8 (weights only)HuggingFace

Note: FP16/FP8 models use selective weight-only quantization for storage. Sensitive layers remain at full precision, with dequantization on-the-fly. Activations and KV cache remain unquantized.

Basic Usage

Python

import os
from cerebras.cloud.sdk import Cerebras

client = Cerebras(api_key=os.environ.get("CEREBRAS_API_KEY"))

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Explain quantum computing"}]
)
print(response.choices[0].message.content)

TypeScript

import Cerebras from '@cerebras/cerebras_cloud_sdk';

const client = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY });

const response = await client.chat.completions.create({
    model: 'llama-3.3-70b',
    messages: [{ role: 'user', content: 'Explain quantum computing' }]
});
console.log(response.choices[0].message.content);

Streaming

The Cerebras API supports streaming responses, allowing messages to be sent back in chunks and displayed incrementally as they are generated. Set stream=True to receive an iterable of chunks.

Python

stream = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Why is fast inference important?"}],
    stream=True
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

TypeScript

const stream = await client.chat.completions.create({
    model: 'llama-3.3-70b',
    messages: [{ role: 'user', content: 'Why is fast inference important?' }],
    stream: true
});

for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

Streaming Notes

  • Each chunk contains a delta object with incremental content
  • usage and time_info are only available in the final chunk
  • Use flush=True in Python print for real-time display: print(..., end="", flush=True)

Cancel Streaming (TypeScript)

const stream = await client.chat.completions.create({
    model: 'llama-3.3-70b',
    messages: [{ role: 'user', content: 'Long response' }],
    stream: true
});

for await (const chunk of stream) {
    if (shouldStop) {
        stream.controller.abort();
        break;
    }
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

Async Streaming (Python)

from cerebras.cloud.sdk import AsyncCerebras

client = AsyncCerebras()

async def stream_response():
    stream = await client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[{"role": "user", "content": "Tell me a joke"}],
        stream=True
    )

    async for chunk in stream:
        content = chunk.choices[0].delta.content
        if content:
            print(content, end="", flush=True)

Tool Calling

Tool calling (also known as function calling) enables models to interact with external tools, APIs, or applications to perform actions and access real-time information.

Supported models: gpt-oss-120b, qwen-3-32b, zai-glm-4.7

How It Works

  1. Define tools - Provide name, description, and parameters for each tool
  2. Send request - Include tool definitions with your API call
  3. Model decides - Model analyzes if a tool can help answer the question
  4. Execute & respond - Your code executes the tool and returns results to the model

Define Tools

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "strict": True,
            "description": "Get temperature for a given location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and country e.g. Toronto, Canada"
                    }
                },
                "required": ["location"],
                "additionalProperties": False
            }
        }
    }
]

Make API Call

response = client.chat.completions.create(
    model="zai-glm-4.7",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools
)

Handle Tool Calls

import json

choice = response.choices[0].message

if choice.tool_calls:
    # Add assistant message with tool_calls
    messages.append(choice)

    for tool_call in choice.tool_calls:
        # Execute your tool
        arguments = json.loads(tool_call.function.arguments)
        result = get_weather(arguments["location"])

        # Append tool result
        messages.append({
            "role": "tool",
            "content": json.dumps(result),
            "tool_call_id": tool_call.id
        })

    # Get final response
    final_response = client.chat.completions.create(
        model="zai-glm-4.7",
        messages=messages
    )
    print(final_response.choices[0].message.content)

Parallel Tool Calling

When a query requires multiple independent data points (e.g., comparing weather in different cities), the model can request multiple tools at once.

response = client.chat.completions.create(
    model="zai-glm-4.7",
    messages=[{"role": "user", "content": "Is Toronto warmer than Montreal?"}],
    tools=tools,
    parallel_tool_calls=True  # Default: enabled
)

# Response may contain multiple tool_calls
for tool_call in response.choices[0].message.tool_calls:
    print(f"Tool: {tool_call.function.name}, Args: {tool_call.function.arguments}")

To disable parallel calling:

response = client.chat.completions.create(
    model="zai-glm-4.7",
    messages=messages,
    tools=tools,
    parallel_tool_calls=False  # Force sequential execution
)

TypeScript Example

const tools: Cerebras.Chat.ChatCompletionTool[] = [{
    type: 'function',
    function: {
        name: 'get_weather',
        strict: true,
        description: 'Get temperature for a given location.',
        parameters: {
            type: 'object',
            properties: {
                location: { type: 'string', description: 'City name' }
            },
            required: ['location'],
            additionalProperties: false
        }
    }
}];

const response = await client.chat.completions.create({
    model: 'zai-glm-4.7',
    messages: [{ role: 'user', content: 'Weather in Paris?' }],
    tools
});

if (response.choices[0].message.tool_calls) {
    for (const toolCall of response.choices[0].message.tool_calls) {
        const args = JSON.parse(toolCall.function.arguments);
        // Execute tool and continue conversation
    }
}

Best Practices

  • Use strict: true for reliable JSON argument parsing
  • Always set additionalProperties: false in parameter schemas
  • Provide clear, descriptive tool descriptions
  • Handle cases where model doesn't call any tools

Structured Outputs

Generate structured data with enforced JSON schema compliance. Key benefits:

  • Reduced Variability - Consistent outputs adhering to predefined fields
  • Type Safety - Enforces correct data types, preventing mismatches
  • Easier Parsing - Direct use in applications without extra processing

Defining the Schema

Define a JSON schema specifying fields, types, and required properties.

For every required array, you must set additionalProperties: false.

Python (with Pydantic)

from pydantic import BaseModel

class Movie(BaseModel):
    title: str
    director: str
    year: int

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant"},
        {"role": "user", "content": "Suggest a sci-fi movie"}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "movie",
            "strict": True,
            "schema": Movie.model_json_schema()
        }
    }
)

import json
movie = json.loads(response.choices[0].message.content)

Python (with raw schema)

movie_schema = {
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "director": {"type": "string"},
        "year": {"type": "integer"}
    },
    "required": ["title", "director", "year"],
    "additionalProperties": False
}

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Suggest a sci-fi movie"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "movie",
            "strict": True,
            "schema": movie_schema
        }
    }
)

TypeScript (with Zod)

import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';

const MovieSchema = z.object({
    title: z.string(),
    director: z.string(),
    year: z.number().int()
});

const response = await client.chat.completions.create({
    model: 'llama-3.3-70b',
    messages: [{ role: 'user', content: 'Suggest a sci-fi movie' }],
    response_format: {
        type: 'json_schema',
        json_schema: {
            name: 'movie',
            strict: true,
            schema: zodToJsonSchema(MovieSchema)
        }
    }
});

const movie = MovieSchema.parse(JSON.parse(response.choices[0].message.content || '{}'));

Response Format Modes

ModeValid JSONAdheres to SchemaExtra FieldsConstrained Decoding
json_schema (strict: true)YesYes (guaranteed)NoYes
json_schema (strict: false)Yes (best-effort)YesYesNo
json_objectYesNo (flexible)NoNo

Enabling each mode:

  • Strict: response_format: {type: "json_schema", json_schema: {strict: true, schema:...}}
  • Non-strict: response_format: {type: "json_schema", json_schema: {strict: false, schema:...}}
  • JSON object: response_format: {type: "json_object"}

Schema Requirements

  • Set "additionalProperties": false for all objects with required fields
  • Max nesting: 5 levels
  • Max schema length: 5,000 chars
  • No recursive schemas
tools and response_format cannot be used in the same request.

Reasoning Models

Reasoning models generate intermediate thinking tokens before their final response, enabling better problem-solving and allowing inspection of the model's thought process.

Supported models: qwen-3-32b, gpt-oss-120b, zai-glm-4.7

Reasoning Format Options

FormatBehaviorUse Case
parsedReasoning in separate reasoning field, logprobs split into reasoning_logprobsWhen you need structured access to thinking
rawReasoning prepended to content with wrapper tokens (<think>...</think> for GLM/Qwen)When you want full visibility
hiddenReasoning text dropped from response (tokens still counted/billed)When you want benefits without exposing thinking
noneUses model's default behaviorDefault

Default behaviors by model:

  • Qwen3: raw (or hidden for JSON output)
  • GLM: text_parsed
  • GPT-OSS: text_parsed

Basic Usage

response = client.chat.completions.create(
    model="qwen-3-32b",
    messages=[{"role": "user", "content": "Solve: 15% of 240"}],
    reasoning_format="parsed"
)
print("Thinking:", response.choices[0].message.reasoning)
print("Answer:", response.choices[0].message.content)
const response = await client.chat.completions.create({
    model: 'qwen-3-32b',
    messages: [{ role: 'user', content: 'Solve: 15% of 240' }],
    reasoning_format: 'parsed'
});
console.log('Thinking:', response.choices[0].message.reasoning);
console.log('Answer:', response.choices[0].message.content);

GPT-OSS: Reasoning Effort

Control reasoning intensity with reasoning_effort:

response = client.chat.completions.create(
    model="gpt-oss-120b",
    messages=[{"role": "user", "content": "Prove the Pythagorean theorem"}],
    reasoning_effort="high"  # "low", "medium" (default), "high"
)

GLM: Disable Reasoning

Toggle reasoning on/off for GLM:

response = client.chat.completions.create(
    model="zai-glm-4.7",
    messages=[{"role": "user", "content": "Quick factual question"}],
    disable_reasoning=True  # Skip thinking for simple queries
)

Multi-Turn Reasoning Context

To retain reasoning awareness across conversation turns, include prior reasoning in assistant messages using the model's native format.

GPT-OSS (reasoning prepended directly):

messages = [
    {"role": "user", "content": "What is 25 * 4?"},
    {"role": "assistant", "content": "Multiply 25 times 4 equals 100. The answer is 100."},
    {"role": "user", "content": "Now divide that by 2."}
]
response = client.chat.completions.create(model="gpt-oss-120b", messages=messages)

GLM/Qwen (reasoning in <think> tags):

messages = [
    {"role": "user", "content": "What is 25 * 4?"},
    {"role": "assistant", "content": "<think>Multiply 25 times 4 equals 100.</think>The answer is 100."},
    {"role": "user", "content": "Now divide that by 2."}
]
response = client.chat.completions.create(model="zai-glm-4.7", messages=messages)

Predicted Outputs

Reduce latency by specifying parts of the response that are already known. (Public Preview)

Supported models: gpt-oss-120b, llama3.1-8b, zai-glm-4.7

Predicted Outputs speed up response generation when parts of the output are already known. This is most useful when regenerating text or code that requires only minor changes.

Python

code = """
html {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color: #00FF00;
}
"""

response = client.chat.completions.create(
    model="gpt-oss-120b",
    messages=[
        {"role": "user", "content": "Change the color to blue. Respond only with code."},
        {"role": "user", "content": code}
    ],
    prediction={"type": "content", "content": code}
)

TypeScript

const code = `
html {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color: #00FF00;
}
`;

const response = await client.chat.completions.create({
    model: 'gpt-oss-120b',
    messages: [
        { role: 'user', content: "Change the color to blue. Respond only with code." },
        { role: 'user', content: code }
    ],
    prediction: { type: 'content', content: code }
});

Token-Reuse Metrics

The response includes usage metrics showing prediction efficiency:

{
  "usage": {
    "completion_tokens": 224,
    "prompt_tokens": 204,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 76,
      "rejected_prediction_tokens": 20
    }
  }
}

A high ratio of accepted to rejected tokens indicates efficient prediction reuse.

Best Practices

  • Use when most output is known - The larger the known section, the greater the efficiency gain
  • Set temperature=0 - Reduces randomness and increases token acceptance
  • Keep predictions accurate - Misaligned predictions increase rejected tokens
  • Monitor metrics - Track accepted vs rejected tokens to evaluate effectiveness

Limitations

  • Rejected tokens are billed at completion-token rates
  • Not compatible with: logprobs, n > 1, tools
  • Reasoning tokens may generate additional rejected_prediction_tokens

Prompt Caching

Store and reuse previously processed prompts to reduce latency. Designed to significantly reduce Time to First Token (TTFT) for long-context workloads like multi-turn conversations, RAG, and agentic workflows.

How It Works

Automatic - No code changes required. Works on all supported API requests.

  1. Prefix Matching - System analyzes the beginning of your prompt (system prompts, tool definitions, few-shot examples)
  2. Block-Based Caching - Prompts processed in blocks (100-600 tokens). Matching blocks reuse cached computation
  3. Cache Hit - Cached blocks skip processing, resulting in lower latency
  4. Cache Miss - Prompt processed normally, prefix stored for future matches
  5. Auto Expiration - TTL guaranteed 5 minutes, may persist up to 1 hour
The entire beginning of your prompt must match *exactly* with a cached prefix. Even a single character difference causes a cache miss.

Checking Cache Usage

Check the usage.prompt_tokens_details.cached_tokens field in your response:

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=messages
)

cached = response.usage.prompt_tokens_details.cached_tokens
print(f"Cached tokens: {cached}")
{
  "usage": {
    "prompt_tokens": 1500,
    "prompt_tokens_details": {
      "cached_tokens": 1200
    }
  }
}

Best Practices for Cache Hits

  • Keep prefixes consistent - System prompts, tool definitions, and few-shot examples should be identical across requests
  • Order matters - Place stable content (system prompt, tools) before dynamic content (user messages)
  • Multi-turn conversations - Cache naturally builds as conversation history grows
  • RAG workflows - Place frequently-used context at the beginning

Example: Multi-Turn with Tools

# System message and tools are cached across turns
messages = [
    {"role": "system", "content": "You are a shopping assistant."},
    {"role": "user", "content": "Where is my order ORD-123456?"}
]

# Turn 1 - creates cache for system + tools
response = client.chat.completions.create(
    model="qwen-3-32b",
    messages=messages,
    tools=tools
)
print(f"Turn 1 cached: {response.usage.prompt_tokens_details.cached_tokens}")

# Turn 2 - reuses cached system + tools
messages.append(response.choices[0].message)
messages.append({"role": "user", "content": "Please cancel it."})

response = client.chat.completions.create(
    model="qwen-3-32b",
    messages=messages,
    tools=tools
)
print(f"Turn 2 cached: {response.usage.prompt_tokens_details.cached_tokens}")

FAQ

  • Pricing: No additional cost. Standard token rates apply
  • Quality: Caching only affects input processing. Output generation unchanged
  • Manual clear: Not available. System manages cache automatically
  • TTL: Guaranteed 5 minutes, up to 1 hour depending on load

Async Usage (Python)

import asyncio
from cerebras.cloud.sdk import AsyncCerebras

client = AsyncCerebras()

async def main():
    response = await client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())

Error Handling

All errors inherit from cerebras.cloud.sdk.APIError. Main categories:

  • APIConnectionError - Unable to connect to the API
  • APIStatusError - API returns non-success status code (4xx or 5xx)

Error Codes

StatusExceptionDescription
400BadRequestErrorInvalid request parameters
401AuthenticationErrorInvalid or missing API key
402PaymentRequiredPayment required
403PermissionDeniedErrorInsufficient permissions
404NotFoundErrorResource not found
422UnprocessableEntityErrorValidation error
429RateLimitErrorToo many requests
500InternalServerErrorServer error
503ServiceUnavailableService temporarily unavailable
N/AAPIConnectionErrorNetwork/connection issue

Python Example

import cerebras.cloud.sdk
from cerebras.cloud.sdk import Cerebras

client = Cerebras()

try:
    response = client.chat.completions.create(
        model="llama-3.3-70b",
        messages=[{"role": "user", "content": "Hello"}]
    )
except cerebras.cloud.sdk.APIConnectionError as e:
    print("Server could not be reached")
    print(e.__cause__)
except cerebras.cloud.sdk.RateLimitError as e:
    print("Rate limited - implement backoff")
except cerebras.cloud.sdk.APIStatusError as e:
    print(f"Error {e.status_code}: {e.response}")

TypeScript Example

try {
    const response = await client.chat.completions.create({
        model: 'llama-3.3-70b',
        messages: [{ role: 'user', content: 'Hello' }]
    });
} catch (err) {
    if (err instanceof Cerebras.APIError) {
        console.log(err.status);   // 400
        console.log(err.name);     // BadRequestError
        console.log(err.headers);  // Response headers
    } else {
        throw err;
    }
}

Retries & Timeouts

Automatic Retries

By default, these errors are retried 2 times with exponential backoff:

  • Connection errors
  • 408 Request Timeout
  • 429 Rate Limit
  • = 500 Internal errors
# Python - configure retries
client = Cerebras(max_retries=0)  # Disable retries

# Per-request override
client.with_options(max_retries=5).chat.completions.create(...)
// TypeScript - configure retries
const client = new Cerebras({ maxRetries: 0 });

// Per-request override
await client.chat.completions.create(params, { maxRetries: 5 });

Timeouts

Default timeout is 60 seconds. On timeout, APITimeoutError is thrown.

# Python - configure timeout
client = Cerebras(timeout=20.0)  # 20 seconds

# Granular control
import httpx
client = Cerebras(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0)
)

# Per-request override
client.with_options(timeout=5.0).chat.completions.create(...)
// TypeScript - configure timeout
const client = new Cerebras({ timeout: 20 * 1000 });

// Per-request override
await client.chat.completions.create(params, { timeout: 5 * 1000 });

TCP Warming

SDK sends warmup requests on init to reduce first-token latency. Disable if needed:

client = Cerebras(warm_tcp_connection=False)
const client = new Cerebras({ warmTCPConnection: false });

Key Parameters

ParameterDescription
modelModel identifier (required)
messagesConversation history (required)
temperatureRandomness 0-1.5 (default varies)
max_completion_tokensMax output tokens
stopUp to 4 stop sequences
streamEnable streaming
response_formattext, json_object, or json_schema
toolsFunction definitions for tool calling
reasoning_formatparsed, raw, hidden
reasoning_effortlow, medium, high (gpt-oss only)

References

For detailed SDK documentation:

平台分布

Claude Code

27%
按下载量换算29

trae

22.01%
按下载量换算24

OpenCode

17.55%
按下载量换算19

Codex

11.52%
按下载量换算13

Antigravity

7.31%
按下载量换算8

Gemini CLI

3.6%
按下载量换算4

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills