Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions plugin/skills/microsoft-foundry/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: microsoft-foundry
description: "Deploy, evaluate, and manage Foundry agents end-to-end: Docker build, ACR push, hosted/prompt agent create, container start, batch eval, continuous eval, prompt optimizer workflows, agent.yaml, dataset curation from traces. USE FOR: deploy agent to Foundry, hosted agent, create agent, invoke agent, evaluate agent, run batch eval, continuous eval, continuous monitoring, continuous eval status, optimize prompt, improve prompt, prompt optimizer, optimize agent instructions, improve agent instructions, optimize system prompt, deploy model, Foundry project, RBAC, role assignment, permissions, quota, capacity, region, troubleshoot agent, deployment failure, create dataset from traces, dataset versioning, eval trending, create AI Services, Cognitive Services, create Foundry resource, provision resource, knowledge index, agent monitoring, customize deployment, onboard, availability. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure-prepare)."
description: "Deploy, evaluate, and manage Foundry agents end-to-end: Docker build, ACR push, hosted/prompt agent create, container start, batch eval, continuous eval, prompt optimizer workflows, FAOS optimization, tracing insights, agent.yaml, dataset curation from traces. USE FOR: deploy agent, hosted agent, create agent, invoke agent, evaluate agent, batch eval, continuous eval, optimize prompt, improve prompt, optimize system prompt, improve agent instructions, FAOS, tracing insights, quality regression, anomaly detection, deploy model, Foundry project, RBAC, role assignment, permissions, quota, capacity, region, troubleshoot agent, deployment failure, create dataset from traces, dataset versioning, eval trending, create AI Services, Cognitive Services, create Foundry resource, provision resource, knowledge index, agent monitoring, customize deployment, onboard, availability. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure-prepare)."
license: MIT
Comment thread
imatiach-msft marked this conversation as resolved.
metadata:
author: Microsoft
Expand All @@ -25,8 +25,8 @@ This skill includes specialized sub-skills for specific workflows. **Use these i
|-----------|-------------|-----------|
| **deploy** | Containerize, build, push to ACR, create/update/clone agent deployments | [deploy](foundry-agent/deploy/deploy.md) |
| **invoke** | Send messages to an agent, single or multi-turn conversations | [invoke](foundry-agent/invoke/invoke.md) |
| **observe** | Evaluate agent quality, run batch evals, analyze failures, optimize prompts, improve agent instructions, compare versions, set up CI/CD monitoring, and enable continuous production evaluation | [observe](foundry-agent/observe/observe.md) |
| **trace** | Query traces, analyze latency/failures, correlate eval results to specific responses via App Insights `customEvents` | [trace](foundry-agent/trace/trace.md) |
| **observe** | Evaluate agent quality, run batch evals, analyze failures, optimize prompts (via `prompt_optimize` or FAOS), run insights-to-optimize loops, improve agent instructions, compare versions, set up CI/CD monitoring, and enable continuous production evaluation | [observe](foundry-agent/observe/observe.md) |
| **trace** | Query traces, analyze latency/failures, correlate eval results, auto-detect quality regressions via Tracing Insights API | [trace](foundry-agent/trace/trace.md) |
| **troubleshoot** | View hosted agent logs, query telemetry, diagnose failures | [troubleshoot](foundry-agent/troubleshoot/troubleshoot.md) |
| **create** | Create new hosted agent applications. Supports Microsoft Agent Framework, LangGraph, or custom frameworks in Python or C#, across `responses` or `invocations` protocols. | [create](foundry-agent/create/create.md) |
| **faos-optimize** | Convert existing Python agent code to a FAOS (Foundry Agent Optimization Service) optimization-ready version by wiring evaluator-targeted instructions/model/temperature knobs, then stop for review before deployment. | [faos-optimize](foundry-agent/faos-optimize/faos-optimize.md) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ USE FOR: evaluate my agent, run an eval, test my agent, check agent quality, run
| "Compare agent versions" | [Step 5: Compare](references/compare-iterate.md) |
| "Set up CI/CD evals" | [Step 6: CI/CD & Monitoring](references/cicd-monitoring.md) |
| "Enable continuous monitoring" / "Set up production monitoring" / "Evaluation results dropping" | [Continuous Eval](references/continuous-eval.md) |
| "Run FAOS optimization" / "Auto-optimize agent" / "Use FAOS" | [FAOS Optimization](references/faos-optimization.md) (prompt agents only) |
| "Auto-detect and fix issues" / "Insights to optimize" / "End-to-end quality loop" | [Insights-to-Optimize Loop](references/insights-to-optimize.md) (prompt agents only) |

