API 参考xAI (Grok)
xAI (Grok)
xAI Grok API 集成 - 通过 UniterRouter 访问 Grok-2、Grok-1.5。OpenAI 兼容格式,实时知识和推理能力。
xAI (Grok) API
通过 UniterRouter 使用 OpenAI 兼容 API 格式访问 xAI 的 Grok 模型。Grok 以其实时知识和对话能力著称。
快速开始
curl https://api.uniterouter.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $UNITEROUTER_API_KEY" \
-d '{
"model": "grok-2",
"messages": [
{"role": "user", "content": "AI 领域有什么最新进展?"}
]
}'from openai import OpenAI
client = OpenAI(
base_url="https://api.uniterouter.ai/v1",
api_key="your_uniterouter_api_key",
)
response = client.chat.completions.create(
model="grok-2",
messages=[
{"role": "user", "content": "AI 领域有什么最新进展?"}
]
)
print(response.choices[0].message.content)import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uniterouter.ai/v1",
apiKey: process.env.UNITEROUTER_API_KEY,
});
const response = await client.chat.completions.create({
model: "grok-2",
messages: [
{ role: "user", content: "AI 领域有什么最新进展?" }
],
});
console.log(response.choices[0].message.content);可用模型
| 模型 | 描述 | 上下文 | 最适合 |
|---|---|---|---|
grok-2 | 最新 Grok 模型 | 128K | 通用场景、时事 |
grok-2-vision | 支持视觉的 Grok | 128K | 图像理解 |
grok-beta | Beta 功能 | 128K | 测试新功能 |
视觉支持
Grok-2-Vision 支持图像理解:
response = client.chat.completions.create(
model="grok-2-vision",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "描述这张图片"},
{
"type": "image_url",
"image_url": {"url": "https://example.com/image.jpg"}
}
]
}
]
)函数调用
Grok 支持工具使用:
tools = [
{
"type": "function",
"function": {
"name": "search_web",
"description": "搜索网络获取当前信息",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "搜索查询"}
},
"required": ["query"]
}
}
}
]
response = client.chat.completions.create(
model="grok-2",
messages=[{"role": "user", "content": "今天科技新闻有什么?"}],
tools=tools,
tool_choice="auto"
)流式传输
stream = client.chat.completions.create(
model="grok-2",
messages=[{"role": "user", "content": "给我介绍一下 SpaceX"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")功能特点
- 最新知识:访问最新信息
- 长上下文:128K token 上下文窗口
- 视觉:图像理解能力
- 函数调用:工具使用支持
- 对话式:自然的对话风格
相关文档
How is this guide?