azure-ai-projects-py

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Azure AI Projects Python SDK (Foundry SDK)

Azure AI Projects Python SDK (Foundry SDK)

Build AI applications on Azure AI Foundry using the
azure-ai-projects
SDK.
使用
azure-ai-projects
SDK在Azure AI Foundry上构建AI应用程序。

Installation

安装

bash
pip install azure-ai-projects azure-identity
bash
pip install azure-ai-projects azure-identity

Environment Variables

环境变量

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

Authentication

身份验证

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,
)
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 Operations Overview

客户端操作概览

OperationAccessPurpose
client.agents
.agents.*
Agent CRUD, versions, threads, runs
client.connections
.connections.*
List/get project connections
client.deployments
.deployments.*
List model deployments
client.datasets
.datasets.*
Dataset management
client.indexes
.indexes.*
Index management
client.evaluations
.evaluations.*
Run evaluations
client.red_teams
.red_teams.*
Red team operations
操作访问方式用途
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.*
红队操作

Two Client Approaches

两种客户端使用方式

1. AIProjectClient (Native Foundry)

1. AIProjectClient(原生Foundry客户端)

python
from azure.ai.projects import AIProjectClient

client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential(),
)
python
from azure.ai.projects import AIProjectClient

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

Use Foundry-native operations

Use Foundry-native operations

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

2. OpenAI-Compatible Client

2. 兼容OpenAI的客户端

python
undefined
python
undefined

Get OpenAI-compatible client from project

Get OpenAI-compatible client from project

openai_client = client.get_openai_client()
openai_client = client.get_openai_client()

Use standard OpenAI API

Use standard OpenAI API

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

Agent Operations

Agent操作

Create Agent (Basic)

创建基础Agent

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

Create Agent with Tools

创建带工具的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()],
)
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()],
)

Versioned Agents with PromptAgentDefinition

通过PromptAgentDefinition创建带版本的Agent

python
from azure.ai.projects.models import PromptAgentDefinition
python
from azure.ai.projects.models import PromptAgentDefinition

Create a versioned agent

Create a versioned 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=[], # Add tools as needed ), version_label="v1.0", )

See [references/agents.md](references/agents.md) for detailed agent patterns.
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=[], # Add tools as needed ), version_label="v1.0", )

查看[references/agents.md](references/agents.md)获取详细的Agent使用模式。

Tools Overview

工具概览

ToolClassUse Case
Code Interpreter
CodeInterpreterTool
Execute Python, generate files
File Search
FileSearchTool
RAG over uploaded documents
Bing Grounding
BingGroundingTool
Web search (requires connection)
Azure AI Search
AzureAISearchTool
Search your indexes
Function Calling
FunctionTool
Call your Python functions
OpenAPI
OpenApiTool
Call REST APIs
MCP
McpTool
Model Context Protocol servers
Memory Search
MemorySearchTool
Search agent memory stores
SharePoint
SharepointGroundingTool
Search SharePoint content
See references/tools.md for all tool patterns.
工具使用场景
代码解释器
CodeInterpreterTool
执行Python代码、生成文件
文件搜索
FileSearchTool
对上传文档进行RAG检索
Bing grounding
BingGroundingTool
网页搜索(需要配置连接)
Azure AI搜索
AzureAISearchTool
搜索自定义索引
函数调用
FunctionTool
调用自定义Python函数
OpenAPI
OpenApiTool
调用REST API
MCP
McpTool
调用模型上下文协议服务器
内存搜索
MemorySearchTool
搜索Agent内存存储
SharePoint
SharepointGroundingTool
搜索SharePoint内容
查看references/tools.md获取所有工具的使用模式。

Thread and Message Flow

线程与消息流

python
undefined
python
undefined

1. Create thread

1. Create thread

thread = client.agents.threads.create()
thread = client.agents.threads.create()

2. Add message

2. Add message

client.agents.messages.create( thread_id=thread.id, role="user", content="What's the weather like?", )
client.agents.messages.create( thread_id=thread.id, role="user", content="What's the weather like?", )

3. Create and process run

3. Create and process run

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

4. Get response

4. Get response

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)
undefined
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)
undefined

Connections

连接管理

python
undefined
python
undefined

List all connections

List all connections

connections = client.connections.list() for conn in connections: print(f"{conn.name}: {conn.connection_type}")
connections = client.connections.list() for conn in connections: print(f"{conn.name}: {conn.connection_type}")

Get specific connection

Get specific connection

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

See [references/connections.md](references/connections.md) for connection patterns.
connection = client.connections.get(connection_name="my-search-connection")

