### Run Hatchet Cloud Quickstart Source: https://docs.hatchet.run/llms-full.txt Executes the Hatchet Cloud quickstart project setup. ```sh hatchet quickstart ``` -------------------------------- ### Setup Development Environment Source: https://docs.hatchet.run/llms-full.txt Installs dependencies, runs migrations, generates encryption keys, and seeds the database. This is a comprehensive setup command. ```sh task setup ``` -------------------------------- ### Install Hatchet Stack with Helm Source: https://docs.hatchet.run/self-hosting/kubernetes-quickstart Deploy the Hatchet stack including Caddy for local access and a quickstart job for initial setup. This command adds the Hatchet Helm repository and installs the hatchet-stack. ```bash helm repo add hatchet https://hatchet-dev.github.io/hatchet-charts helm install hatchet-stack hatchet/hatchet-stack --set caddy.enabled=true --set quickstartJob.enabled=true ``` -------------------------------- ### Start Hatchet Services with Docker Compose Source: https://docs.hatchet.run/self-hosting/docker-compose Run this command in the root of your repository to start all defined services in the Docker Compose file. Ensure Docker is installed and the docker-compose.yml file is present. ```bash docker compose up ``` -------------------------------- ### Start Database and Queue Services Source: https://docs.hatchet.run/llms-full.txt Run this command to start the necessary database and queue services for development. ```sh task start-db ``` -------------------------------- ### TypeScript Worker Start Command Source: https://docs.hatchet.run/llms-full.txt Command to start the TypeScript worker for the support agent tools example. Ensure you are in the 'sdks/typescript' directory and have pnpm installed. ```bash cd sdks/typescript pnpm exec tsx -r tsconfig-paths/register src/v1/examples/support_agent_tools/worker.ts ``` -------------------------------- ### Python Worker Start Command Source: https://docs.hatchet.run/llms-full.txt Command to start the Python worker for the support agent tools example. Ensure you are in the 'sdks/python' directory. ```bash cd sdks/python poetry run python -m examples.support_agent_tools.worker ``` -------------------------------- ### Example .env File Configuration Source: https://docs.hatchet.run/llms-full.txt Example configuration for an .env file in the `./examples/simple` directory. Includes optional settings for OpenTelemetry. ```sh cat > ./examples/simple/.env << "EOF" # optional OTEL_EXPORTER_OTLP_HEADERS= # optional OTEL_EXPORTER_OTLP_ENDPOINT= EOF ``` -------------------------------- ### Run Python Agent Examples (Claude/OpenAI) Source: https://docs.hatchet.run/cookbooks/hatchet-and-mcp Execute agent examples using the Python SDK. Requires ANTHROPIC_API_KEY or OPENAI_API_KEY environment variables. ```bash cd sdks/python poetry run python -m examples.agent.agent_claude # or poetry run python -m examples.agent.agent_openai ``` -------------------------------- ### Run Streaming Workflow in NextJS (TypeScript) Source: https://docs.hatchet.run/llms-full.txt Example of running a streaming workflow in a NextJS backend-as-frontend setup using TypeScript. Ensure the necessary imports and client setup are in place. ```typescript export async function GET(): Promise { try { const ref = await streamingTask.runNoWait({}); const workflowRunId = await ref.getWorkflowRunId(); const stream = Readable.from(hatchet.runs.subscribeToStream(workflowRunId)); return new Response(Readable.toWeb(stream), { headers: { 'Content-Type': 'text/plain', 'Cache-Control': 'no-cache', Connection: 'keep-alive', }, }); } catch (error) { return new Response('Internal Server Error', { status: 500 }); } } ``` -------------------------------- ### Go Worker Configuration Source: https://docs.hatchet.run/cli/running-workers-locally Configure a Go worker for local development. Use `preCmds` for setup and `runCmd` to start the worker. Includes file watching and auto-reload. ```yaml dev: preCmds: ["go mod download"] runCmd: "go run ./cmd/worker" files: - "**/*.go" reload: true ``` -------------------------------- ### Run TypeScript Agent Examples (Claude/OpenAI) Source: https://docs.hatchet.run/cookbooks/hatchet-and-mcp Execute agent examples with the TypeScript SDK. Ensure necessary API keys (e.g., ANTHROPIC_API_KEY) are configured. ```bash cd sdks/typescript pnpm exec tsx -r tsconfig-paths/register src/v1/examples/agent/agent-claude.ts # or pnpm exec tsx -r tsconfig-paths/register src/v1/examples/agent/agent-openai.ts ``` -------------------------------- ### Start Development Server Source: https://docs.hatchet.run/llms-full.txt Starts the Hatchet engine, API server, dashboard, and Prisma studio. Use `task start-dev-tmux` for tmux pane integration. ```sh task start-dev # or task start-dev-tmux if you want to use tmux panes ``` -------------------------------- ### Install Hatchet SDK Source: https://docs.hatchet.run/llms-full.txt Install the hatchet-sdk using pip. This can be done alongside Celery to allow for incremental migration. ```bash pip install hatchet-sdk ``` -------------------------------- ### Start Python Worker Source: https://docs.hatchet.run/cookbooks/hatchet-openai-agents-sdk-trusted-env Navigate to the Python SDK directory and start the worker process using Poetry. ```bash cd sdks/python poetry run python -m examples.support_agent_tools.worker ``` -------------------------------- ### Register and Start Hatchet Worker (TypeScript) Source: https://docs.hatchet.run/llms-full.txt Notes that in TypeScript, workflows are registered through the shared example worker, not a per-example registration file. ```typescript In TypeScript, workflows are registered through the shared example worker rather than a per-example registration file. ``` -------------------------------- ### Install Hatchet CLI Natively Source: https://docs.hatchet.run/llms-full.txt Use this command to install the Hatchet CLI on MacOS, Linux, or WSL. This is the recommended installation method. ```bash curl -fsSL https://install.hatchet.run/install.sh | bash ``` -------------------------------- ### Start Hatchet Locally Source: https://docs.hatchet.run/reference/cli/running-hatchet-locally Run this command to start a local Hatchet instance using Docker. It automatically sets up PostgreSQL and the Hatchet server. ```bash hatchet server start ``` -------------------------------- ### Install Hatchet CLI with Install Script Source: https://docs.hatchet.run/cli Use this command to install the Hatchet CLI on MacOS, Linux, or WSL. This is the recommended installation method. ```bash curl -fsSL https://install.hatchet.run/install.sh | bash ``` -------------------------------- ### Install Hatchet SDK with OpenTelemetry Extra Source: https://docs.hatchet.run/llms-full.txt Install the Hatchet SDK with the 'otel' extra to enable OpenTelemetry support. This is a prerequisite for instrumenting your tasks. ```bash pip install hatchet-sdk[otel] ``` -------------------------------- ### Start ngrok for Webhook Exposure Source: https://docs.hatchet.run/llms-full.txt Starts ngrok to expose a local port to the internet, enabling the reception of incoming webhooks from Github. ```sh task start-ngrok ``` -------------------------------- ### Basic Hatchet Worker with EmptyModel Input Source: https://docs.hatchet.run/reference/python/pydantic This example demonstrates a basic Hatchet worker setup using `EmptyModel` for task inputs. It includes both a standard task and a durable task. The `EmptyModel` allows any input without validation errors due to `extra='allow'`. ```python from hatchet_sdk import Context, DurableContext, EmptyModel, Hatchet hatchet = Hatchet() @hatchet.task() def simple(input: EmptyModel, ctx: Context) -> dict[str, str]: return {"result": "Hello, world!"} @hatchet.durable_task() async def simple_durable(input: EmptyModel, ctx: DurableContext) -> dict[str, str]: # durable tasks should be async return {"result": "Hello, world!"} def main() -> None: worker = hatchet.worker( "test-worker", workflows=[simple, simple_durable], ) worker.start() ``` -------------------------------- ### Register and Start Worker (Python) Source: https://docs.hatchet.run/cookbooks/hatchet-and-mcp Sets up and starts a Hatchet worker, registering specified workflows and tasks for execution. ```python from examples.agent.workflows import ( hatchet, get_temperature_workflow, get_temperature_standalone, ) def main() -> None: worker = hatchet.worker( "test-worker", workflows=[get_temperature_workflow, get_temperature_standalone] ) worker.start() if __name__ == "__main__": main() ``` ```python from examples.agent.workflows import ( hatchet, get_temperature_workflow, get_temperature_standalone, ) def main() -> None: worker = hatchet.worker( "test-worker", workflows=[get_temperature_workflow, get_temperature_standalone] ) worker.start() if __name__ == "__main__": main() ``` -------------------------------- ### Install Hatchet Docs MCP Source: https://docs.hatchet.run/llms-full.txt Installs Hatchet documentation for AI coding assistants. Use `claude-code` for Claude Code. ```sh hatchet docs install ``` ```sh hatchet docs install claude-code ``` -------------------------------- ### Install Zod and OpenAI Agents SDK for TypeScript Source: https://docs.hatchet.run/llms-full.txt Install Zod v4 and the OpenAI Agents SDK for TypeScript agent integration. ```bash npm install zod@^4.0.0 npm install @openai/agents ``` -------------------------------- ### Install System Dependencies for Native Gems Source: https://docs.hatchet.run/llms-full.txt Installs build-essential for native gem compilation in a Dockerfile. Cleans up apt cache afterwards. ```dockerfile RUN apt-get update && \ apt-get install -y build-essential && \ apt-get clean && \ rm -rf /var/lib/apt/lists/\* ``` -------------------------------- ### Start Hatchet with Custom Ports and Project Name Source: https://docs.hatchet.run/reference/cli/running-hatchet-locally Starts the local Hatchet server with custom ports for the dashboard and gRPC, and assigns a specific project name to the Docker containers. ```bash hatchet server start --dashboard-port 9000 --grpc-port 8077 --project-name my-hatchet ``` -------------------------------- ### Register and Start Hatchet Worker (Python) Source: https://docs.hatchet.run/cookbooks/welcome-email Registers the 'welcome-email-worker' and starts it, making it ready to process workflows. Ensure the 'welcome_email' workflow is imported and available. ```python def main() -> None: worker = hatchet.worker("welcome-email-worker", workflows=[welcome_email]) worker.start() if __name__ == "__main__": main() ``` -------------------------------- ### Trigger Welcome Email Workflow (Python) Source: https://docs.hatchet.run/cookbooks/welcome-email Starts the 'welcome-email' workflow with signup details and pushes an 'onboarding-completed' event. It then waits for the workflow to finish and prints the result. Requires 'SignupInput', 'hatchet', and the 'welcome_email' workflow to be imported. ```python from examples.welcome_email.worker import ( ONBOARDING_EVENT_KEY, SignupInput, hatchet, welcome_email, ) signup = SignupInput( email="alice@example.com", user_id="user-123", ) # Start the welcome-email workflow ref = welcome_email.run(signup, wait_for_result=False) print(f"Started workflow run: {ref.workflow_run_id}") # Push onboarding-completed event (scoped to this user) print("Pushing onboarding-completed event...") hatchet.event.push( ONBOARDING_EVENT_KEY, {"status": "done"}, scope=signup.user_id, ) # Wait for the workflow to complete result = ref.result() print(f"Workflow completed: {result}") ``` -------------------------------- ### Minimal Local Development Configuration Source: https://docs.hatchet.run/self-hosting/configuration-options A minimal configuration example for local development, connecting to a local PostgreSQL instance and using file-based encryption keys. Recommended for development environments. ```bash # Database DATABASE_URL='postgresql://hatchet:hatchet@127.0.0.1:5431/hatchet' # Encryption (using key files - recommended for development) SERVER_ENCRYPTION_MASTER_KEYSET_FILE=./keys/master.key SERVER_ENCRYPTION_JWT_PRIVATE_KEYSET_FILE=./keys/private_ec256.key SERVER_ENCRYPTION_JWT_PUBLIC_KEYSET_FILE=./keys/public_ec256.key # Authentication SERVER_AUTH_COOKIE_SECRETS="your-secret-key-1 your-secret-key-2" SERVER_AUTH_SET_EMAIL_VERIFIED=true # Basic server config SERVER_PORT=8080 SERVER_URL=http://localhost:8080 # Development settings (optional but recommended) SERVER_GRPC_INSECURE=true SERVER_INTERNAL_CLIENT_BASE_STRATEGY=none SERVER_LOGGER_LEVEL=error SERVER_LOGGER_FORMAT=console DATABASE_LOGGER_LEVEL=error DATABASE_LOGGER_FORMAT=console ``` -------------------------------- ### Run Claude Agent SDK Example Source: https://docs.hatchet.run/cookbooks/hatchet-claude-agent-sdk-trusted-env This example demonstrates how to set up and run a query using the Claude Agent SDK. It includes tool definitions, MCP server creation, and asynchronous message handling. Ensure you are using an ESM-compatible TypeScript runner. ```typescript import { createLookupCustomerToolClaude, createCheckOrderStatusToolClaude, createTicketToolClaude, } from './tools'; async function main() { const lookupCustomerTool = createLookupCustomerToolClaude(); const checkOrderStatusTool = createCheckOrderStatusToolClaude(); const ticketTool = createTicketToolClaude(); // The Claude Agent SDK is ESM-only, so avoid loading it at module import time. // Run this example with an ESM-compatible TypeScript runner. const { query, createSdkMcpServer } = await import('@anthropic-ai/claude-agent-sdk'); // Wrap the tools in an in-process MCP server const supportServer = createSdkMcpServer({ name: 'support', version: '1.0.0', tools: [lookupCustomerTool, checkOrderStatusTool, ticketTool], }); for await (const message of query({ prompt: 'Customer C-100 says order ORD-9987 has not arrived. ' + 'Look up the customer, check the order status, and create a ' + 'support ticket if the order has a known issue or delayed delivery. ' + 'If you create a ticket, use priority "high", subject ' + '"Delayed order ORD-9987", and a body that summarizes the known ' + 'carrier delay. Then summarize what happened.', options: { mcpServers: { support: supportServer }, allowedTools: [ `mcp__${supportServer.name}__${lookupCustomerTool.name}`, `mcp__${supportServer.name}__${checkOrderStatusTool.name}`, `mcp__${supportServer.name}__${ticketTool.name}`, ], }, })) { // "result" is the final message after all tool calls complete if (message.type === 'result' && message.subtype === 'success') { console.log(message.result); } } } if (require.main === module) { main() .catch(console.error) .finally(() => { process.exit(0); }); } ``` -------------------------------- ### Hatchet Worker Configuration (Typescript) Source: https://docs.hatchet.run/llms-full.txt Configuration for running a Typescript worker locally. Ensure 'pnpm install' is run before starting the worker. Auto-reload is enabled by default. ```yaml dev: preCmds: ["pnpm install"] runCmd: "pnpm start" files: - "**/*.ts" - "!**/node_modules/**" reload: true ``` -------------------------------- ### Enabling Setup Job for Secrets Source: https://docs.hatchet.run/self-hosting/kubernetes-helm-configuration Configuration to enable the `quickstartJob`, which bootstraps encryption and authentication secrets into a Kubernetes Secret named `hatchet-config`. ```yaml quickstartJob: enabled: true ``` -------------------------------- ### Hatchet Worker Configuration (Python) Source: https://docs.hatchet.run/llms-full.txt Configuration for running a Python worker locally. Ensure 'poetry install' is run before starting the worker. Auto-reload is enabled by default. ```yaml dev: preCmds: ["poetry install"] runCmd: "poetry run python src/worker.py" files: - "**/*.py" - "!**/__pycache__/**" - "!**/.venv/**" reload: true ``` -------------------------------- ### TypeScript Agent Run Command Source: https://docs.hatchet.run/llms-full.txt Command to run the TypeScript Claude agent for the support agent tools example. Ensure you are in the 'sdks/typescript' directory and have pnpm installed. ```bash cd sdks/typescript pnpm exec tsx -r tsconfig-paths/register src/v1/examples/support_agent_tools/agent-claude.ts ``` -------------------------------- ### Run Agent Example (TypeScript - Claude/OpenAI) Source: https://docs.hatchet.run/llms-full.txt Execute TypeScript agent examples that utilize Hatchet tools. Ensure the required provider SDKs and API keys (e.g., ANTHROPIC_API_KEY or OPENAI_API_KEY) are set up. ```bash cd sdks/typescript pnpm exec tsx -r tsconfig-paths/register src/v1/examples/agent/agent-claude.ts # or pnpm exec tsx -r tsconfig-paths/register src/v1/examples/agent/agent-openai.ts ``` -------------------------------- ### Go Dockerfile (Multi-stage) Source: https://docs.hatchet.run/llms-full.txt This multi-stage Dockerfile builds a Go application. The first stage downloads Go modules and builds the binary. The second stage copies the compiled binary into a lean Alpine Linux image for production. ```dockerfile # Stage 1: Build FROM golang:1.26-alpine3.21 AS builder WORKDIR /app COPY . . RUN go mod download RUN go build -o hatchet-worker . # Stage 2: Production FROM golang:1.26-alpine3.21 WORKDIR /app COPY --from=builder hatchet-worker . CMD ["/app/hatchet-worker"] ``` -------------------------------- ### TypeScript Worker Configuration Source: https://docs.hatchet.run/cli/running-workers-locally Configure a TypeScript worker for local development. Use `preCmds` for setup and `runCmd` to start the worker. Includes file watching and auto-reload. ```yaml dev: preCmds: ["pnpm install"] runCmd: "pnpm start" files: - "**/*.ts" - "!**/node_modules/**" reload: true ``` -------------------------------- ### Python Worker Configuration Source: https://docs.hatchet.run/cli/running-workers-locally Configure a Python worker for local development. Use `preCmds` for setup and `runCmd` to start the worker. Includes file watching and auto-reload. ```yaml dev: preCmds: ["poetry install"] runCmd: "poetry run python src/worker.py" files: - "**/*.py" - "!**/__pycache__/**" - "!**/.venv/**" reload: true ``` -------------------------------- ### Run Streaming Workflow with Go HTTP Server Source: https://docs.hatchet.run/llms-full.txt Example of running a streaming workflow using Go's built-in HTTP server. This includes client initialization, setting up the HTTP handler, and streaming content. ```go func main() { client, err := hatchet.NewClient() if err != nil { log.Fatalf("Failed to create Hatchet client: %v", err) } streamingWorkflow := shared.StreamingWorkflow(client) http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) { ctx := context.Background() w.Header().Set("Content-Type", "text/plain") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") workflowRun, err := streamingWorkflow.RunNoWait(ctx, shared.StreamTaskInput{}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } stream := client.Runs().SubscribeToStream(ctx, workflowRun.RunId) flusher, _ := w.(http.Flusher) for content := range stream { fmt.Fprint(w, content) if flusher != nil { flusher.Flush() } } }) server := &http.Server{ Addr: ":8000", ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } if err := server.ListenAndServe(); err != nil { log.Println("Failed to start server:", err) } } ``` -------------------------------- ### Register Worker with Labels (Ruby) Source: https://docs.hatchet.run/llms-full.txt Defines and starts a Hatchet worker, assigning it labels for 'model' and 'memory'. This Ruby example sets up a worker that can be targeted by tasks based on these defined characteristics. ```ruby def main worker = HATCHET.worker( "affinity-worker", slots: 10, labels: { "model" => "fancy-ai-model-v2", "memory" => 512 }, workflows: [AFFINITY_WORKER_WORKFLOW] ) worker.start end ``` -------------------------------- ### Create and Run Support Agent with OpenAI Tools (Python) Source: https://docs.hatchet.run/cookbooks/hatchet-openai-agents-sdk-trusted-env This Python script initializes a support agent with tools for looking up customers, checking order status, and creating tickets. It then runs the agent with a specific customer query and prints the final output. ```python import asyncio from agents import Agent, Runner from examples.support_agent_tools.tools import ( create_lookup_customer_tool_openai, create_check_order_status_tool_openai, create_ticket_tool_openai, ) async def main() -> None: lookup_customer_tool = create_lookup_customer_tool_openai() check_order_status_tool = create_check_order_status_tool_openai() ticket_tool = create_ticket_tool_openai() agent = Agent( name="support-agent", tools=[lookup_customer_tool, check_order_status_tool, ticket_tool], ) result = await Runner.run( agent, "Customer C-100 says order ORD-9987 has not arrived. " "Look up the customer, check the order status, and create a " "support ticket if the order has a known issue or delayed delivery. " 'If you create a ticket, use priority \"high\", subject ' '"Delayed order ORD-9987", and a body that summarizes the known ' "carrier delay. Then summarize what happened.", ) print(result.final_output) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Ruby: Wait for Sleep or Event Source: https://docs.hatchet.run/home/conditional-workflows This Ruby example sets up a task that will proceed after 60 seconds or upon receiving a user event with the key 'wait_for_event:start'. It's designed for scenarios where a task needs to wait for either a timeout or an external trigger. ```ruby WAIT_FOR_EVENT = TASK_CONDITION_WORKFLOW.task( :wait_for_event, parents: [COND_START], wait_for: [ Hatchet.or_( Hatchet::SleepCondition.new(60), Hatchet::UserEventCondition.new(event_key: "wait_for_event:start") ) ] ) do |input, ctx| { "random_number" => rand(1..100) } end ``` -------------------------------- ### Initialize S3 Client (Python) Source: https://docs.hatchet.run/cookbooks/workflow-aws-s3 Initializes an S3 client in Python using boto3. AWS credentials should be configured via environment variables. ```python s3 = boto3.client("s3") ``` -------------------------------- ### get Source: https://docs.hatchet.run/reference/python/feature-clients/webhooks Get a webhook by its name. ```APIDOC ## get ### Description Get a webhook by its name. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **webhook_name** (str) - Required - The name of the webhook to retrieve. ### Request Example ```json { "webhook_name": "my_webhook" } ``` ### Response #### Success Response (200) - **V1Webhook** - The webhook with the specified name. #### Response Example ```json { "id": "whk_12345", "source_name": "example_source", "name": "my_webhook", "event_key_expression": "payload.id", "auth": { "type": "basic", "username": "user" }, "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### Define and Run a Standalone Task in Go Source: https://docs.hatchet.run/llms-full.txt Shows how to create a Hatchet client, define a standalone task with input and output types, and then run it. ```go package main import ( "context" "fmt" "log" hatchet "github.com/hatchet-dev/hatchet/sdks/go" ) type StubInput struct { Message string `json:"message"` } type StubOutput struct { Ok bool `json:"ok"` } func StubWorkflow(client *hatchet.Client) *hatchet.StandaloneTask { return client.NewStandaloneTask("stub-workflow", func(ctx hatchet.Context, input StubInput) (StubOutput, error) { return StubOutput{ Ok: true, }, nil }) } func main() { client, err := hatchet.NewClient() if err != nil { log.Fatalf("failed to create hatchet client: %v", err) } task := StubWorkflow(client) // we are simply running the task here, but it can be implemented in another service / worker // and in another language with the same name and input-output types result, err := task.Run(context.Background(), StubInput{Message: "Hello, World!"}) if err != nil { log.Fatalf("failed to run task: %v", err) } fmt.Println(result) } ``` -------------------------------- ### get Source: https://docs.hatchet.run/reference/python/feature-clients/workflows Get a workflow by its ID. ```APIDOC ## get ### Description Get a workflow by its ID. ### Parameters #### Path Parameters - **workflow_id** (str) - Required - The ID of the workflow to retrieve. ### Returns - **Workflow** - The workflow. ``` -------------------------------- ### Create and Use a Task Stub in Python Source: https://docs.hatchet.run/llms-full.txt Illustrates creating a task stub that matches the implementation's name and schemas, and then using it to trigger the task asynchronously. ```python stub = hatchet.stubs.task( # make sure the name and schemas exactly match the implementation name="externally-triggered-task", input_validator=TaskInput, output_validator=TaskOutput, ) # input type checks properly result = await stub.aio_run(input=TaskInput(user_id=1234)) # `result.ok` type checks properly print("Is successful:", result.ok) ``` -------------------------------- ### Verify Hatchet CLI Installation Source: https://docs.hatchet.run/cli Run this command after installation to confirm that the Hatchet CLI is installed correctly and to check its version. ```bash hatchet --version ``` -------------------------------- ### Install Hatchet CLI with Homebrew Source: https://docs.hatchet.run/cli Install the Hatchet CLI on MacOS using Homebrew. Ensure you have Homebrew installed before running this command. ```bash brew install hatchet-dev/hatchet/hatchet --cask ``` -------------------------------- ### Python Claude Agent SDK with MCP Server Source: https://docs.hatchet.run/cookbooks/hatchet-claude-agent-sdk-trusted-env This Python snippet demonstrates setting up an agent process that hosts Hatchet-backed tools, groups them into an MCP server, and passes this server to the Claude Agent SDK. It configures allowed tools and queries Claude with a prompt that requires tool usage. ```python import asyncio from claude_agent_sdk import ( create_sdk_mcp_server, ClaudeAgentOptions, query, ResultMessage, ) from examples.support_agent_tools.tools import ( create_lookup_customer_tool_claude, create_check_order_status_tool_claude, create_ticket_tool_claude, ) async def main() -> None: lookup_customer_tool = create_lookup_customer_tool_claude() check_order_status_tool = create_check_order_status_tool_claude() ticket_tool = create_ticket_tool_claude() support_server = create_sdk_mcp_server( name="support", version="1.0.0", tools=[lookup_customer_tool, check_order_status_tool, ticket_tool], ) server_name = support_server["name"] options = ClaudeAgentOptions( mcp_servers={"support": support_server}, allowed_tools=[ f"mcp__{server_name}__{lookup_customer_tool.name}", f"mcp__{server_name}__{check_order_status_tool.name}", f"mcp__{server_name}__{ticket_tool.name}", ], ) async for message in query( prompt=( "Customer C-100 says order ORD-9987 has not arrived. " "Look up the customer, check the order status, and create a " "support ticket if the order has a known issue or delayed delivery. " 'If you create a ticket, use priority "high", subject ' '"Delayed order ORD-9987", and a body that summarizes the known ' "carrier delay. Then summarize what happened." ), options=options, ): print(message) if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### get Source: https://docs.hatchet.run/reference/python/feature-clients/runs Get workflow run details for a given workflow run ID. ```APIDOC ## get ### Description Get workflow run details for a given workflow run ID. ### Parameters #### Path Parameters - **workflow_run_id** (str) - Required - The ID of the workflow run to retrieve details for. ### Returns - **V1WorkflowRunDetails** - Workflow run details for the specified workflow run ID. ``` -------------------------------- ### Start Celery Worker Source: https://docs.hatchet.run/llms-full.txt Use this command to start a Celery worker from the CLI. ```bash celery -A tasks worker --loglevel=info --concurrency=4 ``` -------------------------------- ### Celery Group Example Source: https://docs.hatchet.run/llms-full.txt This is an example of a Celery group, which runs multiple tasks in parallel. ```python from celery import group checks = group( check_inventory.s(order_id), check_fraud.s(order_id), ) checks.apply_async() ``` -------------------------------- ### Python Claude Agent with Support Tools Source: https://docs.hatchet.run/llms-full.txt This Python snippet demonstrates how to create an MCP server with support tools (lookup customer, check order status, create ticket) and query the Claude agent with a prompt to handle a customer's delayed order. ```python import asyncio from claude_agent_sdk import ( create_sdk_mcp_server, ClaudeAgentOptions, query, ResultMessage, ) from examples.support_agent_tools.tools import ( create_lookup_customer_tool_claude, create_check_order_status_tool_claude, create_ticket_tool_claude, ) async def main() -> None: lookup_customer_tool = create_lookup_customer_tool_claude() check_order_status_tool = create_check_order_status_tool_claude() ticket_tool = create_ticket_tool_claude() support_server = create_sdk_mcp_server( name="support", version="1.0.0", tools=[lookup_customer_tool, check_order_status_tool, ticket_tool], ) server_name = support_server["name"] options = ClaudeAgentOptions( mcp_servers={"support": support_server}, allowed_tools=[ f"mcp__{server_name}__{lookup_customer_tool.name}", f"mcp__{server_name}__{check_order_status_tool.name}", f"mcp__{server_name}__{ticket_tool.name}", ], ) async for message in query( prompt=( "Customer C-100 says order ORD-9987 has not arrived. " "Look up the customer, check the order status, and create a " "support ticket if the order has a known issue or delayed delivery. " 'If you create a ticket, use priority "high", subject ' '"Delayed order ORD-9987", and a body that summarizes the known ' "carrier delay. Then summarize what happened." ), options=options, ): print(message) if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Push Events in Bulk (Go) Source: https://docs.hatchet.run/llms-full.txt Demonstrates how to create a Hatchet client and push multiple events in a single request. Note the maximum limit of 1000 events per request. ```go c, err := client.New( client.WithHostPort("127.0.0.1", 7077), ) if err != nil { panic(err) } events := []client.EventWithMetadata{ { Event: &events.TestEvent{ Name: "testing", }, AdditionalMetadata: map[string]string{"hello": "world1"}, Key: "user:create", }, { Event: &events.TestEvent{ Name: "testing2", }, AdditionalMetadata: map[string]string{"hello": "world2"}, Key: "user:create", }, } c.Event().BulkPush( context.Background(), events, ) ``` -------------------------------- ### Run Child Workflow with Sticky Strategy (Go) Source: https://docs.hatchet.run/llms-full.txt Runs a child workflow on the same worker using a sticky strategy. This Go example demonstrates how to configure the child workflow run to maintain affinity with the parent worker. ```go func Sticky(client *hatchet.Client) *hatchet.StandaloneTask { sticky := client.NewStandaloneTask("sticky-task", func(ctx worker.HatchetContext, input StickyInput) (*StickyResult, error) { // Run a child workflow on the same worker childWorkflow := Child(client) childResult, err := childWorkflow.Run(ctx, ChildInput{N: 1}, hatchet.WithRunSticky(true)) if err != nil { return nil, err } var childOutput ChildResult err = childResult.Into(&childOutput) if err != nil { return nil, err } return &StickyResult{ Result: fmt.Sprintf("child-result-%s", childOutput.Result), }, }, ) return sticky } ``` -------------------------------- ### Trigger Welcome Email Workflow (TypeScript) Source: https://docs.hatchet.run/cookbooks/welcome-email Initiates the 'welcomeEmail' workflow without waiting for immediate completion, logs the run ID, pushes a scoped 'onboarding-completed' event, and then retrieves the final workflow output. Ensure 'hatchet-client', 'workflow', and 'SignupInput' are imported. ```typescript import { hatchet } from '../hatchet-client'; import { welcomeEmail, ONBOARDING_EVENT_KEY, SignupInput } from './workflow'; async function main() { const input: SignupInput = { email: 'alice@example.com', user_id: 'user-123', }; // Start the welcome-email workflow const ref = await welcomeEmail.runNoWait(input); const runId = await ref.getWorkflowRunId(); console.log(`Started workflow run: ${runId}`); // Push onboarding-completed event (scoped to this user) console.log('Pushing onboarding-completed event...'); await hatchet.events.push(ONBOARDING_EVENT_KEY, { status: 'done' }, { scope: input.user_id }); // Wait for the workflow to complete const result = await ref.output; console.log('Workflow completed:', result); } ``` -------------------------------- ### Start TypeScript Worker Source: https://docs.hatchet.run/cookbooks/hatchet-openai-agents-sdk-trusted-env Navigate to the TypeScript SDK directory and start the worker process using PNPM and tsx. ```bash cd sdks/typescript pnpm exec tsx -r tsconfig-paths/register src/v1/examples/support_agent_tools/worker.ts ``` -------------------------------- ### Register and Start Worker (TypeScript) Source: https://docs.hatchet.run/cookbooks/hatchet-and-mcp Sets up and starts a Hatchet worker, registering specified workflows and tasks for execution. ```typescript import { hatchet } from '../hatchet-client'; import { getTemperature, getTemperatureWorkflow } from './workflow'; async function main() { const worker = await hatchet.worker('temperature-worker', { workflows: [getTemperature, getTemperatureWorkflow], }); await worker.start(); } if (require.main === module) { main(); } ``` ```typescript import { hatchet } from '../hatchet-client'; import { getTemperature, getTemperatureWorkflow } from './workflow'; async function main() { const worker = await hatchet.worker('temperature-worker', { workflows: [getTemperature, getTemperatureWorkflow], }); await worker.start(); } if (require.main === module) { main(); } ``` -------------------------------- ### Test Workflow Imports (Python) Source: https://docs.hatchet.run/llms-full.txt Verify that workflow definitions and helper functions can be imported successfully in Python without needing provider SDKs. This is a basic check for project setup. ```bash cd sdks/python poetry run python -c "from examples.agent.workflows import create_temperature_workflow_tool_claude, create_temperature_task_tool_claude; print('OK')" ``` -------------------------------- ### Install OpenTelemetry Packages for TypeScript Source: https://docs.hatchet.run/llms-full.txt Install the necessary OpenTelemetry packages for your TypeScript project. These are required before registering the Hatchet instrumentor. ```bash npm install @opentelemetry/api @opentelemetry/instrumentation @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-grpc ``` -------------------------------- ### Run Hatchet Lite with Postgres Source: https://docs.hatchet.run/self-hosting/hatchet-lite After saving the `docker-compose.hatchet.yml` file for Postgres, use this command to start the Hatchet Lite instance. ```bash docker-compose -f docker-compose.hatchet.yml up ``` -------------------------------- ### Initialize Hatchet Client and List Workflows (Python) Source: https://docs.hatchet.run/llms-full.txt Initializes the Hatchet client and retrieves a list of workflows. This is a prerequisite for fetching task runs. ```python from datetime import datetime, timedelta, timezone from hatchet_sdk import BulkCancelReplayOpts, Hatchet, RunFilter, V1TaskStatus hatchet = Hatchet() workflows = hatchet.workflows.list() assert workflows.rows workflow = workflows.rows[0] ``` -------------------------------- ### Get a Filter Source: https://docs.hatchet.run/llms-full.txt Retrieve a specific filter by providing its ID to the `get` method. The method returns the requested filter object. ```typescript await hatchet.filters.get("filter-id"); ``` -------------------------------- ### Go: Multiple Concurrency Strategies Source: https://docs.hatchet.run/llms-full.txt Implement a standalone task in Go that utilizes multiple concurrency strategies. This example demonstrates setting a `GroupRoundRobin` strategy with a maximum number of runs for two different input expressions. ```go strategy := types.GroupRoundRobin var maxRuns int32 = 20 return client.NewStandaloneTask("multi-concurrency", func(ctx worker.HatchetContext, input ConcurrencyInput) (*TransformedOutput, error) { // Random sleep between 200ms and 1000ms time.Sleep(time.Duration(200+rand.Intn(800)) * time.Millisecond) return &TransformedOutput{ TransformedMessage: input.Message, }, }, hatchet.WithWorkflowConcurrency( types.Concurrency{ Expression: "input.Tier", MaxRuns: &maxRuns, LimitStrategy: &strategy, }, types.Concurrency{ Expression: "input.Account", MaxRuns: &maxRuns, LimitStrategy: &strategy, }, ), ) ``` -------------------------------- ### RatelimitsClient.list() Source: https://docs.hatchet.run/llms-full.txt Lists all rate limits for the current tenant. ```APIDOC ## RatelimitsClient.list() ### Description Lists all rate limits for the current tenant. ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of rate limits to return. - **offset** (number) - Optional - The number of rate limits to skip. - **orderByDirection** (RateLimitOrderByDirection) - Optional - The direction to order the results. - **orderByField** (RateLimitOrderByField) - Optional - The field to order the results by. - **search** (string) - Optional - A search string to filter rate limits. ### Returns `Promise` - A promise that resolves to the list of rate limits. ``` -------------------------------- ### Define and Run Hatchet Workflows in TypeScript Source: https://docs.hatchet.run/llms-full.txt Demonstrates how to define a simple workflow with input and output types, and then run it using various methods like run, runNoWait, schedule, and cron. ```typescript import { hatchet } from '../hatchet-client'; // (optional) Define the input type for the workflow export type SimpleInput = { Message: string; }; // (optional) Define the output type for the workflow export type SimpleOutput = { 'to-lower': { TransformedMessage: string; }; }; // declare the workflow with the same name as the // workflow name on the worker export const simple = hatchet.workflow({ name: 'simple', }); // you can use all the same run methods on the stub // with full type-safety simple.run({ Message: 'Hello, World!' }); simple.runNoWait({ Message: 'Hello, World!' }); simple.schedule(new Date(), { Message: 'Hello, World!' }); simple.cron('my-cron', '0 0 * * *', { Message: 'Hello, World!' }); ``` -------------------------------- ### Pushing a Simple Event in Go Source: https://docs.hatchet.run/llms-full.txt Shows how to push an event with a skip flag and scope in Go. Requires a Hatchet client and a specific event key format. ```go triggerPayload := map[string]interface{}{ "shouldSkip": false, } triggerScope := "foobarbaz" err = client.Events().Push( context.Background(), "simple-event:create", triggerPayload, v0Client.WithFilterScope(&triggerScope), ) if err != nil { return err } ```