AI School Pakistan
← Applied AI Builder0 of 18 complete
LessonCourse overview

Module 6 · Prepare the Capstone for Review · 45 min

Prepare Deployment, Logging, and Monitoring for an AI Workflow

Lesson 16 of 18

Is lesson ke baad tum

Shipping means making the workflow controllable after launch: version it, observe it, limit it, rehearse failures, and give operators a safe way to recover.

In this lesson

Prepare an Operations Review

Prepare a workflow for an operations review by testing a small log boundary and making a release decision from supplied observations. The core runs locally with Node. Deployment accounts, credentials, hosting charges, and a public release are outside this exercise.

A reachable URL does not establish that a workflow can be operated safely. Operators need versioned behavior, durable state, bounded work, useful logs, actionable alerts, and a tested recovery path. You will mark untested controls honestly rather than imply they exist.

Draw the production path

A typical path is client → authenticated API → bounded queue → worker → durable state → human review. Retrieval adds a permission-scoped knowledge store. Logs and metrics observe transitions without collecting full private records.

Keep state outside a single API process. Limit concurrency when a provider slows down instead of launching unlimited calls. Development, staging, and production need separate authorized credentials and limits; a synthetic local lab establishes none of those environments. Store workflow, schema, prompt, model configuration, and source versions so rollback can restore a compatible set.

Worked build: a lead-intake drafting workflow

A training company receives course enquiries through a form. The workflow validates consent and contact fields, retrieves current course facts, classifies the requested topic, drafts a response with citations, and queues it for staff review. It never invents seats, discounts, earnings, or admissions decisions.

The synchronous API can return 202 Accepted with a job ID, while a worker performs retrieval and drafting. A status endpoint returns QUEUED, RUNNING, AWAITING_REVIEW, COMPLETE, or a safe error. If the provider is temporarily unavailable, the job waits and retries within a defined budget. If the knowledge base is stale, it escalates rather than drafting.

Use structured events instead of scattered prose logs. This runnable JavaScript helper emits one JSON object per line:

javascript40 lines
function logEvent(event, fields = {}) {
  if (!fields || typeof fields !== "object" || Array.isArray(fields)) throw new Error("Invalid log fields");
  if (typeof event !== "string" || !/^[a-z]+(?:[._-][a-z]+)*$/.test(event)) {
    throw new Error("Invalid event name");
  }
  const allowed = new Set([
    "requestId", "state", "latencyMs", "toolCalls", "citationCount",
    "retryCount", "errorClass"
  ]);
  const safe = {};
  const states = new Set(["QUEUED", "RUNNING", "AWAITING_REVIEW", "COMPLETE", "FAILED"]);
  const errors = new Set(["RATE_LIMIT", "PROVIDER", "VALIDATION", "UNKNOWN"]);
  for (const [key, value] of Object.entries(fields)) {
    if (!allowed.has(key)) continue;
    const valid = key === "requestId" ? typeof value === "string" && /^req_[a-z0-9_]{1,40}$/.test(value)
      : key === "state" ? states.has(value)
      : key === "errorClass" ? errors.has(value)
      : Number.isSafeInteger(value) && value >= 0 && value <= 1_000_000_000;
    if (!valid) throw new Error(`Invalid log field: ${key}`);
    safe[key] = value;
  }
  const version = process.env.WORKFLOW_VERSION ?? "dev";
  if (!/^[a-zA-Z0-9._-]{1,40}$/.test(version)) throw new Error("Invalid workflow version");

  process.stdout.write(JSON.stringify({
    ...safe,
    timestamp: new Date().toISOString(),
    event,
    service: "lead-drafter",
    workflowVersion: version,
  }) + "\n");
}

logEvent("workflow.awaiting_review", {
  requestId: "req_demo_123",
  state: "AWAITING_REVIEW",
  latencyMs: 842,
  toolCalls: 1,
  citationCount: 2,
});

This example validates a small flat schema, but an ID or version can still encode sensitive information if callers choose it badly. Use server-generated opaque IDs and approved version labels; do not use this helper as a general-purpose redactor. Restrict log access and retention, and test the real paths that emit events. The reserved envelope fields are written last so caller data cannot replace the event name, timestamp, service, or workflow version. Generate opaque request IDs rather than putting email addresses or phone numbers in identifiers.

What to log and measure

For each run, record:

  • request, job, and trace IDs;
  • environment and workflow version;
  • model configuration identifier and prompt version, not secret contents;
  • source/index version and retrieved source IDs;
  • state transitions and durations;
  • tool name, sanitized argument summary, status, latency, and retry count;
  • approval event and payload version;
  • input/output token counts or provider usage fields;
  • final state, abstention reason, and error class.

