- Spec files
pypi-langgraph-sdk
Describes: pkg:pypi/langgraph-sdk@0.2.x
- Description
- Python SDK for interacting with the LangGraph Platform REST API to build and manage AI assistants and conversational workflows
- Author
- tessl
- Last updated
scheduled-tasks.md docs/
1# Scheduled Tasks23Create and manage cron jobs for automated execution of assistants on threads or with dynamic thread creation. Supports timezone handling, webhook notifications, and flexible scheduling.45## Capabilities67### Cron Job Creation89Create scheduled tasks for automated assistant execution with flexible scheduling and configuration options.1011```python { .api }12from collections.abc import Mapping13from typing import Any14from langgraph_sdk.schema import (15Cron, Config, Context, All, QueryParamTypes16)1718# Via client.crons19async def create(20assistant_id: str,21*,22schedule: str,23input: Mapping[str, Any] | None = None,24metadata: Mapping[str, Any] | None = None,25config: Config | None = None,26context: Context | None = None,27checkpoint_during: bool | None = None,28interrupt_before: All | list[str] | None = None,29interrupt_after: All | list[str] | None = None,30webhook: str | None = None,31webhook_mode: str | None = None,32headers: Mapping[str, str] | None = None,33params: QueryParamTypes | None = None,34) -> Cron:35"""36Create a cron job that will create a new thread for each run.3738Args:39assistant_id: The assistant ID or graph name to cron.40schedule: The schedule to run the assistant on.41input: The input to the assistant.42metadata: The metadata to add to the runs.43config: The config to use for the runs.44context: The context to add to the runs.45checkpoint_during: Whether to checkpoint during the run.46interrupt_before: Nodes to interrupt immediately before they run.47interrupt_after: Nodes to interrupt immediately after they run.48webhook: Webhook to call after the run is done.49webhook_mode: Mode to call the webhook. Options are "GET" and "POST".50headers: Optional custom headers to include with the request.51params: Optional query parameters to include with the request.5253Returns:54Cron: The created cron job.55"""5657async def create_for_thread(58thread_id: str,59assistant_id: str,60*,61schedule: str,62input: Mapping[str, Any] | None = None,63metadata: Mapping[str, Any] | None = None,64config: Config | None = None,65context: Context | None = None,66checkpoint_during: bool | None = None,67interrupt_before: All | list[str] | None = None,68interrupt_after: All | list[str] | None = None,69webhook: str | None = None,70webhook_mode: str | None = None,71headers: Mapping[str, str] | None = None,72params: QueryParamTypes | None = None,73) -> Cron:74"""75Create a cron job that will run on a specific thread.7677Args:78thread_id: The thread ID to cron.79assistant_id: The assistant ID or graph name to cron.80schedule: The schedule to run the assistant on.81input: The input to the assistant.82metadata: The metadata to add to the runs.83config: The config to use for the runs.84context: The context to add to the runs.85checkpoint_during: Whether to checkpoint during the run.86interrupt_before: Nodes to interrupt immediately before they run.87interrupt_after: Nodes to interrupt immediately after they run.88webhook: Webhook to call after the run is done.89webhook_mode: Mode to call the webhook. Options are "GET" and "POST".90headers: Optional custom headers to include with the request.91params: Optional query parameters to include with the request.9293Returns:94Cron: The created cron job.95"""96```9798### Cron Job Management99100Search, list, count, and delete scheduled tasks with filtering capabilities.101102```python { .api }103from langgraph_sdk.schema import (104CronSelectField, CronSortBy, SortOrder, QueryParamTypes105)106107async def search(108*,109assistant_id: str | None = None,110thread_id: str | None = None,111limit: int = 10,112offset: int = 0,113sort_by: CronSortBy | None = None,114sort_order: SortOrder | None = None,115select: list[CronSelectField] | None = None,116headers: Mapping[str, str] | None = None,117params: QueryParamTypes | None = None,118) -> list[Cron]:119"""120List cron jobs.121122Args:123assistant_id: Assistant ID to filter by.124thread_id: Thread ID to filter by.125limit: Limit the number of cron jobs to return.126offset: Offset to start from.127sort_by: Field to sort by.128sort_order: Order to sort by.129select: Fields to include in the response.130headers: Optional custom headers to include with the request.131params: Optional query parameters to include with the request.132133Returns:134list[Cron]: List of cron jobs.135"""136137async def count(138*,139assistant_id: str | None = None,140thread_id: str | None = None,141headers: Mapping[str, str] | None = None,142params: QueryParamTypes | None = None,143) -> int:144"""145Count cron jobs matching filters.146147Args:148assistant_id: Assistant ID to filter by.149thread_id: Thread ID to filter by.150headers: Optional custom headers to include with the request.151params: Optional query parameters to include with the request.152153Returns:154int: Number of crons matching the criteria.155"""156157async def delete(158cron_id: str,159*,160headers: Mapping[str, str] | None = None,161params: QueryParamTypes | None = None,162) -> None:163"""164Delete a cron job.165166Args:167cron_id: The cron ID to delete.168headers: Optional custom headers to include with the request.169params: Optional query parameters to include with the request.170"""171```172173## Types174175```python { .api }176class Cron(TypedDict):177"""Scheduled task definition."""178cron_id: str179thread_id: str180assistant_id: str181schedule: str182timezone: str183created_at: str184updated_at: str185metadata: dict186config: Config187input: dict188next_run_time: str189last_run_time: str190enabled: bool191192CronSelectField = Literal[193"cron_id", "thread_id", "assistant_id", "schedule",194"timezone", "created_at", "updated_at", "metadata",195"config", "input", "next_run_time", "last_run_time", "enabled"196]197198CronSortBy = Literal["created_at", "updated_at", "next_run_time", "last_run_time"]199```200201## Usage Examples202203### Creating Scheduled Tasks204205```python206# Daily report generation207daily_report = await client.crons.create(208assistant_id="report-assistant",209schedule="0 9 * * *", # 9 AM daily210input={"report_type": "daily", "email_list": ["admin@company.com"]},211config={"timeout": 600},212metadata={"purpose": "daily_report", "owner": "operations"},213timezone="America/New_York",214webhook="https://myapp.com/webhooks/report-complete"215)216217# Hourly data processing for specific thread218hourly_processor = await client.crons.create_for_thread(219thread_id="data-thread-123",220assistant_id="data-processor",221schedule="0 * * * *", # Every hour222input={"source": "api", "format": "json"},223config={"batch_size": 1000},224metadata={"environment": "production"}225)226227# Weekly cleanup task228cleanup_job = await client.crons.create(229assistant_id="cleanup-assistant",230schedule="0 2 * * 0", # 2 AM on Sundays231input={"retention_days": 30, "dry_run": False},232timezone="UTC",233on_completion="keep" # Keep run records for audit234)235```236237### Managing Scheduled Tasks238239```python240# List all cron jobs for an assistant241assistant_jobs = await client.crons.search(242assistant_id="report-assistant",243limit=50244)245246# Find jobs for a specific thread247thread_jobs = await client.crons.search(248thread_id="data-thread-123"249)250251# Get total job count252total_jobs = await client.crons.count()253254# Delete a scheduled task255await client.crons.delete("cron-456")256```257258### Schedule Patterns259260```python261# Common cron schedule patterns262263# Every minute264await client.crons.create(265assistant_id="monitoring-assistant",266schedule="* * * * *"267)268269# Every 15 minutes270await client.crons.create(271assistant_id="health-check-assistant",272schedule="*/15 * * * *"273)274275# Daily at 3:30 AM276await client.crons.create(277assistant_id="backup-assistant",278schedule="30 3 * * *"279)280281# Weekly on Monday at 9 AM282await client.crons.create(283assistant_id="weekly-report-assistant",284schedule="0 9 * * 1"285)286287# Monthly on the 1st at midnight288await client.crons.create(289assistant_id="monthly-billing-assistant",290schedule="0 0 1 * *"291)292293# Weekdays at 6 PM294await client.crons.create(295assistant_id="daily-summary-assistant",296schedule="0 18 * * 1-5"297)298```299300### Timezone Handling301302```python303# Schedule with specific timezone304tokyo_job = await client.crons.create(305assistant_id="tokyo-report-assistant",306schedule="0 9 * * *", # 9 AM Tokyo time307timezone="Asia/Tokyo",308input={"region": "APAC"}309)310311# Multiple timezone jobs for global operation312timezones = ["UTC", "America/New_York", "Europe/London", "Asia/Tokyo"]313for tz in timezones:314await client.crons.create(315assistant_id="regional-assistant",316schedule="0 8 * * *", # 8 AM local time317timezone=tz,318input={"timezone": tz, "region": tz.split("/")[-1]}319)320```321322### Webhook Integration323324```python325# Job with webhook notifications326webhook_job = await client.crons.create(327assistant_id="critical-task-assistant",328schedule="0 */6 * * *", # Every 6 hours329input={"task": "system_health_check"},330webhook="https://monitoring.company.com/webhooks/cron-complete",331metadata={"priority": "critical", "alert_on_failure": True}332)333334# Webhook payload will include:335# {336# "cron_id": "cron-123",337# "run_id": "run-456",338# "status": "success|error|timeout",339# "metadata": {...},340# "completed_at": "2023-12-01T12:00:00Z"341# }342```343344### Error Handling and Monitoring345346```python347# Create jobs with error handling configuration348robust_job = await client.crons.create(349assistant_id="data-sync-assistant",350schedule="0 2 * * *",351input={"source": "external_api", "retries": 3},352config={"timeout": 1800, "retry_policy": "exponential_backoff"},353multitask_strategy="enqueue", # Queue if previous run still active354webhook="https://alerts.company.com/cron-status"355)356357# Monitor scheduled tasks358all_jobs = await client.crons.search(limit=100)359for job in all_jobs:360next_run = job.get("next_run_time")361last_run = job.get("last_run_time")362enabled = job.get("enabled", True)363364print(f"Job {job['cron_id']}: next={next_run}, last={last_run}, enabled={enabled}")365366if not enabled:367print(f"Warning: Job {job['cron_id']} is disabled")368```