|
| 1 | +# pylint: disable=line-too-long,useless-suppression |
| 2 | +# ------------------------------------ |
| 3 | +# Copyright (c) Microsoft Corporation. |
| 4 | +# Licensed under the MIT License. |
| 5 | +# ------------------------------------ |
| 6 | + |
| 7 | +""" |
| 8 | +DESCRIPTION: |
| 9 | + This sample demonstrates how to create a Routine that fires on a |
| 10 | + recurring cron schedule, then record the resulting runs by polling |
| 11 | + `list_runs(...)` using the synchronous AIProjectClient. |
| 12 | +
|
| 13 | + The routine is bound to an existing hosted agent and scheduled with a |
| 14 | + `ScheduleRoutineTrigger` using a 5-field cron expression. The service |
| 15 | + enforces a minimum interval of five minutes, so the sample polls the |
| 16 | + run history for up to ~6 minutes to catch the first fire, prints each |
| 17 | + observed phase transition, then deletes the routine. |
| 18 | +
|
| 19 | + Routines are currently a preview feature. In the Python SDK, you access |
| 20 | + these operations via `project_client.beta.routines`. |
| 21 | +
|
| 22 | +USAGE: |
| 23 | + python sample_routines_with_schedule_trigger.py |
| 24 | +
|
| 25 | + Before running the sample: |
| 26 | +
|
| 27 | + pip install "azure-ai-projects>=2.2.0" python-dotenv |
| 28 | +
|
| 29 | + Set these environment variables with your own values: |
| 30 | + 1) FOUNDRY_PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview |
| 31 | + page of your Microsoft Foundry portal. |
| 32 | + 2) FOUNDRY_HOSTED_AGENT_NAME - The name of an existing Hosted Agent to invoke |
| 33 | + when the routine schedule fires. |
| 34 | + 3) POLL_INTERVAL_SECONDS - Optional. Seconds to sleep between run-history polls. |
| 35 | + Defaults to 15. |
| 36 | +""" |
| 37 | + |
| 38 | +import json |
| 39 | +import os |
| 40 | +import time |
| 41 | + |
| 42 | +from dotenv import load_dotenv |
| 43 | + |
| 44 | +from azure.core.exceptions import ResourceNotFoundError |
| 45 | +from azure.identity import DefaultAzureCredential |
| 46 | + |
| 47 | +from azure.ai.projects import AIProjectClient |
| 48 | +from azure.ai.projects.models import ( |
| 49 | + InvokeAgentResponsesApiRoutineAction, |
| 50 | + RoutineRun, |
| 51 | + RoutineRunPhase, |
| 52 | + ScheduleRoutineTrigger, |
| 53 | +) |
| 54 | + |
| 55 | +load_dotenv() |
| 56 | + |
| 57 | +endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"] |
| 58 | +agent_name = os.environ["FOUNDRY_HOSTED_AGENT_NAME"] |
| 59 | +poll_interval_seconds = int(os.environ.get("POLL_INTERVAL_SECONDS", "15")) |
| 60 | + |
| 61 | + |
| 62 | +def main() -> None: |
| 63 | + with ( |
| 64 | + DefaultAzureCredential() as credential, |
| 65 | + AIProjectClient(endpoint=endpoint, credential=credential, allow_preview=True) as project_client, |
| 66 | + ): |
| 67 | + routine_name = "sample-routine-schedule" |
| 68 | + |
| 69 | + try: |
| 70 | + project_client.beta.routines.delete(routine_name) |
| 71 | + print(f"Routine `{routine_name}` deleted") |
| 72 | + except ResourceNotFoundError: |
| 73 | + pass |
| 74 | + |
| 75 | + # Fire every 5 minutes (the service-enforced minimum interval) in UTC. |
| 76 | + cron_expression = "*/5 * * * *" |
| 77 | + time_zone = "UTC" |
| 78 | + created = project_client.beta.routines.create_or_update( |
| 79 | + routine_name, |
| 80 | + description="Routine used by the schedule-trigger sample.", |
| 81 | + enabled=True, |
| 82 | + triggers={ |
| 83 | + "every_five_minutes": ScheduleRoutineTrigger( |
| 84 | + cron_expression=cron_expression, |
| 85 | + time_zone=time_zone, |
| 86 | + ) |
| 87 | + }, |
| 88 | + action=InvokeAgentResponsesApiRoutineAction(agent_name=agent_name), |
| 89 | + ) |
| 90 | + print( |
| 91 | + f"Created routine: {created.name} enabled={created.enabled} " |
| 92 | + f"cron={cron_expression!r} time_zone={time_zone!r}" |
| 93 | + ) |
| 94 | + |
| 95 | + try: |
| 96 | + terminal_phases = {RoutineRunPhase.COMPLETED, RoutineRunPhase.FAILED} |
| 97 | + seen_phases: dict[str, str] = {} |
| 98 | + final_run: RoutineRun | None = None |
| 99 | + |
| 100 | + # Poll for up to ~6m30s to catch the first scheduled fire. |
| 101 | + max_polls = max(1, (6 * 60 + 30) // poll_interval_seconds + 1) |
| 102 | + print( |
| 103 | + f"Poll `{routine_name}` every {poll_interval_seconds}s for new runs " |
| 104 | + f"(up to {max_polls} iterations, ~6m30s).", |
| 105 | + end="", |
| 106 | + flush=True, |
| 107 | + ) |
| 108 | + dots_pending = False |
| 109 | + for _ in range(max_polls): |
| 110 | + runs = list(project_client.beta.routines.list_runs(routine_name, limit=20, order="desc")) |
| 111 | + for run in runs: |
| 112 | + if seen_phases.get(run.id) == run.phase: |
| 113 | + continue |
| 114 | + seen_phases[run.id] = str(run.phase) |
| 115 | + if dots_pending: |
| 116 | + print() |
| 117 | + dots_pending = False |
| 118 | + print( |
| 119 | + f" - run_id={run.id} phase={run.phase} status={run.status} " |
| 120 | + f"trigger_type={run.trigger_type} triggered_at={run.triggered_at} ended_at={run.ended_at}" |
| 121 | + ) |
| 122 | + if str(run.status).lower() == "finished": |
| 123 | + final_run = run |
| 124 | + |
| 125 | + if final_run is not None: |
| 126 | + break |
| 127 | + time.sleep(poll_interval_seconds) |
| 128 | + print(".", end="", flush=True) |
| 129 | + dots_pending = True |
| 130 | + |
| 131 | + if dots_pending: |
| 132 | + print() |
| 133 | + |
| 134 | + if final_run: |
| 135 | + print("Final run:") |
| 136 | + print(json.dumps(final_run.as_dict(), indent=2, default=str)) |
| 137 | + # Note: retrieving the response body produced by a routine-dispatched |
| 138 | + # run via `openai_client.responses.retrieve(final_run.response_id)` is |
| 139 | + # not yet supported by the service for this scenario. |
| 140 | + else: |
| 141 | + print("Schedule did not produce a terminal run within the deadline.") |
| 142 | + except KeyboardInterrupt: |
| 143 | + print("Interrupted by user; cleaning up routine before exiting.") |
| 144 | + finally: |
| 145 | + # Always delete the routine so it stops firing on the schedule, |
| 146 | + # even if the sample was interrupted or raised an exception. |
| 147 | + try: |
| 148 | + project_client.beta.routines.delete(routine_name) |
| 149 | + print("Routine deleted") |
| 150 | + except ResourceNotFoundError: |
| 151 | + pass |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == "__main__": |
| 155 | + main() |
0 commit comments