> ⚠️ **Important:** Before running any evaluation (Step 2), always resolve the selected agent root, metadata file, and environment, then inspect that metadata file plus `.foundry/evaluators/` and `.foundry/datasets/` in that root only. If the cache is missing, stale, or the user wants to refresh it, route through [Step 1: Auto-Setup](references/deploy-and-setup.md) first — even if the user only asked to "evaluate." Do **not** merge `.foundry` cache or source context from sibling agent folders or sibling metadata files.

Expand Down
Comment thread
imatiach-msft marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# FAOS Optimization (Foundry Agent Optimization Service)

Automatically optimize agent instructions through an iterative RUN → EVAL → REFLECT loop. FAOS rewrites the agent's system prompt to fix quality regressions detected by evaluators.

## Scope

**Prompt agents only.** FAOS reads and rewrites agent instructions via the Foundry Agents API (`POST /agents/{name}/versions`). Hosted agents are not supported in this workflow.

## Endpoint

```
POST https://agents-optimization.westus2.hyena.infra.ai.azure.com/agents-optimization/v1.0/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.MachineLearningServices/workspaces/{ws}/optimize
```

> **Preview:** The FAOS endpoint (`westus2.hyena.infra.ai.azure.com`) is preview/canary infrastructure subject to change. When the production URL becomes available, update the base URL accordingly.
>
> **⚠️ Workspace Requirement:** The `{sub}`, `{rg}`, `{ws}` must reference a **registered** `MachineLearningServices/workspaces` resource. CognitiveServices accounts will not work (hardcoded controller route). Unregistered workspaces return 404. To find a valid workspace, run `az ml workspace list --query "[].{name:name, rg:resource_group}" -o table` and use one from your subscription.
>
> Your actual agent project goes in `foundryProjectUrl` in the request body (any region/subscription).

**Auth:** `az account get-access-token --resource https://ai.azure.com`

## Request Body

```json
{
"agent": {
"foundryProjectUrl": "https://<account>.services.ai.azure.com/api/projects/<project>",
"agentName": "<agent-name>",
"model": "<model-deployment>"
},
"dataset": [
{
"name": "test_scenario_1",
"prompt": "Representative query that exercises the problem area",
"criteria": [
{ "name": "task_adherence", "instruction": "Describe what correct behavior looks like" }
]
}
],
"evaluators": ["task_adherence"],
"options": {
"evalModel": "<model-deployment>",
"budget": 3,
"maxIterations": 2,
"strategies": ["instruction"]
}
}
```

**Strategies:** `instruction` (GEPA-style prompt rewrite), `skill` (failure-driven), `model` (model-swap).

## Polling

POST returns `{"operationId": "opt_xxx", "status": "pending"}`. Poll until complete:

```powershell
$token = az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv
$base = "https://agents-optimization.westus2.hyena.infra.ai.azure.com/agents-optimization/v1.0/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.MachineLearningServices/workspaces/{ws}"

# Capture operationId from the initial POST response
$opId = $startResponse.operationId

do {
Start-Sleep -Seconds 15
$result = Invoke-RestMethod -Uri "$base/optimize/$opId" -Headers @{"Authorization"="Bearer $token"}
} while ($result.status -in @("pending", "running"))
Comment thread
imatiach-msft marked this conversation as resolved.
```

## Response (completed)

```json
{
"operationId": "opt_xxx",
"status": "completed",
"baseline": { "avgScore": 0.75, "passRate": 0.667, "avgTokens": 1145 },
"best": {
"avgScore": 0.75,
"passRate": 1.0,
"avgTokens": 555,
"config": { "systemPrompt": "<optimized instructions>" }
}
}
```

## Apply Optimized Instructions

After FAOS completes, use `agent_update` MCP tool with the optimized prompt from `best.config.systemPrompt`, or PATCH the agent directly via Foundry Agents API (`/agents/<name>?api-version=2025-05-15-preview`).

## Caveats

- FAOS may read default instructions ("You are a helpful assistant") instead of the agent's actual prompt — verify by checking `baseline` scores. If baseline doesn't match expected behavior, manually provide instructions in the request.
- Auto-versioning (`keepVersions: true`) may not create versions correctly on new Foundry agents — create versions manually after optimization.
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Insights-to-Optimize Loop