Metrics aggregate behaviour: request rate, queue depth, completion and error rate, retry rate, tail latency, citation support, approval wait time, token usage, cost per completed task, and blocked safety events. Break them down by workflow version and important user path without creating unnecessary personal profiles.

Define service-level objectives that reflect the product. Example: “99% of accepted jobs reach a final or review state within five minutes over 30 days” is more useful than “server up 99%.” Add quality objectives such as citation support or correct abstention, checked through sampled reviews and automated evals.

Alerts need a response

Alert only when someone can act. Each alert should name severity, threshold, owner, first diagnostic query, containment action, and escalation path. Useful alerts include:

  • queue age exceeds the target;
  • error or retry rate jumps after a deployment;
  • completion cost rises sharply;
  • citation coverage falls after re-indexing;
  • authorization blocks or prompt-injection detections spike;
  • no successful synthetic check has run recently;
  • spend or rate-limit thresholds approach a configured boundary.

Provide a kill switch that disables risky tools or new requests while preserving evidence for investigation. For a read-only assistant, degraded mode might return approved static contact information. For a write workflow, fail closed rather than executing without validation.

Release, rollback, and maintenance

Use a deployment checklist:

  1. Automated unit, integration, retrieval, and eval suites pass.
  2. Threat-model controls and secret scanning pass.
  3. Database and index migrations have rollback or forward-recovery plans.
  4. Staging smoke tests use realistic synthetic inputs.
  5. A canary or small traffic slice receives the new workflow version.
  6. Operators compare quality, failure, latency, and cost metrics.
  7. Promotion or rollback is explicit and recorded.

Keep prompts and schemas under version control. Pin dependency versions, monitor deprecations, and schedule source-freshness reviews. Rotate credentials and remove former team access. Test restores from backup. Review alerts and dead-letter jobs. Update the runbook after every incident; otherwise the same failure remains tribal knowledge.

OpenAI's production guidance recommends securing API keys outside code, separating staging and production projects, planning for rate limits, and monitoring usage. Current deployment and error guides should be consulted at implementation time because limits and platform details can change.

Failure cases to rehearse

  • The provider returns rate limits during a marketing spike.

  • A deployment changes output schema while an old worker still runs.

  • The API times out but a queued job continues, so the client submits twice.

  • Retrieval indexing lags behind a newly approved policy.

  • Logs contain full enquiry text and phone numbers.

  • A model or tool dependency becomes unavailable.

  • A queue grows for hours without an alert on job age.

  • A prompt change improves style but harms citation support.

  • Rollback restores application code but not the matching source index or schema.

  • One region or network route fails while a simple uptime probe remains green.

Hands-on deliverable

Save the supplied logger as log-lab.mjs and run it. Expect one JSON line with the listed metadata and no message text. Add customerPhone: "03000000000" and prompt: "synthetic private text" to the call: those unknown fields must be absent. Then set state to an object; expect an error before that event is logged. Restore the valid state.

Next review this fictional canary report. The agreed exercise gates are zero private log fields, citation support at least 95%, oldest accepted job below five minutes, and matching application/schema/source versions.

ObservationValueDecision
Private fields in sampled logs0passes this sample
Supported cited claims18 of 2090%, fails 95% gate
Oldest accepted job7 minutesfails five-minute gate
Versionsapp v2/schema 2/source index 1; app v2 expects index 2mismatch

Write a no-promotion decision and one containment action: stop new canary intake, preserve existing job states/traces, and return traffic only to a previously tested compatible version set. Do not discard or blindly replay jobs that might have effects. Assign source-index diagnosis to the knowledge owner and queue/provider diagnosis to the operator.

Changed condition: citation support becomes 20/20 and the queue falls to 2 minutes, but the source index remains 1. Promotion is still blocked by compatibility. These are paper observations; no canary, rollback, queue, or uptime test has actually run.

Completion rubric

  • The valid logger emits one JSON event; unknown personal/prompt fields are absent and invalid allowed values are rejected.
  • You calculate 18/20 as 90% and identify both the queue and version failures.
  • The changed condition still blocks promotion because the index is incompatible.
  • Your decision preserves job evidence and labels deployment/recovery controls as untested.

Sources

Practice quiz

Check yourself

4 questions · practise what you just learned

0/4
  1. 1 / 4 · diagnose

    You add customerPhone and prompt fields to the valid logEvent call. What should the shown logger emit?

Apna kaam check karo.

Practice complete ki? Result ko example aur lesson ke checks se compare karo.

This is your own completion record, not a graded assessment.

Kuch samajh nahi aaya? Ask a question →