查看[references/connections.md](references/connections.md)获取连接管理的使用模式。

Deployments

部署管理

python
undefined
python
undefined

List available model deployments

List available model deployments

deployments = client.deployments.list() for deployment in deployments: print(f"{deployment.name}: {deployment.model}")

See [references/deployments.md](references/deployments.md) for deployment patterns.
deployments = client.deployments.list() for deployment in deployments: print(f"{deployment.name}: {deployment.model}")

查看[references/deployments.md](references/deployments.md)获取部署管理的使用模式。

Datasets and Indexes

数据集与索引

python
undefined
python
undefined

List datasets

List datasets

datasets = client.datasets.list()
datasets = client.datasets.list()

List indexes

List indexes

indexes = client.indexes.list()

See [references/datasets-indexes.md](references/datasets-indexes.md) for data operations.
indexes = client.indexes.list()

查看[references/datasets-indexes.md](references/datasets-indexes.md)获取数据操作的使用模式。

Evaluation

评估

python
undefined
python
undefined

Using OpenAI client for evals

Using OpenAI client for evals

openai_client = client.get_openai_client()
openai_client = client.get_openai_client()

Create evaluation with built-in evaluators

Create evaluation with built-in evaluators

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"}, ], )

See [references/evaluation.md](references/evaluation.md) for evaluation patterns.
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](references/evaluation.md)获取评估操作的使用模式。

Async Client

异步客户端

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(...)
    # ... async operations
See references/async-patterns.md for async patterns.
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(...)
    # ... async operations
查看references/async-patterns.md获取异步操作的使用模式。

Memory Stores

内存存储

python
undefined
python
undefined

Create memory store for agent

Create memory store for agent

memory_store = client.agents.create_memory_store( name="conversation-memory", )
memory_store = client.agents.create_memory_store( name="conversation-memory", )

Attach to agent for persistent memory

Attach to agent for persistent 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]}}, )
undefined
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]}}, )
undefined

Best Practices

最佳实践

  1. Use context managers for async client:
    async with AIProjectClient(...) as client:
  2. Clean up agents when done:
    client.agents.delete_agent(agent.id)
  3. Use
    create_and_process
    for simple runs, streaming for real-time UX
  4. Use versioned agents for production deployments
  5. Prefer connections for external service integration (AI Search, Bing, etc.)
  1. 使用上下文管理器管理异步客户端:
    async with AIProjectClient(...) as client:
  2. 清理Agent:使用完毕后调用
    client.agents.delete_agent(agent.id)
  3. 简单运行使用
    create_and_process
    实时交互使用流式传输
  4. 生产环境使用带版本的Agent
  5. 优先使用连接集成外部服务(如AI Search、Bing等)

SDK Comparison

SDK对比

Feature
azure-ai-projects
azure-ai-agents
LevelHigh-level (Foundry)Low-level (Agents)
Client
AIProjectClient
AgentsClient
Versioning
create_version()
Not available
ConnectionsYesNo
DeploymentsYesNo
Datasets/IndexesYesNo
EvaluationVia OpenAI clientNo
When to useFull Foundry integrationStandalone agent apps
特性
azure-ai-projects
azure-ai-agents
层级高层级(Foundry)低层级(Agent)
客户端
AIProjectClient
AgentsClient
版本管理
create_version()
不支持
连接管理支持不支持
部署管理支持不支持
数据集/索引管理支持不支持
评估通过OpenAI客户端支持不支持
使用场景完整Foundry集成独立Agent应用

Reference Files

参考文档

  • references/agents.md: Agent operations with PromptAgentDefinition
  • references/tools.md: All agent tools with examples
  • references/evaluation.md: Evaluation operations and built-in evaluators
  • references/connections.md: Connection operations
  • references/deployments.md: Deployment enumeration
  • references/datasets-indexes.md: Dataset and index operations
  • references/async-patterns.md: Async client usage
  • references/api-reference.md: Complete API reference for all 373 SDK exports (v2.0.0b4)
  • references/agents.md: 基于PromptAgentDefinition的Agent操作
  • references/tools.md: 所有Agent工具及示例
  • references/evaluation.md: 评估操作及内置评估器
  • references/connections.md: 连接管理操作
  • references/deployments.md: 部署枚举操作
  • references/datasets-indexes.md: 数据集与索引操作
  • references/async-patterns.md: 异步客户端使用方式
  • references/api-reference.md: 完整API参考(v2.0.0b4版本,包含373个SDK导出项)