社区集成

Microsoft Foundry

通过 Azure AI Foundry 访问 xAI 的 Frontier Reasoning 和 Agent 模型,并获得企业级安全、治理和统一计费。

本指南介绍如何在 Microsoft Foundry 上设置和使用 Grok 模型。Foundry 上的 Grok 模型提供强大的 reasoning、原生 Tool Use、通过 Microsoft Entra ID 实现的企业身份验证、Azure-native Monitoring,以及兼容 OpenAI 的 API。

用量通过 Azure Marketplace / Azure Subscription 计费。Grok 模型通过 xAI-Microsoft 合作提供,使用 Azure 管理的 endpoint,并可选择 Azure AI Content Safety Layer。请查看 Foundry Catalog 中的具体 Model Card,了解数据处理、保留和条款的最新详情。

Foundry 上的 Grok 支持官方 OpenAI Python/TypeScript SDK、azure-ai-projects、LangChain、Semantic Kernel、LlamaIndex,以及大多数兼容 OpenAI 的 Framework,并支持 Streaming、Tool Calling 和 Structured Output。

前置条件

开始前,请确保具备:

  • 有效的 Azure Subscription。

  • Azure AI Foundry 访问权限。

  • 创建或管理 Foundry Resource/Project 以及部署模型的足够权限,通常为 Contributor 或具有模型部署权限的 Custom Role。

  • 可选但推荐:安装 Azure CLI,用于 Resource Management 和身份验证测试。

  • 用于运行本指南示例的 Python 3.10+。

安装所需 Package

Bash

pip install -U openai azure-identity

可选,用于更高层的 Project Client 模式:

Bash

pip install azure-ai-projects

Provisioning

Foundry 使用 Resource 管理安全、计费和网络,并使用 Project 管理部署和协作。请先创建 Resource/Project,再在其中部署一个或多个 Grok Model Instance。

所选 Deployment Name 会成为 API 请求中传入 model 参数的值。

创建或选择 Foundry Resource 和 Project

  1. 前往 Foundry Portal。

  2. 创建新的 Foundry Resource,或选择现有 Resource。

  3. 如果 workflow 使用 Project,请在 Resource 中创建新 Project。

  4. 配置 Access Management:

    • 使用 Microsoft Entra ID 和 Role-based Access Control(RBAC)。

    • 为调用模型的 Identity 分配 Cognitive Services OpenAI User Role 或等效 Role。

    • 可选择通过 Azure Virtual Network 配置 Private Networking。

  5. 记录 Resource Name 和 Project Name,供后续使用。

生成的 Endpoint Base 如下:

Text

https://{resource-name}.services.ai.azure.com/api/projects/{project-name}/openai/v1

部署 Grok 模型

  1. 在 Foundry Portal 中前往 Resource 或 Project,然后打开 Models + endpoints

  2. 点击 + Deploy modelDeploy base model,或者直接浏览 Model Catalog 并搜索“Grok”。

  3. 在 Catalog 中浏览或搜索所需的 Grok 模型,例如 grok-4.3

  4. 查看 Model Card 中的能力、context window、Tool Calling 支持、安全评测、价格和 Deployment Option。

  5. 点击 Deploy

  6. 配置 Deployment Setting:

    • Deployment Name:选择清晰、稳定的名称,例如 grok-4.3。该名称创建后无法更改,也是 model 参数使用的值。

    • Deployment Type / SKU:对于 pay-as-you-go workload 选择 Serverless;对于可预测的高流量性能需求,选择 Provisioned Throughput Units(PTU)。

  7. 检查设置并选择 Deploy。等待 Deployment 达到 Ready / Running status。

部署完成后,可以在内置 Playground 中测试、查看生成的 code snippet;如果启用了 API Key Auth,还可以管理 Key/Endpoint,并监控用量和 metric。

身份验证

Foundry 上的 Grok 使用 Azure-native Authentication。推荐使用 Microsoft Entra ID(keyless)和 DefaultAzureCredential。根据 Resource 配置,也可能支持 Portal 中的 API Key。

所有请求都发送到 Foundry Project 兼容 OpenAI 的 endpoint:

Text

https://{resource-name}.services.ai.azure.com/api/projects/{project-name}/openai/v1

使用 azure.identityget_bearer_token_provider。这可以无缝启用 RBAC 和 Managed Identity,并避免 Secret Management。

Python (OpenAI)

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-version query parameter;/openai/v1 path 会处理兼容性。

替代方案:API Key 身份验证

如果 Foundry Resource 在 Keys and Endpoint 中提供 Key,请复制 Primary 或 Secondary Key,并直接将其用作 api_key

Python (OpenAI)

client = OpenAI(
    base_url=base_url,
    api_key="your-foundry-api-key-here",
)

Production 环境应优先使用 Entra ID + RBAC。绝不要将 Key 提交到 Source Control,并定期轮换 Key。

发起首次 API 调用

简单 Reasoning 调用

Python (OpenAI)

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 的一种模式:

Python (OpenAI)

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 继续对话。

Streaming Response

Python (OpenAI)

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)

先在 Foundry Portal 的 Playground 中快速迭代 prompt,再转到代码。

Correlation ID 与调试

Foundry 会在 Response Header 中包含标准 Azure Request Identifier,例如 request-idapim-request-idx-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支持低延迟用户体验。
Long Context请查看具体 Model Card 了解当前 context window。
Code Generation在代码生成和编辑任务中表现出色。

安全与 Responsible AI

Grok 模型包含 xAI 的安全训练和 Alignment。在 Foundry 上可以使用 Azure AI Content Safety,它通常默认启用或可以轻松集成。

Production 部署前:

  • 查看 Foundry 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 支持和精确参数可用性。

  • Rate Limit 和 quota 在 Azure Resource Level 管理。

有关受支持参数和行为的权威列表,请查看 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 UnauthorizedEntra 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。

后续步骤

  • 使用 Foundry Project 中的 Playground。

  • 将 Grok 与 Azure AI Agent Service 或 LangChain、Semantic Kernel、CrewAI 等常用 Framework 结合。

  • 为 Production System 添加 Retrieval、Memory 和 Orchestration Layer。

  • 使用 Foundry Tracing 和内部 Eval Harness 评估并改进行为。

  • 从直接调用 xAI API 迁移时,请更新身份验证和 endpoint 配置。大多数 prompt 和 Tool Schema 只需少量更改即可迁移。


最后更新:2026 年 6 月 26 日