diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index bbb6dbc75839..cd26ec280c31 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -22,12 +22,19 @@ Breaking changes in beta methods: * Added `sample_routines_with_timer_trigger.py` to demonstrate triggering a routine with a timer. * Added `sample_routines_with_schedule_trigger.py` to demonstrate triggering a routine on a recurring cron schedule via `ScheduleRoutineTrigger`. * Added `sample_routines_with_dispatch.py` to demonstrate manually firing a routine on demand via `routines.dispatch(...)` using a `CustomRoutineTrigger`. -* Added `sample_skill_in_toolbox.py` demonstrating how to expose a Skill to a Prompt Agent via a Toolbox using `MCPTool`. +* Added new Hosted Agent sample `sample_toolbox_with_skill.py` under `samples/hosted_agents/`, demonstrating a code-based Hosted Agent that uses Toolbox MCP skills. * Updated `sample_dataset_generation_job_traces_for_evaluation.py` and `sample_dataset_generation_job_traces_for_finetuning.py` to create a temporary agent, seed conversations, retry the data generation job over the trace window, and clean up all created resources. * Updated `sample_memory_crud.py` and `sample_memory_crud_async.py` to demonstrate memory item CRUD (`create_memory`, `get_memory`, `update_memory`, `list_memories`, `delete_memory`) in addition to memory store CRUD. * Updated the rubric evaluator generation samples (`sample_rubric_evaluator_generation_basic.py`, `sample_rubric_evaluator_generation_iterate.py`, `sample_rubric_evaluator_generation_lifecycle.py`, `sample_rubric_evaluator_generation_all_sources.py`) to use the typed `EvaluatorGenerationJob` / `EvaluatorGenerationInputs` / `*EvaluatorGenerationJobSource` models. The job inputs are now nested under `inputs` per the service contract, and the traces source uses `datetime` values for `start_time` / `end_time`. * Updated Hosted Agent code-upload samples (`sample_create_hosted_agent_from_code.py`, `sample_create_hosted_agent_from_code_async.py`) to target runtime `python_3_14`, since `python_3_12` is no longer supported. -* Updated Hosted Agent echo-agent assets (`samples/hosted_agents/assets/echo-agent/main.py`, `echo-agent.zip`, `echo-agent-prebuilt.zip`) to use `@app.response_handler`, resolving a response-handling issue. +* Updated Hosted Agent echo-agent assets (`samples/hosted_agents/assets/echo-agent/main.py`, `echo-agent-prebuilt.zip`) to use `@app.response_handler`, resolving a response-handling issue. The remote-build code-upload sample now builds the echo-agent zip from `samples/hosted_agents/assets/echo-agent/` at runtime instead of relying on a checked-in `echo-agent.zip`, so users can update the agent code and rerun the sample with their changes. +* Updated Skills upload/download samples (`sample_skills_upload_and_download.py`, `sample_skills_upload_and_download_async.py`) to build the `team-status-update.zip` package from `samples/skills/assets/team-status-update/` at runtime instead of relying on a checked-in zip archive, so users can update the skill content and rerun the sample with their changes. +* Updated scheduled evaluation samples (`sample_scheduled_evaluations.py`, `sample_scheduled_agent_traces_evaluation_smart_filter.py`) to import `ResourceManagementClient` from `azure.mgmt.resource.resources`. +* Relocated and renamed `sample_skill_in_toolbox.py` (from `samples/hosted_agents/`) to `samples/agents/tools/sample_agent_toolbox_skill.py`. +* Relocated Skills samples from `samples/hosted_agents/` to `samples/skills/`: + * `sample_skills_crud.py`. + * `sample_skills_upload_and_download.py`. +* Relocated Toolbox sample from `samples/hosted_agents/` to `samples/toolboxes/sample_toolboxes_crud.py`. ## 2.2.0 (2026-05-29) diff --git a/sdk/ai/azure-ai-projects/MANIFEST.in b/sdk/ai/azure-ai-projects/MANIFEST.in index fba50036b227..5eb1d7c2736f 100644 --- a/sdk/ai/azure-ai-projects/MANIFEST.in +++ b/sdk/ai/azure-ai-projects/MANIFEST.in @@ -3,5 +3,6 @@ include LICENSE include azure/ai/projects/py.typed recursive-include tests *.py recursive-include samples *.py *.md +recursive-include samples/skills/assets *.txt *.ttf include azure/__init__.py include azure/ai/__init__.py diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json index 703fd4fce265..2284a0c38e9b 100644 --- a/sdk/ai/azure-ai-projects/assets.json +++ b/sdk/ai/azure-ai-projects/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/ai/azure-ai-projects", - "Tag": "python/ai/azure-ai-projects_44980e76d0" + "Tag": "python/ai/azure-ai-projects_a295b83447" } diff --git a/sdk/ai/azure-ai-projects/pyproject.toml b/sdk/ai/azure-ai-projects/pyproject.toml index 26eac48e1123..3cc1de11d7af 100644 --- a/sdk/ai/azure-ai-projects/pyproject.toml +++ b/sdk/ai/azure-ai-projects/pyproject.toml @@ -67,6 +67,9 @@ pytyped = ["py.typed"] [tool.azure-sdk-build] verifytypes = false +[tool.mypy] +exclude = '.*samples[\\/]hosted_agents[\\/]assets[\\/].*main\.py$' + [tool.azure-sdk-conda] in_bundle = false diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skill_in_toolbox.py b/sdk/ai/azure-ai-projects/samples/agents/tools/sample_agent_toolbox_skill.py similarity index 99% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skill_in_toolbox.py rename to sdk/ai/azure-ai-projects/samples/agents/tools/sample_agent_toolbox_skill.py index 1750f9bf3758..a6b432553375 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skill_in_toolbox.py +++ b/sdk/ai/azure-ai-projects/samples/agents/tools/sample_agent_toolbox_skill.py @@ -21,7 +21,7 @@ you access these operations via `project_client.beta.skills`. USAGE: - python sample_skill_in_toolbox.py + python sample_agent_toolbox_skill.py Before running the sample: diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_agent_traces_evaluation_smart_filter.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_agent_traces_evaluation_smart_filter.py index b3f337f6c522..dc1a46e72825 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_agent_traces_evaluation_smart_filter.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_agent_traces_evaluation_smart_filter.py @@ -36,7 +36,7 @@ from azure.identity import DefaultAzureCredential from azure.ai.projects import AIProjectClient from azure.mgmt.authorization import AuthorizationManagementClient -from azure.mgmt.resource import ResourceManagementClient +from azure.mgmt.resource.resources import ResourceManagementClient import uuid from azure.ai.projects.models import ( TestingCriterionAzureAIEvaluator, diff --git a/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py b/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py index 7155d540b640..8762ed0a9541 100644 --- a/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py +++ b/sdk/ai/azure-ai-projects/samples/evaluations/sample_scheduled_evaluations.py @@ -37,7 +37,7 @@ from azure.identity import DefaultAzureCredential from azure.ai.projects import AIProjectClient from azure.mgmt.authorization import AuthorizationManagementClient -from azure.mgmt.resource import ResourceManagementClient +from azure.mgmt.resource.resources import ResourceManagementClient import uuid from azure.ai.projects.models import ( AgentVersionDetails, diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/canvas-design.zip b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/canvas-design.zip deleted file mode 100644 index 65eab1246042..000000000000 Binary files a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/canvas-design.zip and /dev/null differ diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent.zip b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent.zip deleted file mode 100644 index d1f34d64be36..000000000000 Binary files a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent.zip and /dev/null differ diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent/main.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent/main.py index 359c99dbd58f..5820f00bc4a8 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent/main.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/echo-agent/main.py @@ -1,41 +1,40 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -# import asyncio -# import logging +import asyncio +import logging -# from azure.ai.agentserver.responses import ( -# CreateResponse, -# ResponseContext, -# ResponsesAgentServerHost, -# TextResponse, -# ) +from azure.ai.agentserver.responses import ( + CreateResponse, + ResponseContext, + ResponsesAgentServerHost, + TextResponse, +) -# # Configure logging -# logging.basicConfig( -# level=logging.INFO, -# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' -# ) -# logger = logging.getLogger(__name__) +# Configure logging +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") +logger = logging.getLogger(__name__) -# app = ResponsesAgentServerHost() +app = ResponsesAgentServerHost() -# @app.response_handler -# async def handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): -# """Echo the user's input back as a single message.""" -# input_text = await context.get_input_text() -# logger.info(f"Received input: {input_text}") +@app.response_handler +async def handler( + request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event +) -> TextResponse: + """Echo the user's input back as a single message.""" + input_text = await context.get_input_text() + logger.info(f"Received input: {input_text}") -# output_text = f"Echo: {input_text}" -# logger.info(f"Sending output: {output_text}") + output_text = f"Echo: {input_text}" + logger.info(f"Sending output: {output_text}") -# return TextResponse(context, request, text=output_text) + return TextResponse(context, request, text=output_text) -# def main() -> None: -# app.run() +def main() -> None: + app.run() -# if __name__ == "__main__": -# main() +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/main.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/main.py new file mode 100644 index 000000000000..d4e28efc69e2 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/main.py @@ -0,0 +1,81 @@ +# Copyright (c) Microsoft. All rights reserved. + +import asyncio +import os +from collections.abc import Callable, Generator + +import httpx +from typing import Any, cast +from agent_framework import Agent, SkillsProvider +from agent_framework.foundry import FoundryChatClient +from agent_framework_foundry_hosting import ResponsesHostServer # type: ignore[import-untyped] +from azure.identity import DefaultAzureCredential, get_bearer_token_provider +from dotenv import load_dotenv +from mcp.client.session import ClientSession +from mcp.client.streamable_http import streamable_http_client + +MCPSkillsSource = cast(Any, __import__("agent_framework", fromlist=["MCPSkillsSource"]).MCPSkillsSource) + +load_dotenv() + + +class ToolboxAuth(httpx.Auth): + """Attach a fresh Foundry bearer token to every request.""" + + requires_response_body = True + + def __init__(self, token_provider: Callable[[], str]) -> None: + self._token_provider = token_provider + + def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: + request.headers["Authorization"] = f"Bearer {self._token_provider()}" + yield request + + +async def main() -> None: + project_endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] + deployment = os.environ["FOUNDRY_MODEL_NAME"] + toolbox_mcp_url = os.environ["MCP_SERVER_URL"] + + credential = DefaultAzureCredential() + token_provider = get_bearer_token_provider(credential, "https://ai.azure.com/.default") + + async with ( + httpx.AsyncClient( + auth=ToolboxAuth(token_provider), + headers={"Foundry-Features": "Toolboxes=V1Preview"}, + timeout=httpx.Timeout(30.0, read=300.0), + follow_redirects=True, + ) as http_client, + streamable_http_client( + url=toolbox_mcp_url, + http_client=http_client, + ) as (read, write, _), + ClientSession(read, write) as session, + ): + await session.initialize() + + skills_provider = SkillsProvider(MCPSkillsSource(client=session)) + + agent = Agent( + client=FoundryChatClient( + project_endpoint=project_endpoint, + model=deployment, + credential=credential, + ), + name=os.environ.get("AGENT_NAME", "hosted-toolbox-mcp-skills"), + instructions=( + "Use available toolbox skills to answer pricing questions. " + "For shipping cost requests, follow the skill formula exactly " + "and show the formula used." + ), + context_providers=[skills_provider], + default_options={"store": False}, + ) + + server = ResponsesHostServer(agent) + await server.run_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/requirements.txt b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/requirements.txt new file mode 100644 index 000000000000..6cf68528e791 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/assets/toolbox-mcp-skills-agent/requirements.txt @@ -0,0 +1,10 @@ +agent-framework-foundry==1.8.2 +agent-framework-foundry-hosting==1.0.0a260618 +azure-ai-agentserver-core +azure-ai-agentserver-invocations +azure-ai-agentserver-responses +azure-ai-projects +azure-identity +httpx +mcp +python-dotenv diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/hosted_agents_util.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/hosted_agents_util.py index ede784f3db33..7c48af94cad7 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/hosted_agents_util.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/hosted_agents_util.py @@ -1,9 +1,16 @@ import asyncio import hashlib +import sys import time from pathlib import Path from typing import Tuple +_SAMPLES_DIR = Path(__file__).resolve().parents[1] +if str(_SAMPLES_DIR) not in sys.path: + sys.path.insert(0, str(_SAMPLES_DIR)) + +from util import build_skill_zip + from azure.ai.projects import AIProjectClient from azure.ai.projects.aio import AIProjectClient as AsyncAIProjectClient from azure.ai.projects.models import ( @@ -19,25 +26,31 @@ def select_echo_agent_code_zip( ) -> Tuple[CodeDependencyResolution, str, bytes, str]: """Pick the dependency-resolution mode and matching echo-agent zip, and load it. - When ``use_remote_build`` is ``True``, returns REMOTE_BUILD with - ``assets/echo-agent.zip``; otherwise BUNDLED with - ``assets/echo-agent-prebuilt.zip``. + When ``use_remote_build`` is ``True``, returns REMOTE_BUILD with a zip + built from ``assets/echo-agent/``; otherwise BUNDLED with + the checked-in ``assets/echo-agent-prebuilt.zip``. - Reads the zip bytes, computes its SHA-256, and prints a one-line summary. + Computes the zip SHA-256 and prints a one-line summary. Returns ``(dependency_resolution, zip_filename, zip_bytes, zip_sha256)``. """ dependency_resolution = ( CodeDependencyResolution.REMOTE_BUILD if use_remote_build else CodeDependencyResolution.BUNDLED ) - zip_filename = "echo-agent.zip" if use_remote_build else "echo-agent-prebuilt.zip" - zip_path = _ASSETS_DIR / zip_filename - zip_bytes = zip_path.read_bytes() - zip_sha256 = hashlib.sha256(zip_bytes).hexdigest() - print( - f"Loaded code zip from {zip_path} (dependency_resolution={dependency_resolution.value}): " - f"{len(zip_bytes)} bytes, sha256={zip_sha256}" - ) + + if use_remote_build: + zip_filename = "echo-agent.zip" + zip_bytes, zip_sha256, _ = build_skill_zip(_ASSETS_DIR / "echo-agent", zip_filename) + else: + zip_filename = "echo-agent-prebuilt.zip" + zip_path = _ASSETS_DIR / zip_filename + zip_bytes = zip_path.read_bytes() + zip_sha256 = hashlib.sha256(zip_bytes).hexdigest() + print( + f"Loaded code zip from {zip_path} (dependency_resolution={dependency_resolution.value}): " + f"{len(zip_bytes)} bytes, sha256={zip_sha256}" + ) + return dependency_resolution, zip_filename, zip_bytes, zip_sha256 diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/rbac_util.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/rbac_util.py index 40ef3c3cf6a4..3d87562790f2 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/rbac_util.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/rbac_util.py @@ -7,7 +7,7 @@ from azure.core.exceptions import ResourceNotFoundError from azure.mgmt.authorization import AuthorizationManagementClient, models as authorization_models from azure.mgmt.authorization.aio import AuthorizationManagementClient as AsyncAuthorizationManagementClient -from azure.mgmt.resource import ResourceManagementClient +from azure.mgmt.resource.resources import ResourceManagementClient from azure.mgmt.resource.resources.aio import ResourceManagementClient as AsyncResourceManagementClient from azure.ai.projects.models import AgentVersionDetails diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py index 486b120fa0f2..54e8a012c980 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py @@ -15,9 +15,9 @@ * `false` (BUNDLED) — uploads `assets/echo-agent-prebuilt.zip`, which bundles the agent source plus a `packages/` folder with Linux-built dependencies, so the service skips pip entirely. - * `true` (REMOTE_BUILD) — uploads `assets/echo-agent.zip`, which contains - only the agent source plus `requirements.txt`; the service resolves - dependencies remotely from the public package index. + * `true` (REMOTE_BUILD) — zips and uploads `assets/echo-agent/`, which + contains only the agent source plus `requirements.txt`; the service + resolves dependencies remotely from the public package index. The agent must already exist; create it with `samples/hosted_agents/sample_create_hosted_agent.py`. diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py index b3f6f5ba6c10..85a597130058 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py @@ -16,9 +16,9 @@ * `false` (BUNDLED) — uploads `assets/echo-agent-prebuilt.zip`, which bundles the agent source plus a `packages/` folder with Linux-built dependencies, so the service skips pip entirely. - * `true` (REMOTE_BUILD) — uploads `assets/echo-agent.zip`, which contains - only the agent source plus `requirements.txt`; the service resolves - dependencies remotely from the public package index. + * `true` (REMOTE_BUILD) — zips and uploads `assets/echo-agent/`, which + contains only the agent source plus `requirements.txt`; the service + resolves dependencies remotely from the public package index. The agent must already exist; create it with `samples/hosted_agents/sample_create_hosted_agent_async.py`. diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolbox_with_skill.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolbox_with_skill.py new file mode 100644 index 000000000000..a15632fb6d33 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolbox_with_skill.py @@ -0,0 +1,193 @@ +# pylint: disable=line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Demonstrates deploying a code-based Hosted Agent that discovers and uses + skills from a Foundry Toolbox MCP endpoint via Agent Framework + ``SkillsProvider(MCPSkillsSource(...))``. + + The sample: + 1. Creates a shipping-cost skill. + 2. Creates a toolbox version that references the skill. + 3. Packages ``assets/toolbox-mcp-skills-agent/`` source as a zip at runtime + (REMOTE_BUILD - the service resolves dependencies from requirements.txt). + 4. Deploys a new Hosted Agent version, forwarding the project endpoint, + model name, and toolbox MCP URL to the hosted code. + 5. Waits for the version to become active. + 6. Sends a query to the agent via the Responses API. + 7. Cleans up created resources (agent version, toolbox, and skill). + + The hosted agent must already exist; create it first with: + samples/hosted_agents/sample_create_hosted_agent.py + +USAGE: + python sample_toolbox_with_skill.py + + Before running the sample: + + pip install "azure-ai-projects>=2.3.0" python-dotenv + + Set these environment variables with your own values: + 1) FOUNDRY_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the + Overview page of your Microsoft Foundry portal. + 2) FOUNDRY_MODEL_NAME - The deployment name of the AI model, as found under + the "Name" column in the "Models + endpoints" tab in your Foundry project. + 3) FOUNDRY_HOSTED_AGENT_NAME - The Hosted Agent name. Must already exist. + 4) AZURE_SUBSCRIPTION_ID - Azure subscription ID where the Azure AI account + and project are deployed. +""" + +import os +import sys +from pathlib import Path + +_SAMPLES_DIR = Path(__file__).resolve().parents[1] +if str(_SAMPLES_DIR) not in sys.path: + sys.path.insert(0, str(_SAMPLES_DIR)) + +from dotenv import load_dotenv + +from azure.identity import DefaultAzureCredential +from azure.ai.projects import AIProjectClient +from azure.ai.projects.models import ( + CodeConfiguration, + CodeDependencyResolution, + CreateAgentVersionFromCodeContent, + CreateAgentVersionFromCodeMetadata, + HostedAgentDefinition, + ProtocolVersionRecord, +) + +from hosted_agents_util import wait_for_agent_version_active +from rbac_util import ensure_agent_identity_rbac +from util import build_skill_zip + +from azure.core.exceptions import ResourceNotFoundError +from azure.ai.projects.models import ( + SkillInlineContent, + ToolboxSearchPreviewTool, + ToolboxSkillReference, +) + +load_dotenv() + +endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] +model_name = os.environ["FOUNDRY_MODEL_NAME"] +agent_name = os.environ["FOUNDRY_HOSTED_AGENT_NAME"] +subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] + +_HOSTED_AGENT_SOURCE_DIR = Path(__file__).parent / "assets" / "toolbox-mcp-skills-agent" + +SKILL_NAME = "shipping-cost-skill" +TOOLBOX_NAME = "toolbox_with_skill" + + +def main() -> None: + with ( + DefaultAzureCredential() as credential, + AIProjectClient(endpoint=endpoint, credential=credential, allow_preview=True) as project_client, + project_client.get_openai_client(agent_name=agent_name) as hosted_openai_client, + ): + + try: + project_client.toolboxes.delete(TOOLBOX_NAME) + except ResourceNotFoundError: + pass + + try: + project_client.beta.skills.delete(SKILL_NAME) + except ResourceNotFoundError: + pass + + skill_version = project_client.beta.skills.create( + name=SKILL_NAME, + inline_content=SkillInlineContent( + description="Compute shipping cost for a package given weight and destination.", + instructions=( + "You are a shipping cost calculator. When asked to compute " + "shipping cost, use this formula: cost (USD) = 5 + 2 * weight_kg " + "for domestic destinations, and cost (USD) = 15 + 4 * weight_kg " + "for international destinations. Always state the formula you used." + ), + metadata={"revision": "1"}, + ), + ) + print(f"Created skill: {skill_version.name} version={skill_version.version}") + + toolbox_version = project_client.toolboxes.create_version( + name=TOOLBOX_NAME, + description="Toolbox exposing a shipping-cost skill.", + tools=[ToolboxSearchPreviewTool()], + skills=[ToolboxSkillReference(name=skill_version.name, version=skill_version.version)], + ) + print(f"Created toolbox: {toolbox_version.name} version={toolbox_version.version}") + + toolbox_mcp_url = f"{endpoint}/toolboxes/{TOOLBOX_NAME}/versions/{toolbox_version.version}/mcp?api-version=v1" + + zip_filename = "hosted-toolbox-mcp-skills-agent.zip" + zip_bytes, zip_sha256, _ = build_skill_zip(_HOSTED_AGENT_SOURCE_DIR, zip_filename) + + content = CreateAgentVersionFromCodeContent( + metadata=CreateAgentVersionFromCodeMetadata( + description="Hosted agent code for toolbox MCP skills with shipping-cost skill.", + definition=HostedAgentDefinition( + cpu="0.5", + memory="1Gi", + code_configuration=CodeConfiguration( + runtime="python_3_14", + entry_point=["python", "main.py"], + dependency_resolution=CodeDependencyResolution.REMOTE_BUILD, + ), + environment_variables={ + "FOUNDRY_PROJECT_ENDPOINT": endpoint, + "FOUNDRY_MODEL_NAME": model_name, + "MCP_SERVER_URL": toolbox_mcp_url, + }, + protocol_versions=[ProtocolVersionRecord(protocol="responses", version="1.0.0")], + ), + ), + code=(zip_filename, zip_bytes, "application/zip"), + ) + + created = project_client.agents.create_version_from_code( + agent_name=agent_name, + content=content, + code_zip_sha256=zip_sha256, + ) + print(f"Created hosted agent version: {created.version}") + + wait_for_agent_version_active( + project_client=project_client, + agent_name=agent_name, + agent_version=created.version, + ) + + ensure_agent_identity_rbac( + agent=created, + credential=credential, + subscription_id=subscription_id, + foundry_project_endpoint=endpoint, + ) + + user_input = "Compute the shipping cost for a 3 kg package shipped domestically." + print(f"User: {user_input}") + response = hosted_openai_client.responses.create(input=user_input) + + response_text = response.output_text or "" + print("Response:") + print(response_text.encode("utf-8", errors="replace").decode("utf-8")) + + project_client.agents.delete_version(agent_name=agent_name, agent_version=created.version, force=True) + print(f"Agent version {created.version} deleted") + project_client.toolboxes.delete(TOOLBOX_NAME) + print("Toolbox deleted") + project_client.beta.skills.delete(SKILL_NAME) + print("Skill deleted") + + +if __name__ == "__main__": + main() diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/LICENSE.txt b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/LICENSE.txt new file mode 100644 index 000000000000..7a4a3ea2424c --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/SKILL.md b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/SKILL.md new file mode 100644 index 000000000000..9f63fee82de8 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/SKILL.md @@ -0,0 +1,130 @@ +--- +name: canvas-design +description: Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations. +license: Complete terms in LICENSE.txt +--- + +These are instructions for creating design philosophies - aesthetic movements that are then EXPRESSED VISUALLY. Output only .md files, .pdf files, and .png files. + +Complete this in two steps: +1. Design Philosophy Creation (.md file) +2. Express by creating it on a canvas (.pdf file or .png file) + +First, undertake this task: + +## DESIGN PHILOSOPHY CREATION + +To begin, create a VISUAL PHILOSOPHY (not layouts or templates) that will be interpreted through: +- Form, space, color, composition +- Images, graphics, shapes, patterns +- Minimal text as visual accent + +### THE CRITICAL UNDERSTANDING +- What is received: Some subtle input or instructions by the user that should be taken into account, but used as a foundation; it should not constrain creative freedom. +- What is created: A design philosophy/aesthetic movement. +- What happens next: Then, the same version receives the philosophy and EXPRESSES IT VISUALLY - creating artifacts that are 90% visual design, 10% essential text. + +Consider this approach: +- Write a manifesto for an art movement +- The next phase involves making the artwork + +The philosophy must emphasize: Visual expression. Spatial communication. Artistic interpretation. Minimal words. + +### HOW TO GENERATE A VISUAL PHILOSOPHY + +**Name the movement** (1-2 words): "Brutalist Joy" / "Chromatic Silence" / "Metabolist Dreams" + +**Articulate the philosophy** (4-6 paragraphs - concise but complete): + +To capture the VISUAL essence, express how the philosophy manifests through: +- Space and form +- Color and material +- Scale and rhythm +- Composition and balance +- Visual hierarchy + +**CRITICAL GUIDELINES:** +- **Avoid redundancy**: Each design aspect should be mentioned once. Avoid repeating points about color theory, spatial relationships, or typographic principles unless adding new depth. +- **Emphasize craftsmanship REPEATEDLY**: The philosophy MUST stress multiple times that the final work should appear as though it took countless hours to create, was labored over with care, and comes from someone at the absolute top of their field. This framing is essential - repeat phrases like "meticulously crafted," "the product of deep expertise," "painstaking attention," "master-level execution." +- **Leave creative space**: Remain specific about the aesthetic direction, but concise enough that the next Claude has room to make interpretive choices also at a extremely high level of craftmanship. + +The philosophy must guide the next version to express ideas VISUALLY, not through text. Information lives in design, not paragraphs. + +### PHILOSOPHY EXAMPLES + +**"Concrete Poetry"** +Philosophy: Communication through monumental form and bold geometry. +Visual expression: Massive color blocks, sculptural typography (huge single words, tiny labels), Brutalist spatial divisions, Polish poster energy meets Le Corbusier. Ideas expressed through visual weight and spatial tension, not explanation. Text as rare, powerful gesture - never paragraphs, only essential words integrated into the visual architecture. Every element placed with the precision of a master craftsman. + +**"Chromatic Language"** +Philosophy: Color as the primary information system. +Visual expression: Geometric precision where color zones create meaning. Typography minimal - small sans-serif labels letting chromatic fields communicate. Think Josef Albers' interaction meets data visualization. Information encoded spatially and chromatically. Words only to anchor what color already shows. The result of painstaking chromatic calibration. + +**"Analog Meditation"** +Philosophy: Quiet visual contemplation through texture and breathing room. +Visual expression: Paper grain, ink bleeds, vast negative space. Photography and illustration dominate. Typography whispered (small, restrained, serving the visual). Japanese photobook aesthetic. Images breathe across pages. Text appears sparingly - short phrases, never explanatory blocks. Each composition balanced with the care of a meditation practice. + +**"Organic Systems"** +Philosophy: Natural clustering and modular growth patterns. +Visual expression: Rounded forms, organic arrangements, color from nature through architecture. Information shown through visual diagrams, spatial relationships, iconography. Text only for key labels floating in space. The composition tells the story through expert spatial orchestration. + +**"Geometric Silence"** +Philosophy: Pure order and restraint. +Visual expression: Grid-based precision, bold photography or stark graphics, dramatic negative space. Typography precise but minimal - small essential text, large quiet zones. Swiss formalism meets Brutalist material honesty. Structure communicates, not words. Every alignment the work of countless refinements. + +*These are condensed examples. The actual design philosophy should be 4-6 substantial paragraphs.* + +### ESSENTIAL PRINCIPLES +- **VISUAL PHILOSOPHY**: Create an aesthetic worldview to be expressed through design +- **MINIMAL TEXT**: Always emphasize that text is sparse, essential-only, integrated as visual element - never lengthy +- **SPATIAL EXPRESSION**: Ideas communicate through space, form, color, composition - not paragraphs +- **ARTISTIC FREEDOM**: The next Claude interprets the philosophy visually - provide creative room +- **PURE DESIGN**: This is about making ART OBJECTS, not documents with decoration +- **EXPERT CRAFTSMANSHIP**: Repeatedly emphasize the final work must look meticulously crafted, labored over with care, the product of countless hours by someone at the top of their field + +**The design philosophy should be 4-6 paragraphs long.** Fill it with poetic design philosophy that brings together the core vision. Avoid repeating the same points. Keep the design philosophy generic without mentioning the intention of the art, as if it can be used wherever. Output the design philosophy as a .md file. + +--- + +## DEDUCING THE SUBTLE REFERENCE + +**CRITICAL STEP**: Before creating the canvas, identify the subtle conceptual thread from the original request. + +**THE ESSENTIAL PRINCIPLE**: +The topic is a **subtle, niche reference embedded within the art itself** - not always literal, always sophisticated. Someone familiar with the subject should feel it intuitively, while others simply experience a masterful abstract composition. The design philosophy provides the aesthetic language. The deduced topic provides the soul - the quiet conceptual DNA woven invisibly into form, color, and composition. + +This is **VERY IMPORTANT**: The reference must be refined so it enhances the work's depth without announcing itself. Think like a jazz musician quoting another song - only those who know will catch it, but everyone appreciates the music. + +--- + +## CANVAS CREATION + +With both the philosophy and the conceptual framework established, express it on a canvas. Take a moment to gather thoughts and clear the mind. Use the design philosophy created and the instructions below to craft a masterpiece, embodying all aspects of the philosophy with expert craftsmanship. + +**IMPORTANT**: For any type of content, even if the user requests something for a movie/game/book, the approach should still be sophisticated. Never lose sight of the idea that this should be art, not something that's cartoony or amateur. + +To create museum or magazine quality work, use the design philosophy as the foundation. Create one single page, highly visual, design-forward PDF or PNG output (unless asked for more pages). Generally use repeating patterns and perfect shapes. Treat the abstract philosophical design as if it were a scientific bible, borrowing the visual language of systematic observation—dense accumulation of marks, repeated elements, or layered patterns that build meaning through patient repetition and reward sustained viewing. Add sparse, clinical typography and systematic reference markers that suggest this could be a diagram from an imaginary discipline, treating the invisible subject with the same reverence typically reserved for documenting observable phenomena. Anchor the piece with simple phrase(s) or details positioned subtly, using a limited color palette that feels intentional and cohesive. Embrace the paradox of using analytical visual language to express ideas about human experience: the result should feel like an artifact that proves something ephemeral can be studied, mapped, and understood through careful attention. This is true art. + +**Text as a contextual element**: Text is always minimal and visual-first, but let context guide whether that means whisper-quiet labels or bold typographic gestures. A punk venue poster might have larger, more aggressive type than a minimalist ceramics studio identity. Most of the time, font should be thin. All use of fonts must be design-forward and prioritize visual communication. Regardless of text scale, nothing falls off the page and nothing overlaps. Every element must be contained within the canvas boundaries with proper margins. Check carefully that all text, graphics, and visual elements have breathing room and clear separation. This is non-negotiable for professional execution. **IMPORTANT: Use different fonts if writing text. Search the `./canvas-fonts` directory. Regardless of approach, sophistication is non-negotiable.** + +Download and use whatever fonts are needed to make this a reality. Get creative by making the typography actually part of the art itself -- if the art is abstract, bring the font onto the canvas, not typeset digitally. + +To push boundaries, follow design instinct/intuition while using the philosophy as a guiding principle. Embrace ultimate design freedom and choice. Push aesthetics and design to the frontier. + +**CRITICAL**: To achieve human-crafted quality (not AI-generated), create work that looks like it took countless hours. Make it appear as though someone at the absolute top of their field labored over every detail with painstaking care. Ensure the composition, spacing, color choices, typography - everything screams expert-level craftsmanship. Double-check that nothing overlaps, formatting is flawless, every detail perfect. Create something that could be shown to people to prove expertise and rank as undeniably impressive. + +Output the final result as a single, downloadable .pdf or .png file, alongside the design philosophy used as a .md file. + +--- + +## FINAL STEP + +**IMPORTANT**: The user ALREADY said "It isn't perfect enough. It must be pristine, a masterpiece if craftsmanship, as if it were about to be displayed in a museum." + +**CRITICAL**: To refine the work, avoid adding more graphics; instead refine what has been created and make it extremely crisp, respecting the design philosophy and the principles of minimalism entirely. Rather than adding a fun filter or refactoring a font, consider how to make the existing composition more cohesive with the art. If the instinct is to call a new function or draw a new shape, STOP and instead ask: "How can I make what's already here more of a piece of art?" + +Take a second pass. Go back to the code and refine/polish further to make this a philosophically designed masterpiece. + +## MULTI-PAGE OPTION + +To create additional pages when requested, create more creative pages along the same lines as the design philosophy but distinctly different as well. Bundle those pages in the same .pdf or many .pngs. Treat the first page as just a single page in a whole coffee table book waiting to be filled. Make the next pages unique twists and memories of the original. Have them almost tell a story in a very tasteful way. Exercise full creative freedom. \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-OFL.txt b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-OFL.txt new file mode 100644 index 000000000000..5b17f0c628c0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The DM Mono Project Authors (https://www.github.com/googlefonts/dm-mono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-Regular.ttf b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-Regular.ttf new file mode 100644 index 000000000000..7efe813da72c Binary files /dev/null and b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/DMMono-Regular.ttf differ diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-OFL.txt b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-OFL.txt new file mode 100644 index 000000000000..4bb99142f612 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf new file mode 100644 index 000000000000..14c6113cdd3a Binary files /dev/null and b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf differ diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf new file mode 100644 index 000000000000..976303184a52 Binary files /dev/null and b/sdk/ai/azure-ai-projects/samples/skills/assets/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf differ diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/SKILL.md b/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/SKILL.md new file mode 100644 index 000000000000..cb64f127084e --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/SKILL.md @@ -0,0 +1,30 @@ +--- +name: team-status-update +description: Drafts concise team status updates with progress, plans, and blockers. +--- + +# Team Status Update + +Use this skill to draft a short team status update that summarizes completed work, +upcoming work, and blockers. + +## Guidelines + +- Keep the update short enough to read in under a minute. +- Use one to three bullets in each section. +- Put completed work under Completed work. +- Put upcoming work under Next steps. +- Put risks, blockers, or needed help under Blockers. +- Include owners, dates, or metrics when they make the update clearer. + +## Ask For + +- Team name. +- Time period. +- Completed work. +- Next steps. +- Blockers or risks. + +## Output + +Use the structure in `status-update-template.md`. \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/status-update-template.md b/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/status-update-template.md new file mode 100644 index 000000000000..6e243f9e8875 --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/skills/assets/team-status-update/status-update-template.md @@ -0,0 +1,15 @@ +# Team Status Update Template + +## Completed work + +- Finished the onboarding guide draft. +- Grouped the top support questions into three themes. + +## Next steps + +- Publish the guide on Friday. +- Add support FAQ links next week. + +## Blockers + +- Need an owner for quarterly refreshes. \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_crud.py b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_crud.py similarity index 100% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_crud.py rename to sdk/ai/azure-ai-projects/samples/skills/sample_skills_crud.py diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_crud_async.py b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_crud_async.py similarity index 100% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_crud_async.py rename to sdk/ai/azure-ai-projects/samples/skills/sample_skills_crud_async.py diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download.py b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download.py similarity index 73% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download.py rename to sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download.py index 5000e1b8a26a..eb71031b47a9 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download.py +++ b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download.py @@ -29,14 +29,19 @@ 1) FOUNDRY_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview page of your Microsoft Foundry portal. - This sample uploads `samples/hosted_agents/assets/canvas-design.zip`. + This sample builds and uploads `samples/skills/assets/team-status-update/`. """ import os +import sys import tempfile from datetime import datetime from pathlib import Path +_SAMPLES_DIR = Path(__file__).resolve().parents[1] +if str(_SAMPLES_DIR) not in sys.path: + sys.path.insert(0, str(_SAMPLES_DIR)) + from dotenv import load_dotenv from azure.core.exceptions import ResourceNotFoundError @@ -45,12 +50,15 @@ from azure.ai.projects import AIProjectClient from azure.ai.projects.models import CreateSkillVersionFromFilesBody +from util import build_skill_zip + load_dotenv() endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] download_folder = Path(tempfile.gettempdir()).resolve() -skill_name = "canvas-design" -skill_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/canvas-design.zip")) +skill_name = "team-status-update" +skill_zip_filename = "team-status-update.zip" +skill_source_dir = Path(__file__).parent / "assets/team-status-update" with ( DefaultAzureCredential() as credential, @@ -63,26 +71,26 @@ except ResourceNotFoundError: pass - skill_path = Path(skill_file_path) + skill_zip_bytes, _, skill_zip_path = build_skill_zip(skill_source_dir, skill_zip_filename) # The ``files`` field accepts any variant of the SDK's ``FileType`` union. - # All four forms below produce an equivalent multipart request body; pick - # whichever fits your call site. The 3-tuple form (used here) is the most - # explicit — it pins both the filename and the content type. + # The 2-tuple form used here pins the filename while letting the transport + # choose the multipart part headers. # - # # 1) bare IO[bytes] — filename derived from the file handle's `.name` - # files=[skill_path.open("rb")] + # # 1) bare IO[bytes] - filename derived from the file handle's `.name` + # files=[skill_zip_path.open("rb")] # # # 2) (filename, bytes) - # files=[(skill_path.name, skill_path.read_bytes())] + # files=[(skill_zip_filename, skill_zip_bytes)] # # # 3) (filename, IO[bytes]) - # files=[(skill_path.name, skill_path.open("rb"))] + # files=[(skill_zip_filename, skill_zip_path.open("rb"))] # # # 4) (filename, bytes, content_type) - # files=[(skill_path.name, skill_path.read_bytes(), "application/zip")] + # files=[(skill_zip_filename, skill_zip_bytes, "application/zip")] + # imported = project_client.beta.skills.create_from_files( skill_name, - content=CreateSkillVersionFromFilesBody(files=[(skill_path.name, skill_path.read_bytes(), "application/zip")]), + content=CreateSkillVersionFromFilesBody(files=[(skill_zip_filename, skill_zip_bytes)]), ) imported_skill_name = imported.name print(f"Imported skill from package: {imported.name} ({imported.skill_id}) version={imported.version}") diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download_async.py b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download_async.py similarity index 74% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download_async.py rename to sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download_async.py index 1ddaabeea304..844326c62a4c 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_skills_upload_and_download_async.py +++ b/sdk/ai/azure-ai-projects/samples/skills/sample_skills_upload_and_download_async.py @@ -29,15 +29,20 @@ 1) FOUNDRY_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview page of your Microsoft Foundry portal. - This sample uploads `samples/hosted_agents/assets/canvas-design.zip`. + This sample builds and uploads `samples/skills/assets/team-status-update/`. """ import asyncio import os +import sys import tempfile from datetime import datetime from pathlib import Path +_SAMPLES_DIR = Path(__file__).resolve().parents[1] +if str(_SAMPLES_DIR) not in sys.path: + sys.path.insert(0, str(_SAMPLES_DIR)) + from dotenv import load_dotenv from azure.core.exceptions import ResourceNotFoundError @@ -46,12 +51,15 @@ from azure.ai.projects.aio import AIProjectClient from azure.ai.projects.models import CreateSkillVersionFromFilesBody +from util import build_skill_zip + load_dotenv() endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] download_folder = Path(tempfile.gettempdir()).resolve() -skill_name = "canvas-design" -skill_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/canvas-design.zip")) +skill_name = "team-status-update" +skill_zip_filename = "team-status-update.zip" +skill_source_dir = Path(__file__).parent / "assets/team-status-update" async def main() -> None: @@ -66,28 +74,26 @@ async def main() -> None: except ResourceNotFoundError: pass - skill_path = Path(skill_file_path) + skill_zip_bytes, _, skill_zip_path = build_skill_zip(skill_source_dir, skill_zip_filename) # The ``files`` field accepts any variant of the SDK's ``FileType`` union. - # All four forms below produce an equivalent multipart request body; pick - # whichever fits your call site. The 3-tuple form (used here) is the most - # explicit — it pins both the filename and the content type. + # The 2-tuple form used here pins the filename while letting the transport + # choose the multipart part headers. # - # # 1) bare IO[bytes] — filename derived from the file handle's `.name` - # files=[skill_path.open("rb")] + # # 1) bare IO[bytes] - filename derived from the file handle's `.name` + # files=[skill_zip_path.open("rb")] # # # 2) (filename, bytes) - # files=[(skill_path.name, skill_path.read_bytes())] + # files=[(skill_zip_filename, skill_zip_bytes)] # # # 3) (filename, IO[bytes]) - # files=[(skill_path.name, skill_path.open("rb"))] + # files=[(skill_zip_filename, skill_zip_path.open("rb"))] # # # 4) (filename, bytes, content_type) - # files=[(skill_path.name, skill_path.read_bytes(), "application/zip")] + # files=[(skill_zip_filename, skill_zip_bytes, "application/zip")] + # imported = await project_client.beta.skills.create_from_files( skill_name, - content=CreateSkillVersionFromFilesBody( - files=[(skill_path.name, skill_path.read_bytes(), "application/zip")] - ), + content=CreateSkillVersionFromFilesBody(files=[(skill_zip_filename, skill_zip_bytes)]), ) imported_skill_name = imported.name print(f"Imported skill from package: {imported.name} ({imported.skill_id}) version={imported.version}") diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolboxes_crud.py b/sdk/ai/azure-ai-projects/samples/toolboxes/sample_toolboxes_crud.py similarity index 100% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolboxes_crud.py rename to sdk/ai/azure-ai-projects/samples/toolboxes/sample_toolboxes_crud.py diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolboxes_crud_async.py b/sdk/ai/azure-ai-projects/samples/toolboxes/sample_toolboxes_crud_async.py similarity index 100% rename from sdk/ai/azure-ai-projects/samples/hosted_agents/sample_toolboxes_crud_async.py rename to sdk/ai/azure-ai-projects/samples/toolboxes/sample_toolboxes_crud_async.py diff --git a/sdk/ai/azure-ai-projects/samples/util.py b/sdk/ai/azure-ai-projects/samples/util.py new file mode 100644 index 000000000000..fa7081ac815f --- /dev/null +++ b/sdk/ai/azure-ai-projects/samples/util.py @@ -0,0 +1,48 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import hashlib +import io +import tempfile +import zipfile +from pathlib import Path +from typing import Optional, Tuple + + +def _read_zip_member_bytes(file_path: Path) -> bytes: + file_bytes = file_path.read_bytes() + if b"\0" in file_bytes: + return file_bytes + + try: + text = file_bytes.decode("utf-8") + except UnicodeDecodeError: + return file_bytes + + return text.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8") + + +def build_skill_zip(source_dir: Path, zip_filename: Optional[str] = None) -> Tuple[bytes, str, Path]: + """Zip all files in *source_dir* deterministically and return ``(zip_bytes, sha256_hex, zip_path)``.""" + # Build a byte-stable zip for test-proxy recording/playback: use sorted POSIX + # member paths, fixed timestamps, stored entries, Unix creator metadata, and + # fixed 0644 permissions so Windows, Linux, and macOS produce the same archive + # bytes. Text files are normalized to LF while binary files are preserved unchanged. + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_STORED) as zf: + for file_path in sorted(source_dir.rglob("*")): + if file_path.is_file(): + arcname = file_path.relative_to(source_dir).as_posix() + zip_info = zipfile.ZipInfo(arcname, date_time=(1980, 1, 1, 0, 0, 0)) + zip_info.create_system = 3 + zip_info.compress_type = zipfile.ZIP_STORED + zip_info.external_attr = 0o644 << 16 + zf.writestr(zip_info, _read_zip_member_bytes(file_path)) + zip_bytes = buf.getvalue() + zip_sha256 = hashlib.sha256(zip_bytes).hexdigest() + zip_path = Path(tempfile.gettempdir()).resolve() / (zip_filename or f"{source_dir.name}.zip") + zip_path.write_bytes(zip_bytes) + print(f"Built skill zip from {source_dir}: " f"{len(zip_bytes)} bytes, sha256={zip_sha256}, path={zip_path}") + return zip_bytes, zip_sha256, zip_path diff --git a/sdk/ai/azure-ai-projects/tests/conftest.py b/sdk/ai/azure-ai-projects/tests/conftest.py index d875289e8c8d..4ea07947a42e 100644 --- a/sdk/ai/azure-ai-projects/tests/conftest.py +++ b/sdk/ai/azure-ai-projects/tests/conftest.py @@ -54,6 +54,7 @@ class SanitizedValues: COMPONENT_NAME = "sanitized-component-name" AGENTS_API_VERSION = "sanitized-api-version" API_KEY = "sanitized-api-key" + MODEL_DEPLOYMENT_NAME = "sanitized-model-deployment-name" @pytest.fixture(scope="session") @@ -66,6 +67,7 @@ def sanitized_values(): "component_name": f"{SanitizedValues.COMPONENT_NAME}", "agents_api_version": f"{SanitizedValues.AGENTS_API_VERSION}", "api_key": f"{SanitizedValues.API_KEY}", + "model_deployment_name": f"{SanitizedValues.MODEL_DEPLOYMENT_NAME}", } @@ -236,6 +238,36 @@ def sanitize_url_paths(): ) add_body_string_sanitizer(target=image_generation_model, value="sanitized-gpt-image") + model_deployment_names = { + value + for value in ( + os.environ.get("FOUNDRY_MODEL_NAME"), + os.environ.get("foundry_model_name"), + os.environ.get("MODEL_DEPLOYMENT_NAME"), + os.environ.get("model_deployment_name"), + os.environ.get("MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"), + os.environ.get("memory_store_chat_model_deployment_name"), + ) + if value and value != sanitized_values["model_deployment_name"] + } + for model_deployment_name in model_deployment_names: + add_general_regex_sanitizer( + regex=re.escape(model_deployment_name), + value=sanitized_values["model_deployment_name"], + ) + add_body_string_sanitizer( + target=model_deployment_name, + value=sanitized_values["model_deployment_name"], + ) + + # Deterministic fallback sanitization for model deployment names returned by + # OpenAI-compatible endpoints. These can appear in response bodies and headers + # even when the live value was not supplied through a known environment variable. + add_general_regex_sanitizer( + regex=r"(? str: The sample path may be absolute or relative and may use either '\\' or '/'. Matching is done against the path segment under the `samples/` directory. - Falls back to resource_management_instructions when no folder match is found. + Raises ValueError when no explicit folder mapping is found. """ normalized = str(sample_path).replace("\\", "/") @@ -272,4 +275,8 @@ def get_instructions_for_sample_path(sample_path: str) -> str: if folder == key or folder.startswith(f"{key}/"): return INSTRUCTIONS_BY_FOLDER[key] - return resource_management_instructions + known = ", ".join(sorted(INSTRUCTIONS_BY_FOLDER.keys())) + raise ValueError( + f"No LLM instruction mapping found for sample folder '{folder}' from path '{sample_path}'. " + f"Add an entry to INSTRUCTIONS_BY_FOLDER. Known folders: {known}" + ) diff --git a/sdk/ai/azure-ai-projects/tests/samples/test_samples.py b/sdk/ai/azure-ai-projects/tests/samples/test_samples.py index d27d0e8b5975..6aa1c76d52a8 100644 --- a/sdk/ai/azure-ai-projects/tests/samples/test_samples.py +++ b/sdk/ai/azure-ai-projects/tests/samples/test_samples.py @@ -252,8 +252,44 @@ def test_chat_completions_samples(self, sample_path: str, **kwargs) -> None: @SamplePathPasser() @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) def test_hosted_agents_samples(self, sample_path: str, **kwargs) -> None: - if os.path.basename(sample_path).startswith("sample_create_hosted_agent") and not self.is_live: - pytest.skip("sample_create_hosted_agent.py is skipped in replay mode due to RBAC complications.") + samples_to_skip_validation = ["sample_create_hosted_agent", "sample_toolbox_with_skill"] + if ( + any(os.path.basename(sample_path).startswith(sample) for sample in samples_to_skip_validation) + and not self.is_live + ): + pytest.skip("Hosted agent sample is skipped in replay mode due to RBAC complications.") + env_vars = get_sample_env_vars(kwargs) + executor = SyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) + executor.execute() + executor.validate_print_calls_by_llm() + + @pytest.mark.parametrize( + "sample_path", + get_sample_paths( + "skills", + samples_to_skip=[], + ), + ) + @servicePreparer() + @SamplePathPasser() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_skills_samples(self, sample_path: str, **kwargs) -> None: + env_vars = get_sample_env_vars(kwargs) + executor = SyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) + executor.execute() + executor.validate_print_calls_by_llm() + + @pytest.mark.parametrize( + "sample_path", + get_sample_paths( + "toolboxes", + samples_to_skip=[], + ), + ) + @servicePreparer() + @SamplePathPasser() + @recorded_by_proxy(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + def test_toolboxes_samples(self, sample_path: str, **kwargs) -> None: env_vars = get_sample_env_vars(kwargs) executor = SyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) executor.execute() diff --git a/sdk/ai/azure-ai-projects/tests/samples/test_samples_async.py b/sdk/ai/azure-ai-projects/tests/samples/test_samples_async.py index db877e4900bd..8d92ecca18db 100644 --- a/sdk/ai/azure-ai-projects/tests/samples/test_samples_async.py +++ b/sdk/ai/azure-ai-projects/tests/samples/test_samples_async.py @@ -220,8 +220,44 @@ async def test_chat_completions_samples(self, sample_path: str, **kwargs) -> Non @SamplePathPasser() @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) async def test_hosted_agents_samples(self, sample_path: str, **kwargs) -> None: - if os.path.basename(sample_path).startswith("sample_create_hosted_agent") and not self.is_live: - pytest.skip("sample_create_hosted_agent.py is skipped in replay mode due to RBAC complications.") + samples_to_skip_validation = ["sample_create_hosted_agent", "sample_toolbox_with_skill"] + if ( + any(os.path.basename(sample_path).startswith(sample) for sample in samples_to_skip_validation) + and not self.is_live + ): + pytest.skip("Hosted agent sample is skipped in replay mode due to RBAC complications.") + env_vars = get_sample_env_vars(kwargs) + executor = AsyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) + await executor.execute_async() + await executor.validate_print_calls_by_llm_async() + + @pytest.mark.parametrize( + "sample_path", + get_async_sample_paths( + "skills", + samples_to_skip=[], + ), + ) + @servicePreparer() + @SamplePathPasser() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_skills_samples(self, sample_path: str, **kwargs) -> None: + env_vars = get_sample_env_vars(kwargs) + executor = AsyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) + await executor.execute_async() + await executor.validate_print_calls_by_llm_async() + + @pytest.mark.parametrize( + "sample_path", + get_async_sample_paths( + "toolboxes", + samples_to_skip=[], + ), + ) + @servicePreparer() + @SamplePathPasser() + @recorded_by_proxy_async(RecordedTransport.AZURE_CORE, RecordedTransport.HTTPX) + async def test_toolboxes_samples(self, sample_path: str, **kwargs) -> None: env_vars = get_sample_env_vars(kwargs) executor = AsyncSampleExecutor(self, sample_path, env_vars=env_vars, **kwargs) await executor.execute_async() diff --git a/sdk/ai/azure-ai-projects/tests/samples/test_util.py b/sdk/ai/azure-ai-projects/tests/samples/test_util.py new file mode 100644 index 000000000000..4d35ecf67856 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tests/samples/test_util.py @@ -0,0 +1,78 @@ +# pylint: disable=line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import hashlib +import io +import sys +import zipfile +from pathlib import Path + +SAMPLES_DIR = Path(__file__).resolve().parents[2] / "samples" +sys.path.insert(0, str(SAMPLES_DIR.resolve())) + +import util +from util import build_skill_zip + + +def test_build_skill_zip_writes_deterministic_zip_to_temp_folder(tmp_path, monkeypatch): + source_dir = tmp_path / "source" + nested_dir = source_dir / "nested" + nested_dir.mkdir(parents=True) + (source_dir / "b.txt").write_bytes(b"bravo") + (nested_dir / "a.txt").write_bytes(b"alpha") + + temp_dir = tmp_path / "temp" + temp_dir.mkdir() + monkeypatch.setattr(util.tempfile, "gettempdir", lambda: str(temp_dir)) + + zip_bytes, zip_sha256, zip_path = build_skill_zip(source_dir, "skill.zip") + + assert zip_path == temp_dir.resolve() / "skill.zip" + assert zip_path.read_bytes() == zip_bytes + assert zip_sha256 == hashlib.sha256(zip_bytes).hexdigest() + + with zipfile.ZipFile(io.BytesIO(zip_bytes), "r") as zf: + assert zf.namelist() == ["b.txt", "nested/a.txt"] + assert zf.read("b.txt") == b"bravo" + assert zf.read("nested/a.txt") == b"alpha" + + for zip_info in zf.infolist(): + assert zip_info.date_time == (1980, 1, 1, 0, 0, 0) + assert zip_info.create_system == 3 + assert zip_info.compress_type == zipfile.ZIP_STORED + assert zip_info.external_attr == 0o644 << 16 + + +def test_build_skill_zip_normalizes_text_line_endings_and_preserves_binary(tmp_path, monkeypatch): + source_dir = tmp_path / "source" + source_dir.mkdir() + (source_dir / "SKILL.md").write_bytes(b"# Title\r\n\r\nBody\r\n") + (source_dir / "data.bin").write_bytes(b"\x00\r\n\xff") + + temp_dir = tmp_path / "temp" + temp_dir.mkdir() + monkeypatch.setattr(util.tempfile, "gettempdir", lambda: str(temp_dir)) + + zip_bytes, _zip_sha256, _zip_path = build_skill_zip(source_dir, "skill.zip") + + with zipfile.ZipFile(io.BytesIO(zip_bytes), "r") as zf: + assert zf.read("SKILL.md") == b"# Title\n\nBody\n" + assert zf.read("data.bin") == b"\x00\r\n\xff" + + +def test_build_skill_zip_uses_source_dir_name_for_default_zip_filename(tmp_path, monkeypatch): + source_dir = tmp_path / "canvas-design" + source_dir.mkdir() + (source_dir / "SKILL.md").write_text("# Canvas Design\n", encoding="utf-8") + + temp_dir = tmp_path / "temp" + temp_dir.mkdir() + monkeypatch.setattr(util.tempfile, "gettempdir", lambda: str(temp_dir)) + + _zip_bytes, _zip_sha256, zip_path = build_skill_zip(source_dir) + + assert zip_path == temp_dir.resolve() / "canvas-design.zip" + assert zip_path.exists()