End-to-end workflow: automatically detect agent quality regressions via the Tracing Insights API, then fix them via FAOS optimization, then verify improvement.

## When to Use

Use this when you want a **fully automated quality improvement loop** — no manual KQL analysis, no manual prompt rewriting. The flow is:

1. Tracing Insights API detects anomalies in evaluation scores
2. Critical/Warning insights are converted to FAOS optimization criteria
3. FAOS rewrites agent instructions to address the regressions
4. Verification confirms token reduction and score improvement

**vs. manual eval loop (observe.md Step 4):** Use observe.md when you have a batch eval with specific failure clusters. Use this loop when you want insights auto-detected from production traces.

**Scope:** Prompt agents only (not hosted agents).

## Prerequisites

- App Insights connected to Foundry project with evaluation data (`gen_ai.evaluation.result` events)
- Agent created via Foundry Agents API (not legacy Assistants API)
- Agent's Responses API working (`POST /openai/responses` returns valid completions)

## Flow

1. **Tracing Insights API** (detect anomalies)
2. **Bridge** (convert insights to FAOS dataset)
3. **FAOS Optimize** (rewrite prompt)
4. **Create v2 agent** with optimized instructions
5. **Verify** (compare v1 vs v2 tokens and scores)

## Step 1: Call Tracing Insights API

See [Tracing Insights API reference](../../trace/references/tracing-insights-api.md) for full details.

Filter results to `Warning` and `Critical` severity insights.

## Step 2: Extract Traces from relatedSpans

Each insight in v1-beta2 includes `relatedSpans` with `operationId` values. Query App Insights to get the actual user queries and agent responses:

```kql
dependencies
| where operation_Id in ("<operationId1>", "<operationId2>")
| where customDimensions has "invoke_agent"
| project query = parse_json(customDimensions["gen_ai.input.messages"]),
response = parse_json(customDimensions["gen_ai.output.messages"]),
tokens = toint(customDimensions["gen_ai.usage.output_tokens"])
```

Use the extracted queries as FAOS dataset prompts. If `relatedSpans` is empty, fall back to manually crafted queries.

## Step 3: Convert Insights to FAOS Dataset

For each insight, map to a FAOS dataset item:

| Insight Signal | FAOS Criteria Instruction |
|---------------|---------------------------|
| TaskAdherence drop | "Agent should follow task instructions precisely and complete all requested items" |
| Intent Resolution drop | "Agent should correctly interpret user intent and ask clarifying questions" |
| Token spike | "Agent should give concise, focused responses without excessive verbosity" |
| Latency spike | "Agent should respond efficiently without unnecessary tool calls" |
| Error rate increase | "Agent should handle edge cases gracefully without errors" |

Generate 2-3 representative prompts per insight that exercise the problem area. Use the agent's domain context to make prompts realistic.

## Step 4: Call FAOS

See [FAOS Optimization reference](./faos-optimization.md) for endpoint details and workspace requirement.

Construct request body with the converted dataset and use `"strategies": ["instruction"]` to rewrite the system prompt.

## Step 5: Apply and Verify

1. Extract `best.config.systemPrompt` from FAOS response
2. Create a new agent (e.g., `<name>-v2`) or update existing agent with optimized instructions
3. Send the same test queries to both v1 and v2
4. Compare:
- **Completion tokens** (expect 30-70% reduction from better instructions)
- **Pass rate** on task adherence criteria
- **Response quality** (spot-check a few responses)

## Example Summary Output

| Metric | v1 | v2 |
|--------|----|----|
| Completion tokens | 3195 | 1008 |
| Pass rate | 66.7% | 100% |
| Reduction | — | 68.5% |

## Decision Point

After verification, ask the user:
- **Keep v2** → Update production agent with optimized instructions
- **Keep v1** → Discard (insights may need more data)
- **Iterate** → Run another FAOS pass with adjusted criteria
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Tracing Insights API

Automatically detect quality regressions and anomalies in agent traces using changepoint detection on evaluation scores stored in App Insights.

## When to Use

Use this instead of manual KQL queries when you want **automated anomaly detection** across evaluation dimensions (task adherence, intent resolution, fluency, latency, token usage). The API finds statistical changepoints in score distributions — no manual threshold tuning needed.
Comment thread
imatiach-msft marked this conversation as resolved.

**Prerequisites:**
- App Insights connected to the Foundry project (with `gen_ai.evaluation.result` custom events)
- Evaluation data from portal playground sessions or batch evals (raw traces alone are not enough)

