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
24 changes: 24 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-optimization/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Release History

## 1.0.0b1 (2026-05-24)

### Features Added

- Initial beta release.
- `load_config(*, config_dir, required)` — single-call config loader with 4-priority resolution and graceful fallback.
- `load_skills_from_dir(path)` — load skills from a directory on demand (not loaded inline by `load_config`).
- `OptimizationConfig` dataclass with instructions, model, temperature, skills, skills_dir, tool_definitions, source, and candidate_id.
- `OptimizationConfig.apply_tool_descriptions(tools)` — patch `__doc__`, `.description`, and `input_model` parameter descriptions on @tool-decorated functions from optimized tool definitions.
- `OptimizationConfig.compose_instructions()` — append skill catalog to instructions.
- `CandidateConfig` — typed representation of the resolver API payload.
- `Skill` — learned skill model (name, description, body).
- 4-priority resolution order:
1. Inline JSON via `OPTIMIZATION_CONFIG` env var.
2. Resolver API via `OPTIMIZATION_CANDIDATE_ID` + `OPTIMIZATION_RESOLVE_ENDPOINT` (endpoint is the full job-scoped URL).
3. Local directory layout (`OPTIMIZATION_LOCAL_DIR` or `config_dir` param, defaults to `.agent_configs/`).
4. `required=True` raises `ValueError`; `required=False` returns `None`.
- Local directory layout: `metadata.yaml` + `instructions.md` + `tools.json` + `skills/` per candidate, with `baseline/` fallback.
- Tool definitions use the OpenAI function-calling list format exclusively.
- Skill loading from `SKILL.md` files with YAML frontmatter.
- Resolver API persists fetched configs and skill files to local directory for offline use.
- Path traversal (zip-slip) protection on skill file downloads from the API.
21 changes: 21 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-optimization/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
include *.md
include LICENSE
recursive-include tests *.py
recursive-include samples *.py *.md
include azure/__init__.py
include azure/ai/__init__.py
include azure/ai/agentserver/__init__.py
include azure/ai/agentserver/optimization/py.typed
220 changes: 220 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-optimization/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
# Azure AI Agent Server Optimization client library for Python

The `azure-ai-agentserver-optimization` package provides a drop-in config loader for optimization-ready Azure AI Hosted Agents. A single `load_config()` call resolves optimization parameters (instructions, model, temperature, skills, tool definitions) from multiple sources with graceful fallback — your agent works unchanged when not running under optimization.

## Getting started

### Install the package

```bash
pip install azure-ai-agentserver-optimization
```

### Prerequisites

- Python 3.10 or later

## Key concepts

### Resolution Order

`load_config()` resolves from four sources in order — first match wins:

| Priority | Source | Env vars required | Description |
|----------|--------|-------------------|-------------|
| 1 | **Inline JSON** | `OPTIMIZATION_CONFIG` | Full config as a JSON string. Used by temporary agent versions during evaluation. |
| 2 | **Resolver API** | `OPTIMIZATION_CANDIDATE_ID`, `OPTIMIZATION_RESOLVE_ENDPOINT` | Fetches the candidate config from the remote optimization service and persists it to the local directory. The endpoint should be the full job-scoped URL. |
| 3 | **Local directory** | `OPTIMIZATION_LOCAL_DIR` (optional, defaults to `.agent_configs/`) | Reads from `<local_dir>/<candidate_id>/` or `baseline/` as fallback. |
| 4 | **No config** | *(none)* | `required=True` (default) raises `ValueError`; `required=False` returns `None`. |

Any unexpected error is caught and logged — `load_config()` never crashes (only `ValueError` from `required=True` propagates).

### Environment Variables

| Variable | Description |
|----------|-------------|
| `OPTIMIZATION_CONFIG` | Inline JSON config (Priority 1). |
| `OPTIMIZATION_CANDIDATE_ID` | Candidate ID for resolver API or local folder lookup. |
| `OPTIMIZATION_RESOLVE_ENDPOINT` | Full job-scoped URL of the optimization service (e.g. `https://host/api/projects/proj/agents_optimization_job/job-1`). |
| `OPTIMIZATION_LOCAL_DIR` | Path to the local config directory (default: `.agent_configs/`). |

### Local Directory Layout

The local config directory **must** exist with at least a `baseline/` folder before the agent can start to do optimization. When running under optimization, the resolver API (Priority 2) persists candidate configs into the same layout. If a `<candidate_id>/` folder exists it takes precedence; otherwise `baseline/` is used as the fallback.

```
.agent_configs/
├── baseline/ # required — default candidate used at startup
│ ├── metadata.yaml # model, temperature, file pointers
│ ├── instructions.md # system prompt
│ ├── tools.json # tool definitions (OpenAI function-calling list format)
│ └── skills/ # learned skills
│ └── <skill_name>/
│ └── SKILL.md
└── <candidate_id>/ # optional — created by resolver API, same layout as baseline/
├── metadata.yaml
├── instructions.md
├── tools.json
└── skills/
└── <skill_name>/
└── SKILL.md
```

#### `metadata.yaml`

Points to the other files and sets model parameters. All fields are optional:

```yaml
model: gpt-4o
temperature: 0.7
instruction_file: instructions.md
skill_dir: skills
tool_file: tools.json
```

#### `instructions.md`

The system prompt for the agent — plain text or Markdown:

```markdown
You are a travel assistant. Help users search flights, book hotels,
and answer questions about company travel policy.
```

#### `tools.json`

Tool definitions in the OpenAI function-calling list format:

