Skip to content

feat(customer-onboarding): add --json output flag (#169) - #242

Merged
Karan-Raj-KR merged 2 commits into
Karan-Raj-KR:mainfrom
Subodh-17:feat/issue-169-customer-onboarding-json
Oct 28, 2026
Merged

Karan-Raj-KR merged 2 commits into
Karan-Raj-KR:mainfrom
Subodh-17:feat/issue-169-customer-onboarding-json

Conversation

@Subodh-17

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds an optional --json output flag to the customer-onboarding recipe, mirroring the structured Pydantic output pattern established in recipes/lead-qualification. When --json is supplied, the terminal task formats and emits pure machine-readable JSON matching the newly defined CustomerOnboardingResult Pydantic model (CustomerProfile + OnboardingEmail).

Related issue

Closes #169

Type of change

  • Recipe improvement / bug fix
  • Documentation

Implementation & Architecture Details

  1. Pydantic Models (recipes/customer-onboarding/tasks.py):

    • Defined CustomerProfile: Captures customer signup signals (customer_name, company, role, use_case, team_size), audit status ("READY" or "INCOMPLETE"), completeness_score ("High", "Medium", or "Low"), and missing_fields list.
    • Defined OnboardingEmail: Captures the tailored outbound message (subject, body).
    • Defined CustomerOnboardingResult: Root container holding profile and email.
  2. Task & Crew Wiring (tasks.py, crew.py):

    • Threaded json_output: bool = False through build_crew(...) and build_tasks(...).
    • Wired output_pydantic=CustomerOnboardingResult if json_output else None to the terminal task (composer_task).
    • Dynamically adjusted expected_output and prompt guidelines on composer_task when structured output is requested.
    • Preserved default non-JSON behavior and full backward compatibility for programmatic callers (main.py, playground, tests).
  3. CLI & Machine-Readable Output (run.py):

    • Added --json command-line flag (action="store_true").
    • In JSON mode, decorative terminal banners (🚀, ═) and logging are suppressed so stdout contains strictly valid JSON parseable by jq and python -c 'import sys, json; json.load(sys.stdin)'.
    • Implemented format_json_output(result) with type-safe isinstance checks supporting BaseModel, CrewOutput (.pydantic, .json_dict, .json, .raw), dictionary representations, and markdown code fence stripping.
    • Missing configuration (check_env) and runtime execution errors emit structured {"error": "<msg>"} to stdout and exit with code 1.
  4. Testing (test_main.py):

    • Added 16 deterministic offline unit tests covering:
      • Default execution and backward compatibility.
      • Pydantic schema validation, serialization, and round-trip.
      • Incomplete profile handling (status="INCOMPLETE", missing_fields).
      • Terminal task Pydantic wiring.
      • CLI --json flag parsing and banner suppression.
      • check_env error emission in JSON and human modes.
      • Execution exception handling.
      • json.load(sys.stdin) pipeline compatibility.
    • Includes zero-dependency offline mock fallback for crewai so tests run reliably both locally and in CI.
  5. Known Limitations:

    • Real CrewAI live runtime execution was verified through the repository's test contract and AST validation suite with mocked LLM calls; live NVIDIA NIM calls were not executed to avoid live API token usage in automated testing.

Checklist

  • I ran my recipe end-to-end with deterministic offline mocks
  • ruff check and ruff format --check pass locally
  • I added/updated the recipe's README.md (inputs, outputs, sample run, and piping examples)
  • .env.example lists all required variables with placeholder values (no real keys)
  • This PR touches one recipe (recipes/customer-onboarding)

Sample output

1. JSON Mode (python run.py --json)

{
  "profile": {
    "customer_name": "Sarah Connor",
    "company": "Cyberdyne Systems",
    "role": "Chief Security Officer",
    "use_case": "Automating threat intelligence aggregation and incident response",
    "team_size": "50",
    "status": "READY",
    "completeness_score": "High",
    "missing_fields": []
  },
  "email": {
    "subject": "Welcome to Cyberdyne Systems — Let's Elevate Your Threat Intelligence",
    "body": "Hi Sarah,\n\nWelcome aboard! We are thrilled to partner with Cyberdyne Systems as your team of 50 scales your threat intelligence aggregation and incident response workflows..."
  }
}

2. Downstream Piping Example

$ python run.py --json | python -c 'import sys, json; data = json.load(sys.stdin); print(data["profile"]["status"])'
READY

@github-actions github-actions Bot added the recipe: improvement Enhancement to an existing recipe label Oct 26, 2026
@github-actions

Copy link
Copy Markdown

🎉 Thanks for your first pull request to crewai-recipes! A maintainer will review it soon (usually within 7 days). Make sure CI is green and the PR checklist is filled in — that speeds up review a lot.

@qodo-code-review

qodo-code-review Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

Sorry, something went wrong

We weren't able to complete the code review on our side. Please try again manually by commenting /agentic_review on this PR.

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Add structured JSON output to customer onboarding

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Add an optional --json mode for downstream tools while preserving the existing email output.
• Define a structured onboarding result containing the audited profile and composed email.
• Document JSON usage and add offline tests for schema, CLI, and error behavior.
Diagram

graph TD
  CLI["run.py CLI"] --> Collect["Collect profile"] --> Audit["Audit profile"] --> Compose["Compose email"] --> Mode{"JSON requested?"}
  Mode -->|yes| Schema["Onboarding model"] --> JSON["JSON stdout"]
  Mode -->|no| Human["Email stdout"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Control workflow verbosity in JSON mode
  • ➕ Protects parseable stdout from CrewAI execution traces, not just CLI banners.
  • ➖ Requires mode-aware logging or verbosity across the crew and agents.

Recommendation: Keep the optional Pydantic output on the terminal task; it preserves the existing workflow. Before relying on the documented JSON-only stdout contract, disable or redirect CrewAI verbosity in JSON mode: the crew and agents are still configured with verbose=True, which the mocked CLI tests do not exercise.

Files changed (5) +611 / -46

Enhancement (3) +170 / -38
crew.pyPass JSON mode into task construction +3/-0

Pass JSON mode into task construction

• Adds an optional 'json_output' argument to 'build_crew' and forwards it to 'build_tasks', leaving existing callers on the default path.

recipes/customer-onboarding/crew.py

run.pyAdd JSON CLI output and structured errors +114/-34

Add JSON CLI output and structured errors

• Adds '--json', result serialization across Pydantic and CrewOutput-like representations, and JSON errors for missing credentials or execution failures. The default banner-and-email presentation remains available.

recipes/customer-onboarding/run.py

tasks.pyDefine the onboarding result schema +53/-4

Define the onboarding result schema

• Introduces Pydantic models for the audited customer profile and onboarding email. JSON mode changes the terminal task's instructions and selects 'CustomerOnboardingResult' as its structured output.

recipes/customer-onboarding/tasks.py

Tests (1) +390 / -8
test_main.pyCover schema, task wiring, and both CLI modes +390/-8

Cover schema, task wiring, and both CLI modes

• Expands offline tests for model round-trips, incomplete profiles, terminal-task wiring, JSON formatting, CLI output, and error paths. Adds a CrewAI mock fallback when the package is unavailable.

recipes/customer-onboarding/test_main.py

Documentation (1) +51 / -0
README.mdDocument the JSON CLI mode and output shape +51/-0

Document the JSON CLI mode and output shape

• Adds the '--json' option, an example result, and shell pipelines for consuming the profile and email fields.

recipes/customer-onboarding/README.md

@Karan-Raj-KR
Karan-Raj-KR merged commit c279a9d into Karan-Raj-KR:main Oct 28, 2026
45 checks passed
@Karan-Raj-KR Karan-Raj-KR added dx ECSoC26-L2 ECSoC26 — medium task (Level 2) labels Oct 28, 2026 — with Claude
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dx ECSoC26-L2 ECSoC26 — medium task (Level 2) recipe: improvement Enhancement to an existing recipe

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add --json output flag to customer-onboarding (mirror lead-qualification pattern)

2 participants