|
| 1 | +"""The `my-project` CLI — demo Pipelex methods behind a Typer app. |
| 2 | +
|
| 3 | +Commands stay thin: parse arguments, dispatch on execution mode via |
| 4 | +`my_project.runner`, narrow + render via the matching `my_project.examples` |
| 5 | +module. SDK errors are caught once per command (in `_run_cli`) and presented by |
| 6 | +`my_project.errors`; anything unexpected crashes loudly. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | +from pathlib import Path |
| 11 | +from typing import Annotated, Any, Coroutine, TypeVar |
| 12 | + |
| 13 | +import httpx |
| 14 | +import typer |
| 15 | +from dotenv import load_dotenv |
| 16 | +from mthds.protocol.exceptions import PipelineRequestError |
| 17 | +from pipelex_sdk.runs import RunResultCompleted, RunResultFailed, RunResultRunning, RunResults, RunResultState |
| 18 | +from rich.console import Console |
| 19 | + |
| 20 | +from my_project.errors import present_error |
| 21 | +from my_project.examples import extract_entities as extract_entities_example |
| 22 | +from my_project.runner import ( |
| 23 | + ExecutionMode, |
| 24 | + fetch_run_result, |
| 25 | + fetch_run_status, |
| 26 | + progress_console, |
| 27 | + run_blocking, |
| 28 | + run_durable_attended, |
| 29 | + start_detached, |
| 30 | + wait_for_run, |
| 31 | +) |
| 32 | + |
| 33 | +ResultT = TypeVar("ResultT") |
| 34 | + |
| 35 | +app = typer.Typer(no_args_is_help=True, help="Run the demo Pipelex methods through the Pipelex API.") |
| 36 | +runs_app = typer.Typer(no_args_is_help=True, help="Inspect and resume durable runs by id.") |
| 37 | +app.add_typer(runs_app, name="runs") |
| 38 | + |
| 39 | +# Results go to stdout (pipeable); progress/status chatter goes to stderr (see runner.py). |
| 40 | +output_console = Console() |
| 41 | + |
| 42 | +MODE_HELP = "How to execute the run: `durable` (start + poll, survives anything) or `blocking` (single call, ~30s cap on hosted)." |
| 43 | +DETACH_HELP = "Start the run and exit immediately; fetch it later with `my-project runs ...` (durable mode only)." |
| 44 | + |
| 45 | + |
| 46 | +@app.callback() |
| 47 | +def main() -> None: |
| 48 | + """Load .env so PIPELEX_BASE_URL / PIPELEX_API_KEY are available.""" |
| 49 | + load_dotenv() |
| 50 | + |
| 51 | + |
| 52 | +@app.command(name="extract-entities") |
| 53 | +def extract_entities( |
| 54 | + text: Annotated[str | None, typer.Argument(help="The text to extract entities from.")] = None, |
| 55 | + file: Annotated[Path | None, typer.Option("--file", help="Read the input text from a file instead of the argument.")] = None, |
| 56 | + mode: Annotated[ExecutionMode, typer.Option(envvar="PIPELEX_EXECUTION_MODE", help=MODE_HELP)] = ExecutionMode.DURABLE, |
| 57 | + detach: Annotated[bool, typer.Option("--detach", help=DETACH_HELP)] = False, |
| 58 | +) -> None: |
| 59 | + """Extract people, organizations, and dates from a piece of text.""" |
| 60 | + input_text = _read_text_input(text=text, file=file) |
| 61 | + bundle = extract_entities_example.BUNDLE_PATH.read_text() |
| 62 | + results = _dispatch( |
| 63 | + pipe_code=extract_entities_example.PIPE_CODE, |
| 64 | + bundle=bundle, |
| 65 | + inputs={"text": input_text}, |
| 66 | + mode=mode, |
| 67 | + detach=detach, |
| 68 | + ) |
| 69 | + if results is None: |
| 70 | + return |
| 71 | + # Narrow into the typed model (validates the concept's shape), then print it |
| 72 | + # as JSON — the same rendering `runs result` / `runs wait` give. |
| 73 | + entities = extract_entities_example.parse(results) |
| 74 | + output_console.print_json(data=entities.model_dump()) |
| 75 | + |
| 76 | + |
| 77 | +@runs_app.command(name="status") |
| 78 | +def runs_status(run_id: Annotated[str, typer.Argument(help="The pipeline run id printed when the run started.")]) -> None: |
| 79 | + """Show a run's coarse status without waiting.""" |
| 80 | + run = _run_cli(fetch_run_status(run_id)) |
| 81 | + pipe_part = f" (pipe: {run.pipe_code})" if run.pipe_code else "" |
| 82 | + output_console.print(f"{run.pipeline_run_id}: [bold]{run.status}[/bold]{pipe_part}") |
| 83 | + if run.degraded: |
| 84 | + output_console.print("[yellow]Status is degraded — last-known value, the status backend was unreachable; retry shortly.[/yellow]") |
| 85 | + |
| 86 | + |
| 87 | +@runs_app.command(name="result") |
| 88 | +def runs_result(run_id: Annotated[str, typer.Argument(help="The pipeline run id printed when the run started.")]) -> None: |
| 89 | + """Fetch a run's result if it is finished (no waiting).""" |
| 90 | + state = _run_cli(fetch_run_result(run_id)) |
| 91 | + _render_result_state(state) |
| 92 | + |
| 93 | + |
| 94 | +@runs_app.command(name="wait") |
| 95 | +def runs_wait(run_id: Annotated[str, typer.Argument(help="The pipeline run id printed when the run started.")]) -> None: |
| 96 | + """Poll a run to completion, then print its raw result.""" |
| 97 | + results = _run_cli(wait_for_run(run_id)) |
| 98 | + _print_raw_results(results) |
| 99 | + |
| 100 | + |
| 101 | +def _read_text_input(*, text: str | None, file: Path | None) -> str: |
| 102 | + if text is not None and file is not None: |
| 103 | + msg = "Give the text either as an argument or via --file, not both." |
| 104 | + raise typer.BadParameter(msg) |
| 105 | + if file is not None: |
| 106 | + return file.read_text() |
| 107 | + if text is not None: |
| 108 | + return text |
| 109 | + msg = "Give the text to process as an argument, or point --file at a text file." |
| 110 | + raise typer.BadParameter(msg) |
| 111 | + |
| 112 | + |
| 113 | +def _dispatch(*, pipe_code: str, bundle: str, inputs: dict[str, Any], mode: ExecutionMode, detach: bool) -> RunResults | None: |
| 114 | + """Run the pipe in the requested mode; returns None when detached (id already printed).""" |
| 115 | + if detach: |
| 116 | + match mode: |
| 117 | + case ExecutionMode.BLOCKING: |
| 118 | + msg = "--detach starts a durable run; it cannot be combined with --mode blocking." |
| 119 | + raise typer.BadParameter(msg) |
| 120 | + case ExecutionMode.DURABLE: |
| 121 | + pass |
| 122 | + run_id = _run_cli(start_detached(pipe_code=pipe_code, bundle=bundle, inputs=inputs)) |
| 123 | + print(run_id) |
| 124 | + progress_console.print(f"Run started — fetch it later with: [bold]my-project runs wait {run_id}[/bold]") |
| 125 | + return None |
| 126 | + match mode: |
| 127 | + case ExecutionMode.BLOCKING: |
| 128 | + return _run_cli(run_blocking(pipe_code=pipe_code, bundle=bundle, inputs=inputs)) |
| 129 | + case ExecutionMode.DURABLE: |
| 130 | + return _run_cli(run_durable_attended(pipe_code=pipe_code, bundle=bundle, inputs=inputs)) |
| 131 | + |
| 132 | + |
| 133 | +def _run_cli(coro: Coroutine[Any, Any, ResultT]) -> ResultT: |
| 134 | + """Await a runner coroutine, presenting SDK errors and Ctrl-C as clean exits.""" |
| 135 | + try: |
| 136 | + return asyncio.run(coro) |
| 137 | + except (PipelineRequestError, httpx.HTTPStatusError) as exc: |
| 138 | + presentation = present_error(exc) |
| 139 | + progress_console.print(f"[red]Error:[/red] {presentation.message}") |
| 140 | + if presentation.hint: |
| 141 | + progress_console.print(f"[yellow]Hint:[/yellow] {presentation.hint}") |
| 142 | + raise typer.Exit(1) from exc |
| 143 | + except KeyboardInterrupt as exc: |
| 144 | + # The resume hint was already printed by the runner; the run keeps executing server-side. |
| 145 | + raise typer.Exit(130) from exc |
| 146 | + |
| 147 | + |
| 148 | +def _render_result_state(state: RunResultState) -> None: |
| 149 | + match state: |
| 150 | + case RunResultRunning(): |
| 151 | + progress_console.print( |
| 152 | + f"Run {state.pipeline_run_id} is still running — wait for it with: [bold]my-project runs wait {state.pipeline_run_id}[/bold]" |
| 153 | + ) |
| 154 | + case RunResultCompleted(): |
| 155 | + _print_raw_results(state.result) |
| 156 | + case RunResultFailed(): |
| 157 | + progress_console.print(f"[red]Run {state.pipeline_run_id} ended with status {state.status}: {state.message}[/red]") |
| 158 | + raise typer.Exit(1) |
| 159 | + |
| 160 | + |
| 161 | +def _print_raw_results(results: RunResults) -> None: |
| 162 | + """Print the run's main content as JSON — generic, no per-example narrowing.""" |
| 163 | + output_console.print_json(data=results.main_stuff) |
| 164 | + |
| 165 | + |
| 166 | +if __name__ == "__main__": |
| 167 | + app() |
0 commit comments