## Endpoint

> **Preview:** The Tracing Insights endpoint (`eastus2euap.api.azureml.ms`) is preview/canary infrastructure subject to change. When the production URL becomes available, update the base URL accordingly.

```
POST https://eastus2euap.api.azureml.ms/notification/v1-beta2/subscriptions/{sub}/resourceGroups/{rg}/providers/microsoft.insights/components/{component}/:insights
```

**Query parameters:**
| Parameter | Required | Description |
|-----------|----------|-------------|
| `startDateTimeUtc` | Yes | ISO 8601 start of analysis window |
| `endDateTimeUtc` | Yes | ISO 8601 end of analysis window |
| `agent` | Yes | Agent name (URL-encoded) |
| `projectId` | Yes | ARM resource ID of the Foundry project (URL-encoded — contains slashes) |
| `top` | No | Max insights to return (default 50) |

**Auth:** `az account get-access-token --resource https://ai.azure.com`

**Body:** Must send `{}` (empty JSON object) — POST with no body returns 400.

## Example

```powershell
Comment thread
imatiach-msft marked this conversation as resolved.
$token = az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv
$encodedAgent = [uri]::EscapeDataString("my-agent")
$encodedProjectId = [uri]::EscapeDataString("/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/{account}/projects/{project}")

$uri = "https://eastus2euap.api.azureml.ms/notification/v1-beta2/subscriptions/{sub}/resourceGroups/{rg}/providers/microsoft.insights/components/{component}/:insights?startDateTimeUtc=2025-01-01T00:00:00Z&endDateTimeUtc=2025-01-18T00:00:00Z&agent=$encodedAgent&projectId=$encodedProjectId&top=50"

$response = Invoke-RestMethod -Uri $uri -Method POST -Headers @{
"Authorization" = "Bearer $token"
"Content-Type" = "application/json"
} -Body "{}"
```

## Response Structure (v1-beta2)

Response is grouped by agent version. Each insight includes `relatedSpans` with `operationId` (App Insights trace ID) for querying full trace content.

```json
{
"agents": [{
"agent": "my-agent:1",
"insights": [{
"id": "anomaly-token-shift-<hash>",
"type": "Token",
"severity": "Critical",
"message": "Token usage increased by 137%",
"agentVersion": "1",
"metadata": { "meanBefore": 2041, "meanAfter": 4831, "confidence": 0.91 },
"relatedSpans": {
"totalCount": 13,
"spans": [
{ "responseId": "resp_...", "operationId": "<trace-id>", "evaluationRunId": null }
]
}
}],
"insightCount": 3
}],
"totalCount": 3, "criticalCount": 1, "warningCount": 1, "improvementCount": 1
}
```

## Querying Traces from relatedSpans

Use `operationId` from `relatedSpans` to fetch full trace content from App Insights:

```kql
dependencies
| where operation_Id == "<operationId>"
| where customDimensions has "invoke_agent"
| project input = customDimensions["gen_ai.input.messages"],
output = customDimensions["gen_ai.output.messages"],
tokens = toint(customDimensions["gen_ai.usage.output_tokens"])
```

This returns the user query and agent response — use these to auto-build FAOS optimization datasets from real production traces.

## How Changepoint Detection Works

The API finds **statistical inflection points within the queried time window**. `meanBefore`/`meanAfter` represent averages on either side of the detected shift — not comparisons to a historical baseline.

- 10+ data points give better signal for changepoint detection
- `confidence` close to 1.0 = statistically significant shift

## Next Steps

After receiving insights with `Warning` or `Critical` severity, route to [FAOS Optimization](../../observe/references/faos-optimization.md) or the [Insights-to-Optimize loop](../../observe/references/insights-to-optimize.md) to automatically improve the agent.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ USE FOR: analyze agent traces, search agent conversations, find failing traces,
| "Show me this conversation" / "Trace detail" | [Conversation Detail](references/conversation-detail.md) |
| "Find eval results for response ID" / "eval scores from traces" | [Eval Correlation](references/eval-correlation.md) |
| "What KQL do I need?" | [KQL Templates](references/kql-templates.md) |
| "Auto-detect agent issues" / "Get automated insights" / "What's wrong with my agent?" | [Tracing Insights API](references/tracing-insights-api.md) |

## Before Starting — Resolve App Insights Connection

Expand Down
Loading
Loading