azure-cosmos-py
Azure Cosmos DB SDK for Python (NoSQL API). Use for document CRUD, queries, containers, and globally distributed data. Triggers: "cosmos db", "CosmosClient", "container", "document", "NoSQL", "partition key".
- License 许可
- MIT
- 所属仓库
- microsoft/skills
- 最近更新
- 2026-11-13
- Stars
- ★ 3.2k
- Forks
- 366
01 前言 Front Matter
- name
- azure-cosmos-py
- license
- MIT
- metadata
- { "author": "Microsoft", "package": "azure-cosmos", "version": "1.0.0" }
- description
- Azure Cosmos DB SDK for Python (NoSQL API). Use for document CRUD, queries, containers, and globally distributed data. Triggers: "cosmos db", "CosmosClient", "container", "document", "NoSQL", "partition key".
02 资源文件 120
- 参考文档copilot-studio/agent.sync.yaml174 B
- 参考文档copilot-studio/behaviors/aibast_adjudication-review.mcs.yml1.3 KB
- 参考文档copilot-studio/behaviors/aibast_auto-adjudication.mcs.yml1.1 KB
- 参考文档copilot-studio/behaviors/aibast_claim-intake.mcs.yml1.3 KB
- 参考文档copilot-studio/behaviors/aibast_fraud-flag.mcs.yml1.2 KB
- 参考文档copilot-studio/behaviors/aibast_processing-metrics.mcs.yml1.1 KB
- 参考文档copilot-studio/behaviors/aibast_session-summary.mcs.yml1.1 KB
- 参考文档copilot-studio/behaviors/aibast_settlement-recommendation.mcs.yml1.4 KB
- 参考文档copilot-studio/capabilities/knowledge/files/aibast_claims-processing-controls-and-review.md43.3 KB
- 参考文档copilot-studio/capabilities/knowledge/files/aibast_claims-processing-controls-and-review.md.mcs.yml198 B
- 参考文档copilot-studio/capabilities/knowledge/files/aibast_claims-processing-synthetic-records.md29.5 KB
- 参考文档copilot-studio/capabilities/knowledge/files/aibast_claims-processing-synthetic-records.md.mcs.yml194 B
- 参考文档copilot-studio/settings.mcs.yml4.7 KB
- 参考文档deployment.json3.5 KB
- 参考文档EASY-MODE-COPILOT-CHAT.md225 B
- 参考文档EASY-MODE-PERSONLESS.md225 B
- 参考文档EASY-MODE.md2.6 KB
- 参考文档evals/copilot-studio-preview-evidence.json2.6 KB
- 参考文档evals/dataverse-draft-evidence.json1.6 KB
- 参考文档evals/manual-build-evidence.json4.3 KB
- 参考文档evals/onepager-map.json2.8 KB
- 参考文档evals/source-audit.json2.4 KB
- 参考文档evals/transcripts.json19.9 KB
- 参考文档evals/visual-checkpoints.json31.2 KB
- 参考文档evidence-report.html32.2 KB
- 参考文档export-manifest.json58.3 KB
- 资产文件exports/claims-processing-copilot-studio-solution.zip32.0 KB
- 参考文档exports/claims-processing-deployment-settings.json205 B
- 参考文档exports/claims-processing-solution-export.json1.1 KB
- 参考文档exports/README.md1.5 KB
- 参考文档field-guide.html38.6 KB
- 参考文档FIELD-GUIDE.md14.3 KB
- 参考文档FLOW.md1.1 KB
- 参考文档manual-tutorial.html97.1 KB
- 参考文档manual/GLOBAL-INSTRUCTIONS.md3.6 KB
- 参考文档manual/knowledge/aibast_claims-processing-controls-and-review.md43.3 KB
- 参考文档manual/knowledge/aibast_claims-processing-synthetic-records.md29.5 KB
- 参考文档quest.html153.0 KB
- 参考文档README.md3.5 KB
- 参考文档references/partitioning.md10.3 KB
- 参考文档references/query-patterns.md10.6 KB
- 资产文件screenshots/assisted/01-review-build.jpg106.0 KB
- 资产文件screenshots/assisted/02-clp-01.jpg246.2 KB
- 资产文件screenshots/assisted/03-clp-02.jpg125.0 KB
- 资产文件screenshots/assisted/04-clp-03.jpg180.1 KB
- 资产文件screenshots/assisted/05-clp-04.jpg178.5 KB
- 资产文件screenshots/assisted/06-clp-05.jpg155.8 KB
- 资产文件screenshots/assisted/07-clp-06.jpg136.9 KB
- 资产文件screenshots/assisted/08-clp-07.jpg228.8 KB
- 资产文件screenshots/assisted/09-confirm-draft.jpg27.8 KB
- 资产文件screenshots/assisted/annotated/01-review-build.png111.0 KB
- 资产文件screenshots/assisted/annotated/02-clp-01.png238.2 KB
- 资产文件screenshots/assisted/annotated/03-clp-02.png122.2 KB
- 资产文件screenshots/assisted/annotated/04-clp-03.png171.8 KB
- 资产文件screenshots/assisted/annotated/05-clp-04.png177.8 KB
- 资产文件screenshots/assisted/annotated/06-clp-05.png150.8 KB
- 资产文件screenshots/assisted/annotated/07-clp-06.png135.6 KB
- 资产文件screenshots/assisted/annotated/08-clp-07.png223.3 KB
- 资产文件screenshots/assisted/annotated/09-confirm-draft.png27.9 KB
- 参考文档screenshots/assisted/browserfilm.json1.8 KB
- 资产文件screenshots/assisted/copilot-assisted-contact-sheet.jpg228.7 KB
- 资产文件screenshots/assisted/copilot-assisted-walkthrough.gif1.3 MB
- 参考文档screenshots/assisted/README.md467 B
- 资产文件screenshots/manual/01-create-blank-agent.jpg57.7 KB
- 资产文件screenshots/manual/02-name-agent.jpg59.0 KB
- 资产文件screenshots/manual/03-enter-instructions.jpg133.5 KB
- 资产文件screenshots/manual/04-save-instructions.jpg127.9 KB
- 资产文件screenshots/manual/05-remove-web-search.jpg133.2 KB
- 资产文件screenshots/manual/06-add-aibast-claims-processing-controls-and-review.jpg135.3 KB
- 资产文件screenshots/manual/07-add-aibast-claims-processing-synthetic-records.jpg138.0 KB
- 资产文件screenshots/manual/08-add-aibast-adjudication-review-02.jpg141.4 KB
- 资产文件screenshots/manual/09-add-aibast-auto-adjudication-05.jpg142.9 KB
- 资产文件screenshots/manual/10-add-aibast-claim-intake-01.jpg144.1 KB
- 资产文件screenshots/manual/11-add-aibast-fraud-flag-03.jpg145.1 KB
- 资产文件screenshots/manual/12-add-aibast-processing-metrics-06.jpg146.6 KB
- 资产文件screenshots/manual/13-add-aibast-session-summary-07.jpg146.9 KB
- 资产文件screenshots/manual/14-add-aibast-settlement-recommendation-04.jpg147.4 KB
- 资产文件screenshots/manual/15-review-inventory.jpg147.4 KB
- 资产文件screenshots/manual/16-review-skills.jpg137.8 KB
- 资产文件screenshots/manual/17-review-skills-more.jpg139.2 KB
- 资产文件screenshots/manual/18-open-preview.jpg31.9 KB
- 资产文件screenshots/manual/19-clp-01.jpg183.0 KB
- 资产文件screenshots/manual/20-clp-02.jpg141.0 KB
- 资产文件screenshots/manual/21-clp-03.jpg224.3 KB
- 资产文件screenshots/manual/22-clp-04.jpg146.6 KB
- 资产文件screenshots/manual/23-clp-05.jpg158.4 KB
- 资产文件screenshots/manual/24-clp-06.jpg126.9 KB
- 资产文件screenshots/manual/25-clp-07.jpg210.3 KB
- 资产文件screenshots/manual/26-confirm-draft.jpg28.5 KB
- 资产文件screenshots/manual/annotated/01-create-blank-agent.png62.7 KB
- 资产文件screenshots/manual/annotated/02-name-agent.png63.2 KB
- 资产文件screenshots/manual/annotated/03-enter-instructions.png131.2 KB
- 资产文件screenshots/manual/annotated/04-save-instructions.png126.5 KB
- 资产文件screenshots/manual/annotated/05-remove-web-search.png130.6 KB
- 资产文件screenshots/manual/annotated/06-add-aibast-claims-processing-controls-and-review.png134.0 KB
- 资产文件screenshots/manual/annotated/07-add-aibast-claims-processing-synthetic-records.png136.0 KB
- 资产文件screenshots/manual/annotated/08-add-aibast-adjudication-review-02.png137.9 KB
- 资产文件screenshots/manual/annotated/09-add-aibast-auto-adjudication-05.png139.1 KB
- 资产文件screenshots/manual/annotated/10-add-aibast-claim-intake-01.png139.8 KB
- 资产文件screenshots/manual/annotated/11-add-aibast-fraud-flag-03.png140.4 KB
- 资产文件screenshots/manual/annotated/12-add-aibast-processing-metrics-06.png142.5 KB
- 资产文件screenshots/manual/annotated/13-add-aibast-session-summary-07.png142.6 KB
- 资产文件screenshots/manual/annotated/14-add-aibast-settlement-recommendation-04.png143.4 KB
- 资产文件screenshots/manual/annotated/15-review-inventory.png147.4 KB
- 资产文件screenshots/manual/annotated/16-review-skills.png147.3 KB
- 资产文件screenshots/manual/annotated/17-review-skills-more.png151.5 KB
- 资产文件screenshots/manual/annotated/18-open-preview.png31.5 KB
- 资产文件screenshots/manual/annotated/19-clp-01.png185.8 KB
- 资产文件screenshots/manual/annotated/20-clp-02.png147.6 KB
- 资产文件screenshots/manual/annotated/21-clp-03.png218.9 KB
- 资产文件screenshots/manual/annotated/22-clp-04.png149.3 KB
- 资产文件screenshots/manual/annotated/23-clp-05.png160.2 KB
- 资产文件screenshots/manual/annotated/24-clp-06.png129.3 KB
- 资产文件screenshots/manual/annotated/25-clp-07.png213.6 KB
- 资产文件screenshots/manual/annotated/26-confirm-draft.png29.1 KB
- 参考文档screenshots/manual/browserfilm.json4.5 KB
- 资产文件screenshots/manual/manual-build-contact-sheet.jpg913.9 KB
- 资产文件screenshots/manual/manual-build-walkthrough.gif6.0 MB
- 参考文档screenshots/manual/README.md461 B
- 参考文档screenshots/README.md521 B
03 SKILL.md 正文
Azure Cosmos DB SDK for Python
Client library for Azure Cosmos DB NoSQL API — globally distributed, multi-model database.
Installation
pip install azure-cosmos azure-identity
Environment Variables
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/ # Required for all auth methods
COSMOS_DATABASE=mydb # Required for all auth methods
COSMOS_CONTAINER=mycontainer # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
Authentication & Lifecycle
? Two rules apply to every code sample below:
- Prefer
DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
- Local dev:
DefaultAzureCredentialworks as-is.- Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.- Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
- Sync:
with <Client>(...) as client:- Async:
async with <Client>(...) as client:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.cosmos import CosmosClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
endpoint = "https://<account>.documents.azure.com:443/"
with CosmosClient(url=endpoint, credential=credential) as client:
# Use client here (see following sections for operations)
...
Client Hierarchy
| Client | Purpose | Get From |
|---|---|---|
CosmosClient |
Account-level operations | Direct instantiation |
DatabaseProxy |
Database operations | client.get_database_client() |
ContainerProxy |
Container/item operations | database.get_container_client() |
Core Workflow
Setup Database and Container
# Get or create database
database = client.create_database_if_not_exists(id="mydb")
# Get or create container with partition key
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/category")
)
# Get existing
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
Create Item
item = {
"id": "item-001", # Required: unique within partition
"category": "electronics", # Partition key value
"name": "Laptop",
"price": 999.99,
"tags": ["computer", "portable"]
}
created = container.create_item(body=item)
print(f"Created: {created['id']}")
Read Item
# Read requires id AND partition key
item = container.read_item(
item="item-001",
partition_key="electronics"
)
print(f"Name: {item['name']}")
Update Item (Replace)
item = container.read_item(item="item-001", partition_key="electronics")
item["price"] = 899.99
item["on_sale"] = True
updated = container.replace_item(item=item["id"], body=item)
Upsert Item
# Create if not exists, replace if exists
item = {
"id": "item-002",
"category": "electronics",
"name": "Tablet",
"price": 499.99
}
result = container.upsert_item(body=item)
Delete Item
container.delete_item(
item="item-001",
partition_key="electronics"
)
Queries
Basic Query
# Query within a partition (efficient)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
partition_key="electronics"
)
for item in items:
print(f"{item['name']}: ${item['price']}")
Cross-Partition Query
# Cross-partition (more expensive, use sparingly)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
enable_cross_partition_query=True
)
for item in items:
print(item)
Query with Projection
query = "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category"
items = container.query_items(
query=query,
parameters=[{"name": "@category", "value": "electronics"}],
partition_key="electronics"
)
Read All Items
# Read all in a partition
items = container.read_all_items() # Cross-partition
# Or with partition key
items = container.query_items(
query="SELECT * FROM c",
partition_key="electronics"
)
Partition Keys
Critical: Always include partition key for efficient operations.
from azure.cosmos import PartitionKey
# Single partition key
container = database.create_container_if_not_exists(
id="orders",
partition_key=PartitionKey(path="/customer_id")
)
# Hierarchical partition key (preview)
container = database.create_container_if_not_exists(
id="events",
partition_key=PartitionKey(path=["/tenant_id", "/user_id"])
)
Throughput
# Create container with provisioned throughput
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/pk"),
offer_throughput=400 # RU/s
)
# Read current throughput
offer = container.read_offer()
print(f"Throughput: {offer.offer_throughput} RU/s")
# Update throughput
container.replace_throughput(throughput=1000)
Async Client
from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential
async def cosmos_operations():
async with DefaultAzureCredential() as credential:
async with CosmosClient(endpoint, credential=credential) as client:
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
# Create
await container.create_item(body={"id": "1", "pk": "test"})
# Read
item = await container.read_item(item="1", partition_key="test")
# Query
async for item in container.query_items(
query="SELECT * FROM c",
partition_key="test"
):
print(item)
import asyncio
asyncio.run(cosmos_operations())
Error Handling
from azure.cosmos.exceptions import CosmosHttpResponseError
try:
item = container.read_item(item="nonexistent", partition_key="pk")
except CosmosHttpResponseError as e:
if e.status_code == 404:
print("Item not found")
elif e.status_code == 429:
print(f"Rate limited. Retry after: {e.headers.get('x-ms-retry-after-ms')}ms")
else:
raise
Best Practices
- Pick sync OR async and stay consistent. Do not mix
azure.cosmossync clients withazure.cosmos.aioasync clients in the same call path. Choose one mode per module. - Always use context managers for clients and async credentials. Wrap every client in
with CosmosClient(...) as client:(sync) orasync with CosmosClient(...) as client:(async). For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up. - Use
DefaultAzureCredentialfor portable auth across local dev and Azure (avoid connection strings / API keys when possible). - Always specify partition key for point reads and queries
- Use parameterized queries to prevent injection and improve caching
- Avoid cross-partition queries when possible
- Use
upsert_itemfor idempotent writes - Use async client for high-throughput scenarios
- Design partition key for even data distribution
- Use
read_iteminstead of query for single document retrieval
Reference Files
| File | Contents |
|---|---|
| references/partitioning.md | Partition key strategies, hierarchical keys, hot partition detection and mitigation |
| references/query-patterns.md | Query optimization, aggregations, pagination, transactions, change feed |
| scripts/setup_cosmos_container.py | CLI tool for creating containers with partitioning, throughput, and indexing |
04 同仓库更多 Skills
skill-creator
Guide for creating effective skills for AI coding agents working with Azure SDKs and Microsoft Foundry services. Use when creating new skills or updating existing skills.
podcast-generation
Generate AI-powered podcast-style audio narratives using Azure OpenAI's GPT Realtime Mini model via WebSocket. Use when building text-to-speech features, audio narrative generation, podcast creation from content, or integrating with Azure OpenAI Realtime API for real audio output. Covers full-stack implementation from React frontend to Python FastAPI backend with WebSocket streaming.
microsoft-docs
Understand Microsoft technologies by querying official documentation. Use whenever the user asks how something works, wants tutorials, needs configuration options, limits, quotas, or best practices for any Microsoft technology (Azure, .NET, M365, Windows, Power Platform, etc.)—even if they don't mention "docs." If the question is about understanding a concept rather than writing code, this is the right skill.
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP), Node/TypeScript (MCP SDK), or C#/.NET (Microsoft MCP SDK).
kql
KQL language expertise for writing correct, efficient Kusto Query Language queries. Covers syntax gotchas, join patterns, dynamic types, datetime pitfalls, regex patterns, serialization, memory management, result-size discipline, and advanced functions (geo, vector, graph). USE THIS SKILL whenever writing, debugging, or reviewing KQL queries — even simple ones — because the gotchas section prevents the most common errors that waste tool calls and cause expensive retry cascades. Trigger on: KQL, Kusto, ADX, Azure Data Explorer, Fabric Real-Time Intelligence, EventHouse, Log Analytics, log analysis, data exploration, time series, anomaly detection, summarize, where clause, join, extend, project, let statement, parse operator, extract function, any mention of pipe-forward query syntax.
github-issue-creator
Convert raw notes, error logs, voice dictation, or screenshots into crisp GitHub-flavored markdown issue reports. Use when the user pastes bug info, error messages, or informal descriptions and wants a structured GitHub issue. Supports images/GIFs for visual evidence.