Azure AI 项目 Python SDK

azure-ai-projects-py
分类编程
作者Agentic Awesome Skills 社区
许可MIT
评分4.70/5
使用3.5K

Azure AI Projects Python SDK (Foundry SDK)

使用 azure-ai-projects SDK 在 Microsoft Foundry 上构建 AI 应用程序。

安装

bash
pip install azure-ai-projects azure-identity

环境变量

bash
AZURE_AI_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"
AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"

身份验证

python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

credential = DefaultAzureCredential()
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential,
)

客户端操作概览

| 操作 | 访问路径 | 用途 |
|-----------|--------|---------|
| client.agents | .agents.* | Agent 的 CRUD、版本、线程、运行 |
| client.connections | .connections.* | 列出/获取项目连接 |
| client.deployments | .deployments.* | 列出模型部署 |
| client.datasets | .datasets.* | 数据集管理 |
| client.indexes | .indexes.* | 索引管理 |
| client.evaluations | .evaluations.* | 运行评估 |
| client.red_teams | .red_teams.* | 红队操作 |

两种客户端方法

1. AIProjectClient (Foundry 原生)

python
from azure.ai.projects import AIProjectClient

client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)

使用 Foundry 原生操作

agent = client.agents.create_agent( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], name="my-agent", instructions="You are helpful.", )

2. OpenAI 兼容客户端

python
# 从项目中获取 OpenAI 兼容客户端
openai_client = client.get_openai_client()

使用标准 OpenAI API

response = openai_client.chat.completions.create( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], messages=[{"role": "user", "content": "Hello!"}], )

Agent 操作

创建 Agent (基础)

python
agent = client.agents.create_agent(
    model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
    name="my-agent",
    instructions="You are a helpful assistant.",
)

创建带有工具的 Agent

python
from azure.ai.agents import CodeInterpreterTool, FileSearchTool

agent = client.agents.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="tool-agent",
instructions="You can execute code and search files.",
tools=[CodeInterpreterTool(), FileSearchTool()],
)

使用 PromptAgentDefinition 创建版本化 Agent

python
from azure.ai.projects.models import PromptAgentDefinition

创建一个版本化 agent

agent_version = client.agents.create_version( agent_name="customer-support-agent", definition=PromptAgentDefinition( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], instructions="You are a customer support specialist.", tools=[], # 根据需要添加工具 ), version_label="v1.0", )

详细的 Agent 模式请参阅 references/agents.md。

工具概览

| 工具 | 类 | 使用场景 |
|------|-------|----------|
| 代码解释器 | CodeInterpreterTool | 执行 Python 代码,生成文件 |
| 文件搜索 | FileSearchTool | 对上传的文档进行 RAG |
| Bing Grounding | BingGr | (文本截断) |
| WebGroundingTool | 网页搜索(需要连接) |
| Azure AI Search | AzureAISearchTool | 搜索您的索引 |
| Function Calling | FunctionTool | 调用您的 Python 函数 |
| OpenAPI | OpenApiTool | 调用 REST API |
| MCP | McpTool | Model Context Protocol 服务器 |
| Memory Search | MemorySearchTool | 搜索智能体内存存储 |
| SharePoint | SharepointGroundingTool | 搜索 SharePoint 内容 |

有关所有工具模式,请参阅 references/tools.md。

线程与消息流

python
# 1. 创建线程
thread = client.agents.threads.create()

2. 添加消息

client.agents.messages.create( thread_id=thread.id, role="user", content="天气怎么样?", )

3. 创建并处理运行 (run)

run = client.agents.runs.create_and_process( thread_id=thread.id, agent_id=agent.id, )

4. 获取响应

if run.status == "completed": messages = client.agents.messages.list(thread_id=thread.id) for msg in messages: if msg.role == "assistant": print(msg.content[0].text.value)

连接 (Connections)

python
# 列出所有连接
connections = client.connections.list()
for conn in connections:
    print(f"{conn.name}: {conn.connection_type}")

获取特定连接

connection = client.connections.get(connection_name="my-search-connection")

有关连接模式,请参阅 references/connections.md。

部署 (Deployments)

python
# 列出可用的模型部署
deployments = client.deployments.list()
for deployment in deployments:
    print(f"{deployment.name}: {deployment.model}")

有关部署模式,请参阅 references/deployments.md。

数据集与索引

python
# 列出数据集
datasets = client.datasets.list()

列出索引

indexes = client.indexes.list()

有关数据操作,请参阅 references/datasets-indexes.md。

评估 (Evaluation)

python
# 使用 OpenAI 客户端进行评估
openai_client = client.get_openai_client()

使用内置评估器创建评估

eval_run = openai_client.evals.runs.create( eval_id="my-eval", name="quality-check", data_source={ "type": "custom", "item_references": [{"item_id": "test-1"}], }, testing_criteria=[ {"type": "fluency"}, {"type": "task_adherence"}, ], )

有关评估模式,请参阅 references/evaluation.md。

异步客户端

python
from azure.ai.projects.aio import AIProjectClient

async with AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
) as client:
agent = await client.agents.create_agent(...)
# ... 异步操作

有关异步模式,请参阅 references/async-patterns.md。

内存存储 (Memory Stores)

python
# 为智能体创建内存存储
memory_store = client.agents.create_memory_store(
    name="conversation-memory",
)

绑定到智能体以实现持久化内存

agent = client.agents.create_agent( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], name="memory-agent", tools=[MemorySearchTool()], tool_resources={"memory": {"store_ids": [memory_store.id]}}, )

最佳实践

1. 异步客户端请使用上下文管理器async with AIProjectClient(...) as client:
2. 完成后清理智能体client.agents.delete_agent(agent.id)
3. 简单运行使用 create_and_process,实时用户体验请使用 streaming (流式传输)
4. 生产环境部署请使用版本化智能体
5. 集成外部服务(AI Search, Bing 等)优先使用 connections

SDK 对比

| 功能 |
| azure-ai-projects | azure-ai-agents |
|---------|---------------------|-------------------|
| 层级 | 高层 (Foundry) | 低层 (Agents) |
| 客户端 | AIProjectClient | AgentsClient |
| 版本控制 | create_version() | 不可用 |
| 连接 (Connections) | 是 | 否 |
| 部署 (Deployments) | 是 | 否 |
| 数据集/索引 | 是 | 否 |
| 评估 | 通过 OpenAI 客户端 | 否 |
| 使用场景 | 全量 Foundry 集成 | 独立 Agent 应用 |

参考文件

  • references/agents.md: 使用 PromptAgentDefinition 的 Agent 操作
  • references/tools.md: 所有 Agent 工具及示例
  • references/evaluation.md: 评估操作概览
  • references/built-in-evaluators.md: 完整的内置评估器参考
  • references/custom-evaluators.md: 基于代码和提示词的评估器模式
  • references/connections.md: 连接操作
  • references/deployments.md: 部署枚举
  • references/datasets-indexes.md: 数据集和索引操作
  • references/async-patterns.md: 异步客户端用法
  • references/api-reference.md: 所有 373 个 SDK 导出项的完整 API 参考 (v2.0.0b4)
  • scripts/run_batch_evaluation.py: 批量评估的 CLI 工具

使用场景

本技能适用于执行概览中所描述的工作流或操作。

局限性

  • 仅在任务明确符合上述范围时使用此技能。
  • 不要将输出结果视为针对特定环境的验证、测试或专家评审的替代方案。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。