azure-ai-projects-py
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure AI Projects Python SDK (Foundry SDK)
Azure AI Projects Python SDK (Foundry SDK)
Build AI applications on Azure AI Foundry using the SDK.
azure-ai-projects使用 SDK在Azure AI Foundry上构建AI应用程序。
azure-ai-projectsInstallation
安装
bash
pip install azure-ai-projects azure-identitybash
pip install azure-ai-projects azure-identityEnvironment 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
客户端操作概览
| Operation | Access | Purpose |
|---|---|---|
| | Agent CRUD, versions, threads, runs |
| | List/get project connections |
| | List model deployments |
| | Dataset management |
| | Index management |
| | Run evaluations |
| | Red team operations |
| 操作 | 访问方式 | 用途 |
|---|---|---|
| | Agent的CRUD操作、版本管理、线程与运行 |
| | 列出/获取项目连接 |
| | 列出模型部署 |
| | 数据集管理 |
| | 索引管理 |
| | 运行评估 |
| | 红队操作 |
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.",
)
undefinedagent = client.agents.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="my-agent",
instructions="You are helpful.",
)
undefined2. OpenAI-Compatible Client
2. 兼容OpenAI的客户端
python
undefinedpython
undefinedGet 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!"}],
)
undefinedresponse = openai_client.chat.completions.create(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
messages=[{"role": "user", "content": "Hello!"}],
)
undefinedAgent 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 PromptAgentDefinitionpython
from azure.ai.projects.models import PromptAgentDefinitionCreate 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
工具概览
| Tool | Class | Use Case |
|---|---|---|
| Code Interpreter | | Execute Python, generate files |
| File Search | | RAG over uploaded documents |
| Bing Grounding | | Web search (requires connection) |
| Azure AI Search | | Search your indexes |
| Function Calling | | Call your Python functions |
| OpenAPI | | Call REST APIs |
| MCP | | Model Context Protocol servers |
| Memory Search | | Search agent memory stores |
| SharePoint | | Search SharePoint content |
See references/tools.md for all tool patterns.
| 工具 | 类 | 使用场景 |
|---|---|---|
| 代码解释器 | | 执行Python代码、生成文件 |
| 文件搜索 | | 对上传文档进行RAG检索 |
| Bing grounding | | 网页搜索(需要配置连接) |
| Azure AI搜索 | | 搜索自定义索引 |
| 函数调用 | | 调用自定义Python函数 |
| OpenAPI | | 调用REST API |
| MCP | | 调用模型上下文协议服务器 |
| 内存搜索 | | 搜索Agent内存存储 |
| SharePoint | | 搜索SharePoint内容 |
查看references/tools.md获取所有工具的使用模式。
Thread and Message Flow
线程与消息流
python
undefinedpython
undefined1. 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)
undefinedif 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)
undefinedConnections
连接管理
python
undefinedpython
undefinedList 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
undefinedpython
undefinedList 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
undefinedpython
undefinedList 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
undefinedpython
undefinedUsing 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 operationsSee 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
undefinedpython
undefinedCreate 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]}},
)
undefinedagent = 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]}},
)
undefinedBest Practices
最佳实践
- Use context managers for async client:
async with AIProjectClient(...) as client: - Clean up agents when done:
client.agents.delete_agent(agent.id) - Use for simple runs, streaming for real-time UX
create_and_process - Use versioned agents for production deployments
- Prefer connections for external service integration (AI Search, Bing, etc.)
- 使用上下文管理器管理异步客户端:
async with AIProjectClient(...) as client: - 清理Agent:使用完毕后调用
client.agents.delete_agent(agent.id) - 简单运行使用,实时交互使用流式传输
create_and_process - 生产环境使用带版本的Agent
- 优先使用连接集成外部服务(如AI Search、Bing等)
SDK Comparison
SDK对比
| Feature | | |
|---|---|---|
| Level | High-level (Foundry) | Low-level (Agents) |
| Client | | |
| Versioning | | Not available |
| Connections | Yes | No |
| Deployments | Yes | No |
| Datasets/Indexes | Yes | No |
| Evaluation | Via OpenAI client | No |
| When to use | Full Foundry integration | Standalone agent apps |
| 特性 | | |
|---|---|---|
| 层级 | 高层级(Foundry) | 低层级(Agent) |
| 客户端 | | |
| 版本管理 | | 不支持 |
| 连接管理 | 支持 | 不支持 |
| 部署管理 | 支持 | 不支持 |
| 数据集/索引管理 | 支持 | 不支持 |
| 评估 | 通过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导出项)