onenote-cost-tuning
Optimize costs and API usage for OneNote Graph API integrations with caching and batching strategies. Use when reducing API call volume, planning capacity, or evaluating OneNote integration costs. Trigger with "onenote costs", "onenote api usage", "onenote optimization", "graph api billing onenote".
What this skill does
# OneNote Cost Tuning
## Overview
OneNote Graph API calls have no per-request cost — they are included in every Microsoft 365 E3/E5/Business license. However, rate limits create an effective ceiling that functions like a cost constraint: 600 requests per user per 60 seconds and 10,000 requests per app per 10 minutes at the tenant level. Exceeding these limits returns 429 errors with Retry-After headers, degrading user experience the same way budget overruns degrade service. This skill covers the practical optimization strategies that keep you well under those ceilings: metadata caching, JSON batch requests, delta sync, payload minimization with `$select`/`$expand`, and content deduplication. A naive integration that polls every user's notebooks every minute burns through the tenant limit in under 10 minutes. An optimized one handles thousands of users within the same budget.
## Prerequisites
- Microsoft 365 license (E3/E5/Business) — OneNote API is included, no additional billing
- Azure AD app registration with delegated permissions
- Python: `pip install msgraph-sdk azure-identity` or Node: `npm install @microsoft/microsoft-graph-client @azure/identity`
- Understanding of HTTP caching headers (ETag, If-None-Match)
## Instructions
### Licensing Model and True Cost
| Component | Cost |
|-----------|------|
| OneNote API calls | Included in M365 license (no per-call charge) |
| Rate limit: per user | 600 requests / 60 seconds |
| Rate limit: per tenant | 10,000 requests / 10 minutes |
| Retry-After penalty | Blocked for N seconds (header value) |
| Graph metered billing | Optional; extends limits for high-volume apps |
**The real cost is operational:** every 429 response adds latency, retry logic consumes compute, and throttled users see failures. Optimization is about reliability, not billing.
### Strategy 1: Cache Metadata Aggressively
Notebook and section metadata changes rarely (names, IDs, hierarchy). Cache it locally and refresh on a schedule, not per-request:
```typescript
interface CachedMetadata {
notebooks: any[];
sections: Map<string, any[]>; // notebookId -> sections
fetchedAt: number;
ttlMs: number;
}
class MetadataCache {
private cache: CachedMetadata = {
notebooks: [],
sections: new Map(),
fetchedAt: 0,
ttlMs: 15 * 60 * 1000, // 15 minutes — notebooks/sections rarely change
};
isStale(): boolean {
return Date.now() - this.cache.fetchedAt > this.cache.ttlMs;
}
async getNotebooks(client: any): Promise<any[]> {
if (!this.isStale() && this.cache.notebooks.length > 0) {
return this.cache.notebooks; // 0 API calls
}
const response = await client.api("/me/onenote/notebooks")
.select("id,displayName,lastModifiedDateTime")
.get();
this.cache.notebooks = response.value;
this.cache.fetchedAt = Date.now();
return this.cache.notebooks; // 1 API call
}
async getSections(client: any, notebookId: string): Promise<any[]> {
if (!this.isStale() && this.cache.sections.has(notebookId)) {
return this.cache.sections.get(notebookId)!;
}
const response = await client
.api(`/me/onenote/notebooks/${notebookId}/sections`)
.select("id,displayName")
.get();
this.cache.sections.set(notebookId, response.value);
return response.value;
}
invalidate(): void {
this.cache.fetchedAt = 0;
}
}
```
**Savings:** A typical app listing notebooks 100 times/hour drops from 100 calls to 4 calls (one refresh per 15-minute TTL window).
### Strategy 2: JSON Batch Requests
The `$batch` endpoint combines up to 20 requests into a single HTTP call, reducing call count by up to 20x:
```python
import httpx
async def batch_get_sections(access_token: str, notebook_ids: list[str]) -> dict:
"""Fetch sections for multiple notebooks in a single HTTP call."""
requests = []
for i, nb_id in enumerate(notebook_ids[:20]): # Max 20 per batch
requests.append({
"id": str(i),
"method": "GET",
"url": f"/me/onenote/notebooks/{nb_id}/sections?$select=id,displayName",
})
async with httpx.AsyncClient() as http:
response = await http.post(
"https://graph.microsoft.com/v1.0/$batch",
headers={
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
},
json={"requests": requests},
)
batch_result = response.json()
# Map responses back to notebook IDs
result = {}
for resp in batch_result["responses"]:
idx = int(resp["id"])
nb_id = notebook_ids[idx]
if resp["status"] == 200:
result[nb_id] = resp["body"]["value"]
else:
result[nb_id] = [] # Handle individual failures gracefully
return result
```
**Savings:** Fetching sections for 20 notebooks: 20 calls becomes 1 call. For 100 notebooks, 100 calls becomes 5 calls.
### Strategy 3: Delta Sync Instead of Full Sync
Delta queries return only changes since your last sync, replacing full-list operations that grow linearly with data size:
```typescript
class DeltaSyncer {
private deltaLinks: Map<string, string> = new Map();
async syncPages(client: any, sectionId: string): Promise<{
added: any[];
modified: any[];
deleted: string[];
}> {
const deltaLink = this.deltaLinks.get(sectionId);
const url = deltaLink || `/me/onenote/sections/${sectionId}/pages/delta`;
const response = await client.api(url).get();
const result = { added: [] as any[], modified: [] as any[], deleted: [] as string[] };
for (const page of response.value || []) {
if (page["@removed"]) {
result.deleted.push(page.id);
} else if (deltaLink) {
result.modified.push(page);
} else {
result.added.push(page);
}
}
// Store the delta link for next sync
if (response["@odata.deltaLink"]) {
this.deltaLinks.set(sectionId, response["@odata.deltaLink"]);
}
return result;
}
}
```
**Savings:** A section with 500 pages that changes 3 pages/hour: full sync = 500+ items per response, delta sync = 3 items. Call count may be same (1), but payload size drops 99%.
### Strategy 4: Payload Minimization with $select and $expand
Every field you do not request is bandwidth you save and parsing you skip:
```bash
# BAD: Returns all fields including content URLs, permissions, links (2-5 KB per page)
GET /me/onenote/sections/{id}/pages
# GOOD: Returns only what you need (200-300 bytes per page)
GET /me/onenote/sections/{id}/pages?$select=id,title,createdDateTime,lastModifiedDateTime&$top=50&$orderby=lastModifiedDateTime desc
```
Use `$expand` to eliminate follow-up calls:
```text
# Without $expand: 1 call for notebooks + N calls for sections = N+1 calls
GET /me/onenote/notebooks
GET /me/onenote/notebooks/{id1}/sections
GET /me/onenote/notebooks/{id2}/sections
# With $expand: 1 call total
GET /me/onenote/notebooks?$expand=sections($select=id,displayName)&$select=id,displayName
```
### Strategy 5: Content Deduplication
Hash page content before writing to avoid duplicate POST calls:
```python
import hashlib
def content_hash(html_body: str) -> str:
"""Generate a stable hash of page content for dedup."""
return hashlib.sha256(html_body.encode("utf-8")).hexdigest()
class DeduplicatedWriter:
def __init__(self):
self.written_hashes: dict[str, str] = {} # hash -> page_id
async def write_page(self, client, section_id: str, title: str, html_body: str):
h = content_hash(html_body)
if h in self.written_hashes:
return self.written_hashes[h] # Skip duplicate write
full_html = (
f"<html><head><title>{title}</title></head>"
f"<body>{html_body}</body></html>"
)
page = await client.me.onenote.sections.by_onenote_section_id(
section_id
).pages.post(content=full_html.encode())
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.