社区集成
微软工坊
通过 Azure AI Foundry 访问 xAI 的前沿推理和 agent 模型,并获得企业级安全、治理和统一计费。
本指南介绍如何在 Microsoft Foundry 上设置和使用 Grok 模型。Foundry 上的 Grok 模型提供强大的推理能力、原生 tool 使用、通过 Microsoft Entra ID 实现的企业身份验证、Azure 原生监控,以及兼容 OpenAI 的 API。
用量通过 Azure Marketplace / Azure 订阅计费。Grok 模型通过 xAI 与 Microsoft 的合作提供,使用 Azure 管理的 endpoint,并可选择 Azure AI Content Safety 层。请查看 Foundry 目录中的具体模型卡,了解数据处理、保留和条款的最新详情。
微软工坊上的 Grok 支持官方 OpenAI Python/TypeScript SDK、azure-ai-projects、LangChain、Semantic Kernel、LlamaIndex 以及大多数兼容 OpenAI 的框架,并支持流式传输、tool calling 和结构化输出。
前置条件
开始前,请确保具备:
有效的 Azure 订阅。
Azure AI Foundry 访问权限。
拥有创建或管理 Foundry 资源/项目及部署模型所需的足够权限,通常为 Contributor 或具有模型部署权限的自定义 role。
可选但推荐:安装 Azure CLI,用于资源管理和身份验证测试。
用于运行本指南示例的 Python 3.10+。
安装所需软件包
pip install -U openai azure-identity可选,用于更高层的项目客户端模式:
pip install azure-ai-projects预配
Foundry 使用资源管理安全、计费和网络,使用项目管理部署和协作。请先创建资源/项目,再在其中部署一个或多个 Grok 模型实例。
所选部署名称会成为 API 请求中传入 model 参数的值。
创建或选择 Foundry 资源和项目
前往 Foundry 门户。
创建新的 Foundry 资源,或选择现有资源。
如果 workflow 使用项目,请在资源中创建新项目。
配置访问管理:
使用 Microsoft Entra ID 和基于 role 的访问控制(RBAC)。
为调用模型的身份分配 Cognitive Services OpenAI User role 或等效 role。
可选择通过 Azure Virtual Network 配置专用网络。
记录资源名称和项目名称,供后续使用。
生成的 endpoint base 如下:
https://{resource-name}.services.ai.azure.com/api/projects/{project-name}/openai/v1部署 Grok 模型
在 Foundry 门户中前往资源或项目,然后打开 Models + endpoints。
点击 + Deploy model → Deploy base model,或者直接浏览模型目录并搜索“Grok”。
在目录中浏览或搜索所需的 Grok 模型,例如
grok-4.3。查看模型卡中的能力、上下文窗口、tool calling 支持、安全评测、价格和部署选项。
点击 Deploy。
配置部署设置:
部署名称:选择清晰、稳定的名称,例如
grok-4.3。该名称创建后无法更改,也是model参数使用的值。部署类型 / SKU:对于按需付费工作负载选择 Serverless;对于可预测的高容量性能需求,选择 Provisioned Throughput Units(PTU)。
检查设置并选择 Deploy。等待部署达到 Ready / Running 状态。
部署完成后,可以在内置 Playground 中测试、查看生成的代码片段;如果启用了 API 密钥身份验证,还可以管理密钥/endpoint,并监控用量和指标。
身份验证
微软工坊上的 Grok 使用 Azure 原生身份验证。推荐使用 Microsoft Entra ID(keyless)和 DefaultAzureCredential。根据 Resource 配置,也可能支持 Portal 中的 API Key。
所有请求都发送到微软工坊 Project 兼容 OpenAI 的 endpoint:
https://{resource-name}.services.ai.azure.com/api/projects/{project-name}/openai/v1推荐:Entra ID 身份验证
使用 azure.identity 和 get_bearer_token_provider。这可以无缝启用 RBAC 和 Managed Identity,并避免 Secret Management。
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
project_endpoint = "https://YOUR-RESOURCE-NAME.services.ai.azure.com/api/projects/YOUR_PROJECT_NAME"
base_url = project_endpoint.rstrip("/") + "/openai/v1"
credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(
credential,
"https://ai.azure.com/.default",
)
client = OpenAI(
base_url=base_url,
api_key=token_provider,
)
response = client.responses.create(
model="grok-4.3", # your deployment name
input="Explain the significance of Grok's tool-calling capabilities for building reliable agents. Be concise but insightful.",
max_output_tokens=800,
)
print(response.output_text)重要:
为运行此代码的 Identity 分配 Cognitive Services OpenAI User 或其他适当 Role。
DefaultAzureCredential通过 Azure CLI / VS Code、Managed Identity、Service Principal 和其他受支持流程处理本地开发身份验证。无需
api-versionquery parameter;/openai/v1path 会处理兼容性。
替代方案:API Key 身份验证
如果微软工坊 Resource 在 Keys and Endpoint 中提供 Key,请复制 Primary 或 Secondary Key,并直接将其用作 api_key:
client = OpenAI(
base_url=base_url,
api_key="your-foundry-api-key-here",
)Production 环境应优先使用 Entra ID + RBAC。绝不要将 Key 提交到 Source Control,并定期轮换 Key。
发起首次 API 调用
简单 Reasoning 调用
response = client.responses.create(
model="grok-4.3",
input="Walk through the first-principles reasoning to determine why reusable rockets dramatically reduce the cost of space access.",
max_output_tokens=1500,
)
print(response.output_text)Tool Calling 示例
Grok 擅长 Tool Use。下面是 Parallel Tool Calling 的一种模式:
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country, e.g., San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web for recent information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
},
"required": ["query"],
},
},
},
]
response = client.responses.create(
model="grok-4.3",
input="What's the weather like in Palo Alto right now and any major tech news from today?",
tools=tools,
# parallel_tool_calls=True, # enable if supported in your deployment
max_output_tokens=1000,
)
print(response)在真实 Agent Loop 中,请执行 Tool Call,并使用 Tool Result 继续对话。
流式响应
stream = client.responses.create(
model="grok-4.3",
input="Write a short, helpful onboarding guide for a new engineer joining xAI.",
max_output_tokens=600,
stream=True,
)
for chunk in stream:
if hasattr(chunk, "choices") and chunk.choices:
delta = chunk.choices[0].delta
if hasattr(delta, "content") and delta.content:
print(delta.content, end="", flush=True)先在微软工坊 Portal 的 Playground 中快速迭代 prompt,再转到代码。
Correlation ID 与调试
微软工坊会在 Response Header 中包含标准 Azure Request Identifier,例如 request-id、apim-request-id 和 x-ms-request-id。联系 Microsoft 或 xAI Support 时,请提供这些 ID、Deployment Name 和大致 timestamp。
功能支持与能力
| 能力 | 说明 |
|---|---|
| Reasoning | 强大的 first-principles reasoning。“Think mode”风格的 prompting 效果良好。 |
| Tool / Function Calling | 原生支持可靠的 Agent Workflow。 |
| Structured Output / JSON Mode | 支持。请求 response_format,或明确要求 JSON。 |
| Streaming | 支持低延迟用户体验。 |
| 长上下文 | 请查看具体 Model Card 了解当前 context window。 |
| Code Generation | 在代码生成和编辑任务中表现出色。 |
安全与 Responsible AI
Grok 模型包含 xAI 的安全训练和 Alignment。在微软工坊上可以使用 Azure AI Content Safety,它通常默认启用或可以轻松集成。
Production 部署前:
查看微软工坊 Catalog 中完整的 Model Card 和 Safety Benchmark Tab。
使用清晰的 system prompt 定义安全边界和期望行为。
在适当位置为 input/output 实现 Azure Content Safety Filter。
开展自己的 Red Teaming 和评测。
监控用量和所有必要的 mitigation。
限制
与
api.x.ai上直接调用 xAI API 相比,Feature Parity 可能略有不同,尤其是最新实验功能。验证所选模型/Deployment 的 Vision/Multimodal 支持和精确参数可用性。
速率限制和配额在 Azure 资源级别进行管理。
有关受支持参数和行为的权威列表,请查看 Azure AI Foundry 中的 Model Card,以及 Catalog 链接的 xAI Grok 文档。
Production 最佳实践
模型选择
使用完整 Grok Reasoning Model,获得最大 reasoning 深度和能力。
对于较简单的任务,使用均衡的 reasoning 设置。
选择符合延迟、throughput 和成本要求的 Deployment Setting。
有效 Prompting Grok
需要时鼓励 step-by-step reasoning。
明确所需 Output Format。
使用清晰的 Tool Schema。
成本管理
在 Azure Cost Management + Billing 中监控支出。
对于突发或实验性 workload 使用 Serverless;对于稳定的高 throughput 使用 PTU。
根据预期 Traffic Pattern 合理选择模型和 Deployment Type。
安全与合规
优先使用 Entra ID + RBAC,而不是长期有效的 Key。
按需使用 Private Endpoint / VNet Injection。
记录包含 Correlation ID 的请求,确保可审计性。
Observability
集成 Azure Monitor、Application Insights 或 Log Analytics。
按 Deployment 追踪 token 用量、延迟和 error rate。
故障排查
| 问题 | 检查项 |
|---|---|
| 401 Unauthorized | Entra Role 缺失或错误;Token Scope 错误;检查 DefaultAzureCredential chain。 |
| 404 Not Found / 找不到模型 | Deployment Name 错误;必须与 Portal 中创建的名称完全匹配。 |
| Deployment 卡在“Running” | 检查 Region quota、Resource Health、Portal Notification,或尝试重新部署。 |
| 响应缓慢或延迟高 | 考虑使用 Provisioned Throughput,并检查到 Azure Region 的 Network Path。 |
| Tool Call 未按预期执行 | 验证 Tool Schema,并确认 Deployment 是否启用/支持 Parallel Tool Calling。 |
| 内容被过滤/阻止 | 检查 Azure Content Safety 配置和 system prompt,并按需调整 Safety Threshold。 |
后续步骤
使用微软工坊 Project 中的 Playground。
将 Grok 与 Azure AI Agent Service 或 LangChain、Semantic Kernel、CrewAI 等常用 Framework 结合。
为 Production System 添加 Retrieval、Memory 和 Orchestration Layer。
使用微软工坊 Tracing 和内部 Eval Harness 评估并改进行为。
从直接调用 xAI API 迁移时,请更新身份验证和 endpoint 配置。大多数 prompt 和 Tool Schema 只需少量更改即可迁移。
最后更新:2026 年 6 月 26 日