```json
[
{
"type": "function",
"function": {
"name": "lookup_policy",
"description": "Look up the company travel policy.",
"parameters": {
"type": "object",
"properties": {
"dept": {"type": "string", "description": "Department name"}
}
}
}
}
]
```

#### `skills/*/SKILL.md`

Each skill lives in its own subfolder with a `SKILL.md` file. An optional YAML frontmatter block provides the name and description; the rest is the skill body:

```markdown
---
name: budget-checker
description: Check whether a trip is within budget.
---

Compare the trip cost against the department's remaining travel budget
and return APPROVED or DENIED with a reason.
```

### OptimizationConfig Properties

| Property | Type | Description |
|----------|------|-------------|
| `instructions` | `str \| None` | System prompt (optimized or default). |
| `model` | `str \| None` | Model deployment name. |
| `temperature` | `float \| None` | Sampling temperature. |
| `skills` | `list[Skill]` | Learned skills (from inline config). |
| `skills_dir` | `str \| None` | Path to skills directory (for on-demand loading). |
| `tool_definitions` | `list[dict]` | Optimized tool definitions (OpenAI function-calling format). |
| `source` | `str` | Where the config was loaded from. |
| `candidate_id` | `str \| None` | Candidate ID (when resolved via API or local folder). |
| `has_skills` | `bool` | Whether skills are available (inline or via skills_dir). |

### Public API

| Export | Type | Description |
|--------|------|-------------|
| `load_config(*, config_dir, required)` | function | Load optimization config with 4-priority resolution. |
| `load_skills_from_dir(path)` | function | Load skills from a directory of `SKILL.md` files. |
| `OptimizationConfig` | dataclass | Resolved config with instructions, model, temperature, skills_dir, tool_definitions. |
| `OptimizationConfig.apply_tool_descriptions(tools)` | method | Patch `__doc__`, `.description`, and parameter descriptions on tool functions. |
| `OptimizationConfig.compose_instructions()` | method | Return instructions with skill catalog appended. |
| `CandidateConfig` | dataclass | Typed representation of the resolver API response. |
| `Skill` | dataclass | A learned skill (name, description, body). |

## Examples

### Basic usage

```python
from azure.ai.agentserver.optimization import load_config

config = load_config() # uses .agent_configs/baseline/
config = load_config(config_dir="my_configs") # custom directory
config = load_config(required=False) # returns None if no config found

print(config.instructions) # optimized system prompt
print(config.model) # optimized model name
print(config.temperature) # optimized temperature
print(config.tool_definitions) # optimized tool definitions (list)
print(config.source) # "env:OPTIMIZATION_CONFIG", "api:candidate:abc", "local:...", etc.
```

### Apply optimized tool descriptions

```python
from azure.ai.agentserver.optimization import load_config

config = load_config()

# Your @tool-decorated functions
def search_flights(origin: str, destination: str):
"""Search for flights."""
...

def book_hotel(city: str):
"""Book a hotel room."""
...

# Patches __doc__ and .description on matching tools with optimized descriptions
config.apply_tool_descriptions([search_flights, book_hotel])
```

### Load skills on demand

```python
from pathlib import Path
from azure.ai.agentserver.optimization import load_config, load_skills_from_dir

config = load_config()

# Skills are not loaded inline — load them when needed
if config.skills_dir:
skills = load_skills_from_dir(Path(config.skills_dir))
for skill in skills:
print(f"{skill.name}: {skill.description}")
```

## Troubleshooting

Enable debug logging to see resolution details:

```python
import logging
logging.getLogger("azure.ai.agentserver.optimization").setLevel(logging.DEBUG)
```

Common issues:
- **Config not loading from resolver API** — ensure both env vars are set: `OPTIMIZATION_CANDIDATE_ID` and `OPTIMIZATION_RESOLVE_ENDPOINT`.
- **Local directory not found** — check that `OPTIMIZATION_LOCAL_DIR` points to an existing directory, or ensure `.agent_configs/` exists relative to your main script.
- **`load_config()` raises ValueError** — no config source was found; either set up a baseline folder or pass `required=False`.

## Next steps

- [Azure SDK for Python documentation](https://learn.microsoft.com/azure/developer/python/)
- [Contributing guide](https://github.com/Azure/azure-sdk-for-python/blob/main/CONTRIBUTING.md)

## Contributing

This project welcomes contributions and suggestions. See [CONTRIBUTING.md](https://github.com/Azure/azure-sdk-for-python/blob/main/CONTRIBUTING.md) for details.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------

"""Agent Optimization — Config loader for optimization-ready hosted agents.

One import, one call::

from azure.ai.agentserver.optimization import load_config

config = load_config() # uses .agent_configs/baseline/
config = load_config(config_dir="my_configs") # custom directory
config = load_config(required=False) # returns None fields instead of raising

Resolution order (first match wins):
1. OPTIMIZATION_CONFIG env var → inline JSON (used by temp agent versions)
2. OPTIMIZATION_CANDIDATE_ID + ENDPOINT → resolver API → full config + skills
3. Local directory (config_dir or .agent_configs/) → metadata.yaml + instructions.md + tools.json + skills/
4. No config found → raises ValueError (or returns empty config if required=False)
"""

from azure.ai.agentserver.optimization._config import load_config, load_skills_from_dir
from azure.ai.agentserver.optimization._models import (
CandidateConfig,
OptimizationConfig,
Skill,
)
from azure.ai.agentserver.optimization._version import VERSION

__all__ = [
"CandidateConfig",
"OptimizationConfig",
"Skill",
"load_config",
"load_skills_from_dir",
]
__version__ = VERSION
Loading
Loading