### Usage Examples Source: https://docs.rocketride.org/api/use-method Provides practical examples of how to use the `use` method in various scenarios, including starting pipelines from files, with custom parameters, and from configuration objects. ```APIDOC ## Usage Examples ### Start a Pipeline from a File ```python from rocketride import RocketRideClient async with RocketRideClient(uri='https://cloud.rocketride.ai', auth='your-api-key') as client: result = await client.use(filepath='text_analyzer.json') token = result['token'] print(f'Pipeline started with token: {token}') ``` ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth: 'your-api-key', uri: 'https://cloud.rocketride.ai', }); await client.connect(); const result = await client.use({ filepath: './text_analyzer.json' }); console.log(`Pipeline started with token: ${result.token}`); await client.disconnect(); ``` ### Start with Custom Parameters ```python result = await client.use( filepath='data_processor.json', threads=8, args=['--verbose'], source='custom_input', ttl=300, ) token = result['token'] ``` ```typescript const result = await client.use({ filepath: './data_processor.json', threads: 8, args: ['--verbose'], source: 'custom_input', ttl: 300, }); ``` ### Start from a Pipeline Configuration Object ```python config = { 'name': 'My Pipeline', 'project_id': 'my-project', 'source': 'webhook_1', 'components': [ {'id': 'webhook_1', 'provider': 'webhook', 'config': {}}, {'id': 'ai_chat_1', 'provider': 'ai_chat', 'config': {'model': 'gpt-4'}, 'input': [{'from': 'webhook_1', 'lane': 'output'}]}, {'id': 'response_1', 'provider': 'response', 'config': {}, 'input': [{'from': 'ai_chat_1', 'lane': 'answer'}]}, ], } result = await client.use(pipeline=config) ``` ### Full Workflow: Start, Send Data, Check Status ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: # Start pipeline result = await client.use(filepath='pipeline.json') token = result['token'] # Send data for processing response = await client.send(token, 'Analyze this text for sentiment') # Check status status = await client.get_task_status(token) print(f'State: {status["state"]}') # Terminate when done await client.terminate(token) ``` ``` -------------------------------- ### Start Pipeline from File (Python) Source: https://docs.rocketride.org/api/use-method Example of starting a RocketRide pipeline using a JSON configuration file in Python. It demonstrates obtaining the pipeline token for future operations. ```python from rocketride import RocketRideClient async with RocketRideClient(uri='https://cloud.rocketride.ai', auth='your-api-key') as client: result = await client.use(filepath='text_analyzer.json') token = result['token'] print(f'Pipeline started with token: {token}') ``` -------------------------------- ### Python: Basic Status Check Example Source: https://docs.rocketride.org/api/get-task-status-method Demonstrates initializing the client, starting a pipeline with `use()`, and then fetching its status using `get_task_status()`. ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: result = await client.use(filepath='pipeline.json') token = result['token'] status = await client.get_task_status(token) print(f'State: {status["state"]}') print(f'Progress: {status["completedCount"]}/{status["totalCount"]}') ``` -------------------------------- ### Full Workflow: Start, Send Data, Check Status (Python) Source: https://docs.rocketride.org/api/use-method A comprehensive Python example demonstrating the full lifecycle of a RocketRide pipeline: starting it, sending data for processing, checking its status, and finally terminating it. ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: # Start pipeline result = await client.use(filepath='pipeline.json') token = result['token'] # Send data for processing response = await client.send(token, 'Analyze this text for sentiment') # Check status status = await client.get_task_status(token) print(f'State: {status["state"]}') # Terminate when done await client.terminate(token) ``` -------------------------------- ### TypeScript: Basic Status Check Example Source: https://docs.rocketride.org/api/get-task-status-method Demonstrates initializing the client, starting a pipeline with `use()`, and then fetching its status using `getTaskStatus()`. ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth: 'your-api-key' }); await client.connect(); const result = await client.use({ filepath: './pipeline.json' }); const status = await client.getTaskStatus(result.token); console.log(`State: ${status.state}`); console.log(`Progress: ${status.completedCount}/${status.totalCount}`); await client.disconnect(); ``` -------------------------------- ### Validate Before Starting Pipeline in Python Source: https://docs.rocketride.org/api/validate-method This Python example shows how to validate a pipeline configuration before starting it. If validation passes, a task is initiated. ```python # Validate first, then start if valid result = await client.validate(pipeline) # Check the result for errors before proceeding # (exact structure depends on pipeline configuration) task = await client.use(pipeline=pipeline) ``` -------------------------------- ### Basic Termination Example in Python Source: https://docs.rocketride.org/api/terminate-method Demonstrates how to start a pipeline, send data, and then terminate it using the terminate() method in Python. Ensure the client is properly initialized and connected. ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: result = await client.use(filepath='pipeline.json') token = result['token'] # Send some data await client.send(token, 'Process this text') # Terminate the pipeline await client.terminate(token) print('Pipeline terminated successfully') ``` -------------------------------- ### Start Pipeline from File (TypeScript) Source: https://docs.rocketride.org/api/use-method Example of initiating a RocketRide pipeline from a JSON configuration file using TypeScript. It shows how to log the obtained pipeline token. ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth: 'your-api-key', uri: 'https://cloud.rocketride.ai', }); await client.connect(); const result = await client.use({ filepath: './text_analyzer.json' }); console.log(`Pipeline started with token: ${result.token}`); await client.disconnect(); ``` -------------------------------- ### Start Pipeline with Custom Parameters (Python) Source: https://docs.rocketride.org/api/use-method Demonstrates starting a pipeline with custom parameters such as threads, arguments, source override, and time-to-live in Python. ```python result = await client.use( filepath='data_processor.json', threads=8, args=['--verbose'], source='custom_input', ttl=300, ) token = result['token'] ``` -------------------------------- ### Start Pipeline from Configuration Object (Python) Source: https://docs.rocketride.org/api/use-method Example of initiating a RocketRide pipeline directly from a Python dictionary representing the pipeline configuration object. ```python config = { 'name': 'My Pipeline', 'project_id': 'my-project', 'source': 'webhook_1', 'components': [ {'id': 'webhook_1', 'provider': 'webhook', 'config': {}}, {'id': 'ai_chat_1', 'provider': 'ai_chat', 'config': {'model': 'gpt-4'}, 'input': [{'from': 'webhook_1', 'lane': 'output'}]}, {'id': 'response_1', 'provider': 'response', 'config': {}, 'input': [{'from': 'ai_chat_1', 'lane': 'answer'}]}, ], } result = await client.use(pipeline=config) ``` -------------------------------- ### Run MCP Server from Command Line Source: https://docs.rocketride.org/mcp_server/rocketride-mcp-server Start the MCP server using its installed entry point or by running it as a Python module. Ensure RocketRide engine is running. ```bash # Using the installed entry point rocketride-mcp ``` ```bash # Or using Python module python -m rocketride_mcp ``` -------------------------------- ### Start Pipeline with Custom Parameters (TypeScript) Source: https://docs.rocketride.org/api/use-method Shows how to start a pipeline with custom configurations like threads, arguments, source, and TTL in TypeScript. ```typescript const result = await client.use({ filepath: './data_processor.json', threads: 8, args: ['--verbose'], source: 'custom_input', ttl: 300, }); ``` -------------------------------- ### Basic Termination Example in TypeScript Source: https://docs.rocketride.org/api/terminate-method Demonstrates how to start a pipeline, send data, and then terminate it using the terminate() method in TypeScript. Ensure the client is properly initialized and connected. ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth: 'your-api-key' }); await client.connect(); const result = await client.use({ filepath: './pipeline.json' }); // Send some data await client.send(result.token, 'Process this text'); // Terminate the pipeline await client.terminate(result.token); console.log('Pipeline terminated successfully'); await client.disconnect(); ``` -------------------------------- ### Minimal API Usage Example Source: https://docs.rocketride.org/sdk/python-sdk A basic example demonstrating how to connect to the RocketRide service, run a pipeline from a file, send data, and disconnect. ```APIDOC ## Minimal API Usage Example ### 1. Minimal: connect, run pipeline from file, send one string, disconnect​ ```python import asyncio from rocketride import RocketRideClient async def main(): client = RocketRideClient(uri="https://cloud.rocketride.ai", auth="my-key") await client.connect() result = await client.use(filepath="pipeline.json") token = result["token"] out = await client.send(token, "Hello, pipeline!", objinfo={"name": "input.txt"}, mimetype="text/plain") print(out) await client.terminate(token) await client.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Install RocketRide SDK Source: https://docs.rocketride.org/sdk/node-sdk Install the RocketRide SDK using NPM, Yarn, or PNPM. ```bash # NPM npm install rocketride # Yarn yarn add rocketride # PNPM pnpm add rocketride ``` -------------------------------- ### Install RocketRide Python SDK Source: https://docs.rocketride.org/sdk/python-sdk Install the RocketRide Python SDK using pip. This is the first step to using the SDK in your project. ```bash pip install rocketride ``` -------------------------------- ### Install rocketride-mcp Source: https://docs.rocketride.org/mcp_server/rocketride-mcp-server Install the MCP server package using pip. Requires Python 3.10+ and rocketride-client-python >= 1.1.0. ```bash pip install rocketride-mcp ``` ```bash pip install rocketride-mcp ``` -------------------------------- ### Start Pipeline from File and Poll Status Source: https://docs.rocketride.org/sdk/node-sdk Starts a pipeline using a configuration file and polls its status until completion. Ensure the pipeline configuration file exists and is correctly formatted. The `ttl` option sets the pipeline's time-to-live in seconds. ```javascript const { token } = await client.use({ filepath: './pipeline.json', ttl: 3600 }); await client.setEvents(token, ['apaevt_status_processing']); // ... send data ... while (true) { const status = await client.getTaskStatus(token); if (status.completed) break; await new Promise((r) => setTimeout(r, 2000)); } await client.terminate(token); ``` -------------------------------- ### Basic Pipeline Validation in Python Source: https://docs.rocketride.org/api/validate-method Use this example to perform a basic validation of a pipeline configuration in Python. Ensure the RocketRideClient is properly initialized with authentication. ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: pipeline = { 'project_id': 'my-project', 'source': 'webhook_1', 'components': [ {'id': 'webhook_1', 'provider': 'webhook', 'config': {}}, {'id': 'processor_1', 'provider': 'ai_chat', 'config': {'model': 'gpt-4'}, 'input': [{'from': 'webhook_1', 'lane': 'output'}]}, {'id': 'response_1', 'provider': 'response', 'config': {}, 'input': [{'from': 'processor_1', 'lane': 'answer'}]}, ], } result = await client.validate(pipeline) print('Validation result:', result) ``` -------------------------------- ### Use Method Signature Source: https://docs.rocketride.org/api/use-method Demonstrates the method signature for starting a RocketRide pipeline in both Python and TypeScript. ```APIDOC ## Use Method Signature ### Python (async) ```python result = await client.use( filepath="pipeline.json", # or pipeline={...} token=None, source=None, threads=None, use_existing=None, args=None, ttl=None, pipelineTraceLevel=None, ) ``` ### TypeScript ```typescript const result = await client.use({ filepath: './pipeline.json', token: undefined, source: undefined, threads: undefined, useExisting: undefined, args: undefined, ttl: undefined, pipelineTraceLevel: undefined, }); ``` ``` -------------------------------- ### RocketRide CLI Commands Source: https://docs.rocketride.org/sdk/python-sdk Examples of common commands for managing RocketRide pipelines and tasks via the CLI. Commands may require a token for authentication and can use environment variables for configuration. ```bash rocketride start pipeline.json ``` ```bash rocketride upload *.pdf --token ``` ```bash rocketride status --token ``` ```bash rocketride stop --token ``` ```bash rocketride list ``` ```bash rocketride events ALL --token ``` ```bash rocketride rrext_store get_all_projects ``` -------------------------------- ### Upload multiple files and poll for completion Source: https://docs.rocketride.org/sdk/python-sdk Upload multiple files and monitor the pipeline's progress by polling the task status. This example demonstrates setting specific events to listen for and handling upload results. ```python import asyncio from pathlib import Path from rocketride import RocketRideClient async def main(): client = RocketRideClient(uri="https://cloud.rocketride.ai", auth="my-key") await client.connect() result = await client.use(filepath="vectorize.json") token = result["token"] await client.set_events(token, ["apaevt_status_upload", "apaevt_status_processing"]) files = ["doc1.md", "doc2.md", ("doc3.json", {"tag": "export"}, "application/json")] upload_results = await client.send_files(files, token) for r in upload_results: if r["action"] == "complete": print("OK", r["filepath"]) else: print("Failed", r["filepath"], r.get("error")) while True: status = await client.get_task_status(token) print(f"Progress: {status.get('completedCount', 0)}/{status.get('totalCount', 0)}") if status.get("completed"): break await asyncio.sleep(2) await client.terminate(token) await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### List and Get RocketRide Prompts Programmatically Source: https://docs.rocketride.org/mcp_server/rocketride-mcp-server Use session.list_prompts() to see available prompts and session.get_prompt() to render a specific prompt with arguments. The rendered message content is available in result.messages[0].content.text. ```python # List available prompts prompts = await session.list_prompts() # Get a rendered prompt result = await session.get_prompt("analyze-document", arguments={ "pipeline": "my-pipeline", "query": "Summarize the key findings" }) # result.messages[0].content.text contains the rendered message ``` -------------------------------- ### Read MCP Resources Programmatically Source: https://docs.rocketride.org/mcp_server/rocketride-mcp-server Access live information from the RocketRide engine using 'rocketride://' URIs. Examples show reading pipeline lists, server status, and node registry. ```python # Example: read the pipeline list resource result = await session.read_resource("rocketride://pipelines") # Returns: {"pipelines": [{"name": "my-pipeline", "description": "..."}, ...]} ``` ```python # Example: check server status result = await session.read_resource("rocketride://status") # Returns: {"connected": true, "pipeline_count": 3, "pipelines": ["pipe-a", "pipe-b", "pipe-c"]} ``` ```python # Example: list available node types result = await session.read_resource("rocketride://nodes") ``` -------------------------------- ### Anonymize Text Example Source: https://docs.rocketride.org/text/text-anonymization Demonstrates how sensitive entities in text are replaced with masking characters. No specific setup or imports are shown, as this is a conceptual example. ```text Input: John Smith is a patient at St. Mary's Hospital. Output: ████ █████ is a patient at ██ █████████████████. ``` -------------------------------- ### Chat with JSON parsing Source: https://docs.rocketride.org/sdk/python-sdk Engage in a chat interaction, providing instructions and examples to guide the AI's response. This example shows how to expect and parse a JSON answer. ```python import asyncio from rocketride import RocketRideClient from rocketride.schema import Question, Answer async def main(): async with RocketRideClient(uri="https://cloud.rocketride.ai", auth="my-key") as client: result = await client.use(filepath="chat_pipeline.json") token = result["token"] question = Question(expectJson=True) question.addInstruction("Format", "Return a JSON object with keys: summary, keywords.") question.addExample("Summarize X", {"summary": "...", "keywords": ["a", "b"]}) question.addQuestion("Summarize the main points and list keywords.") response = await client.chat(token=token, question=question) answer_text = response.get("data", {}).get("answer") or (response.get("answers") or [None])[0] structured = Answer().parseJson(answer_text) if answer_text else None print(structured) await client.terminate(token) asyncio.run(main()) ``` -------------------------------- ### Static Client with Connection Source: https://docs.rocketride.org/sdk/node-sdk Creates a client instance, establishes a connection, executes a callback function with the client, and ensures disconnection. ```APIDOC ## withConnection RocketRideClient.withConnection ### Description Creates a client, calls `connect()`, runs `callback(client)`, then `disconnect()` in a `finally` block. Returns the callback result. Use for one-off scripts so you never forget to disconnect. ### Method `RocketRideClient.withConnection(config: RocketRideClientConfig, callback: (client: RocketRideClient) => Promise): Promise` ### Parameters #### Request Body - **config** (RocketRideClientConfig) - Required - The configuration for the RocketRide client. - **callback** ((client: RocketRideClient) => Promise) - Required - A function that accepts the connected client and returns a Promise. ``` -------------------------------- ### Instantiate and Connect RocketRide Client Source: https://docs.rocketride.org/sdk/node-sdk Demonstrates the basic instantiation of the RocketRide client with authentication and URI, followed by establishing a connection. Auth and URI can be set later if not provided during construction. ```javascript const client = new RocketRideClient({ auth: 'my-key', uri: 'https://cloud.rocketride.ai' }); await client.connect(); ``` -------------------------------- ### Install RocketRide MCP SSE Source: https://docs.rocketride.org/mcp_server/rocketride-mcp-server Install the RocketRide MCP server with SSE support using pip. This command installs the necessary package for running the server in HTTP/SSE mode. ```bash pip install rocketride-mcp[sse] ``` -------------------------------- ### RocketRideClient Constructor Source: https://docs.rocketride.org/sdk/node-sdk Creates a client instance; it does not connect until you call `connect()`. You can set up callbacks and then open the connection when ready. ```APIDOC ## RocketRideClient ### Constructor ```typescript constructor(config: RocketRideClientConfig = {}) ``` Creates a client instance; it does **not** connect until you call `connect()`. You can set up callbacks and then open the connection when ready. `auth` and `uri` are optional at construction and can be set later with `setConnectionParams()` before `connect()`. **Example:** ```javascript const client = new RocketRideClient({ auth: 'my-key', uri: 'https://cloud.rocketride.ai' }); await client.connect(); ``` ``` -------------------------------- ### Using the Use Method with Error Handling Source: https://docs.rocketride.org/api/use-method Shows how to call the `client.use` method with a pipeline file path and includes exception handling for common errors like `FileNotFoundError` and `RuntimeError`. ```python from rocketride import RocketRideClient, RocketRideException try: result = await client.use(filepath='pipeline.json') except FileNotFoundError: print('Pipeline file not found') except RuntimeError as e: print(f'Pipeline failed to start: {e}') ``` -------------------------------- ### Create Streaming Data Pipe (Python) Source: https://docs.rocketride.org/api/send-method Demonstrates creating a streaming data pipe for large datasets using the client.pipe method. The recommended approach uses an async context manager for automatic resource management. ```python async with await client.pipe(token, mime_type='text/csv') as pipe: for chunk in csv_chunks: await pipe.write(chunk.encode()) result = await pipe.close() ``` ```python pipe = await client.pipe(token, mime_type='application/json') await pipe.open() await pipe.write(json.dumps(data_part1).encode()) await pipe.write(json.dumps(data_part2).encode()) result = await pipe.close() ``` -------------------------------- ### Send Files with RocketRide Client (Python) Source: https://docs.rocketride.org/api/send-method Demonstrates sending a list of files with and without metadata and MIME types using the send_files method. Ensure the client is initialized with authentication. ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: result = await client.use(filepath='document_processor.json') token = result['token'] # Simple file list files = ['document1.pdf', 'data.csv', 'report.docx'] results = await client.send_files(files, token) for r in results: if r['action'] == 'complete': print(f"Uploaded {r['filepath']} in {r['upload_time']:.2f}s") else: print(f"Failed {r['filepath']}: {r['error']}") # With metadata and MIME types files = [ ('report.pdf', {'department': 'finance'}), ('data.csv', {'type': 'quarterly'}, 'text/csv'), ] results = await client.send_files(files, token) ``` -------------------------------- ### Error Handling Example in Python Source: https://docs.rocketride.org/api/terminate-method Provides a Python code example for handling termination failures, specifically catching RuntimeError. This is useful for robustly managing pipeline operations. ```python try: await client.terminate(token) except RuntimeError as e: print(f'Termination failed: {e}') ``` -------------------------------- ### Terminate After Monitoring Example in Python Source: https://docs.rocketride.org/api/terminate-method Illustrates terminating a pipeline after monitoring its status for a period. This example uses asyncio.sleep to pause execution before checking the status and potentially terminating. ```python import asyncio result = await client.use(filepath='long_processor.json') token = result['token'] # Monitor for a while, then terminate await asyncio.sleep(30) status = await client.get_task_status(token) if not status['completed']: await client.terminate(token) print('Pipeline was still running — terminated') else: print('Pipeline already completed') ``` -------------------------------- ### Discover Services with Rocketride SDK Source: https://docs.rocketride.org/sdk/python-sdk Call `get_services` to retrieve a dictionary of all available service definitions on the server, allowing you to discover supported functionalities. Use `get_service` to fetch a specific service by name. ```python services = await client.get_services() ``` ```python service = await client.get_service(service_name) ``` -------------------------------- ### Chat with JSON Answer Parsing (Node.js) Source: https://docs.rocketride.org/sdk/node-sdk Use this snippet to send a chat question with instructions and examples, expecting a JSON answer. It demonstrates setting up the client, using a chat pipeline, adding instructions and examples to a question, sending the question, parsing the JSON answer, and cleaning up resources. ```typescript import { RocketRideClient, Question, Answer } from 'rocketride'; const client = new RocketRideClient({ auth, uri }); await client.connect(); const { token } = await client.use({ pipeline: { pipeline: chatPipelineConfig } }); const question = new Question({ expectJson: true }); question.addInstruction('Format', 'Return a JSON object with keys: summary, keywords.'); question.addExample('Summarize X', { summary: '...', keywords: ['a', 'b'] }); question.addQuestion('Summarize the main points and list keywords.'); const response = await client.chat({ token, question }); const answerText = response?.data?.answer ?? response?.answers?.[0]; const structured = answerText ? Answer.parseJson(answerText) : null; console.log(structured); await client.terminate(token); await client.disconnect(); ``` -------------------------------- ### Pipeline Execution Source: https://docs.rocketride.org/sdk/node-sdk Manage the lifecycle of a pipeline, from starting and validating to terminating and checking status. ```APIDOC ## use ### Description Starts a pipeline. You must pass either `pipeline` (object) or `filepath` (path to a JSON file; Node only). The client substitutes `${ROCKETRIDE_*}` in the config from its `env` (or `.env`). Returns at least `token`; use that token for `send()`, `sendFiles()`, `pipe()`, `chat()`, `getTaskStatus()`, and `terminate()`. ### Method `use(options?: { token?: string; filepath?: string; pipeline?: PipelineConfig; source?: string; threads?: number; useExisting?: boolean; args?: string[]; ttl?: number }): Promise & { token: string }> ` ### Returns `Promise<{ token: string, ... }> ` ### Example - start from file and poll until done: ```javascript const { token } = await client.use({ filepath: './pipeline.json', ttl: 3600 }); await client.setEvents(token, ['apaevt_status_processing']); // ... send data ... while (true) { const status = await client.getTaskStatus(token); if (status.completed) break; await new Promise((r) => setTimeout(r, 2000)); } await client.terminate(token); ``` ``` ```APIDOC ## validate ### Description Validates a pipeline configuration without starting it. Returns validation results (e.g. errors, warnings). Use to check pipeline correctness before `use()`. ### Method `validate(options: { pipeline: PipelineConfig | Record; source?: string }): Promise>` ### Returns `Promise>` ``` ```APIDOC ## terminate ### Description Stops the pipeline for that token and frees server resources. Call when the user cancels or when you are done sending data. ### Method `terminate(token: string): Promise` ### Returns `-` ``` ```APIDOC ## getTaskStatus ### Description Returns current task status: e.g. `completedCount`, `totalCount`, `completed`, `state`, `exitCode`. Use to poll until `completed` is true or to show progress. ### Method `getTaskStatus(token: string): Promise` ### Returns `Promise` ``` -------------------------------- ### Discover Services and Send Custom DAP Request (Node.js) Source: https://docs.rocketride.org/sdk/node-sdk This snippet shows how to discover available services, retrieve a specific service schema (e.g., 'ocr'), build a custom DAP request, send it with a timeout, and check for failures. Ensure you have authentication details and a valid token. ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth, uri }); await client.connect(); const services = await client.getServices(); console.log('Available:', Object.keys(services)); const ocrSchema = await client.getService('ocr'); const req = client.buildRequest('rrext_ping', { token: myToken }); const res = await client.request(req, 5000); if (client.didFail(res)) throw new Error(res.message); await client.disconnect(); ``` -------------------------------- ### Pipeline Configuration with Environment Variables Source: https://docs.rocketride.org/api/use-method Demonstrates how to use environment variables (e.g., `${ROCKETRIDE_PROJECT_ID}`, `${ROCKETRIDE_APIKEY}`) within pipeline configurations for dynamic value injection. ```json { "project_id": "${ROCKETRIDE_PROJECT_ID}", "components": [ { "id": "processor", "provider": "transform", "config": { "apiKey": "${ROCKETRIDE_APIKEY}" } } ] } ``` -------------------------------- ### Task Status Response Format Source: https://docs.rocketride.org/api/get-task-status-method Example of the full TASK_STATUS object returned by the method. ```json { "name": "text_analyzer", "project_id": "my-project", "state": 3, "completed": false, "startTime": 1700000000.0, "endTime": 0.0, "totalCount": 100, "completedCount": 45, "failedCount": 2, "rateCount": 5, "errors": [], "warnings": [], "metrics": { "cpu_percent": 25.3, "cpu_memory_mb": 512.0, "gpu_memory_mb": 1024.0 }, "tokens": { "cpu_utilization": 1.5, "cpu_memory": 0.8, "gpu_memory": 2.1, "total": 4.4 }, "pipeflow": { "totalPipes": 2, "byPipe": { "0": ["source", "transform", "filter"], "1": ["source", "transform"] } } } ``` -------------------------------- ### Use Method Parameters Source: https://docs.rocketride.org/api/use-method Details the parameters available for the `use` method, including their types, requirements, and descriptions. ```APIDOC ## Parameters | Parameter | Type | Required | Description | |---|---|---|---| | `pipeline` | `dict` / `PipelineConfig` | One of `pipeline` or `filepath` required | Pipeline configuration object | | `filepath` | `str` / `string` | One of `pipeline` or `filepath` required | Path to a JSON or JSON5 pipeline configuration file | | `token` | `str` / `string` | No | Custom task token (server generates one if not provided) | | `source` | `str` / `string` | No | Override the source component specified in the pipeline config | | `threads` | `int` / `number` | No | Number of processing threads (server decides default) | | `use_existing` / `useExisting` | `bool` / `boolean` | No | Reuse an existing pipeline with the same token | | `args` | `list[str]` / `string[]` | No | Command-line style arguments to pass to the pipeline | | `ttl` | `int` / `number` | No | Time-to-live in seconds for idle pipelines (0 = no timeout) | | `pipelineTraceLevel` | `str` / `string` | No | Trace level: `'none'`, `'metadata'`, `'summary'`, or `'full'` ``` -------------------------------- ### Python Error Handling for Get Task Status Source: https://docs.rocketride.org/api/get-task-status-method Handles potential runtime errors when retrieving task status. ```python try: status = await client.get_task_status(token) except RuntimeError as e: print(f'Failed to get status: {e}') ``` -------------------------------- ### Task State Transitions Source: https://docs.rocketride.org/api/get-task-status-method Illustrates the possible state transitions for a task. ```text NONE → STARTING → INITIALIZING → RUNNING → STOPPING → COMPLETED → STOPPING → CANCELLED ``` -------------------------------- ### Get Task Status Method Source: https://docs.rocketride.org/api/get-task-status-method Retrieves the current status and detailed metrics of a running pipeline task using its token. ```APIDOC ## Get Task Status ### Description Retrieves the current status and detailed metrics of a running pipeline task. Use this method to monitor progress, check for errors, and determine when processing is complete. ### Method Signature **Python (async)** ```python status = await client.get_task_status(token) ``` **TypeScript** ```typescript const status = await client.getTaskStatus(token); ``` ### Parameters | Parameter | Type | Required | Description | |---|---|---|---| | `token` | `str` / `string` | Yes | Task token returned by `use()` | ### Returns - **Type**: `TASK_STATUS` — a dictionary/object with comprehensive status fields. ### Key Fields | Field | Type | Description | |---|---|---| | `state` | `int` | Current task state (see Task States) | | `completed` | `bool` | Whether the task has finished execution | | `name` | `str` | Pipeline name | | `project_id` | `str` | Project identifier | | `source` | `str` | Source component ID | | `startTime` | `float` | Task start timestamp (Unix time) | | `endTime` | `float` | Task completion timestamp (Unix time) | | `totalCount` | `int` | Total items to process | | `completedCount` | `int` | Items processed successfully | | `failedCount` | `int` | Items that failed processing | | `totalSize` | `int` | Total size in bytes | | `completedSize` | `int` | Bytes processed successfully | | `rateCount` | `int` | Current processing rate (items/sec) | | `rateSize` | `int` | Current processing rate (bytes/sec) | | `errors` | `list[str]` | Recent error messages (max 50) | | `warnings` | `list[str]` | Recent warning messages (max 50) | | `status` | `str` | Current status message | | `currentObject` | `str` | Item currently being processed | | `exitCode` | `int` | Process exit code (0 = success) | | `exitMessage` | `str` | Exit message details | | `metrics` | `TASK_METRICS` | CPU, memory, and GPU utilization | | `tokens` | `TASK_TOKENS` | Token usage for billing | | `pipeflow` | `TASK_STATUS_FLOW` | Pipeline component execution flow | ### Metrics Fields (`metrics`) | Field | Type | Description | |---|---|---| | `cpu_percent` | `float` | Current CPU utilization (0-100%) | | `cpu_memory_mb` | `float` | Current RAM usage in MB | | `gpu_memory_mb` | `float` | Current GPU VRAM usage in MB | | `peak_cpu_percent` | `float` | Peak CPU utilization | | `peak_cpu_memory_mb` | `float` | Peak RAM usage in MB | | `peak_gpu_memory_mb` | `float` | Peak GPU VRAM usage in MB | ### Token Usage Fields (`tokens`) | Field | Type | Description | |---|---|---| | `cpu_utilization` | `float` | Cumulative CPU utilization tokens | | `cpu_memory` | `float` | Cumulative CPU memory tokens | | `gpu_memory` | `float` | Cumulative GPU memory tokens | | `total` | `float` | Total cumulative tokens | ### Usage Examples **Basic Status Check (Python)** ```python from rocketride import RocketRideClient async with RocketRideClient(auth='your-api-key') as client: result = await client.use(filepath='pipeline.json') token = result['token'] status = await client.get_task_status(token) print(f'State: {status["state"]}') print(f'Progress: {status["completedCount"]}/{status["totalCount"]}') ``` **Basic Status Check (TypeScript)** ```typescript import { RocketRideClient } from 'rocketride'; const client = new RocketRideClient({ auth: 'your-api-key' }); await client.connect(); const result = await client.use({ filepath: './pipeline.json' }); const status = await client.getTaskStatus(result.token); console.log(`State: ${status.state}`); console.log(`Progress: ${status.completedCount}/${status.totalCount}`); await client.disconnect(); ``` **Polling Until Completion (Python)** ```python import asyncio status = await client.get_task_status(token) while not status['completed']: print(f'Processing: {status["completedCount"]}/{status["totalCount"]}') if status['errors']: for error in status['errors']: print(f'Error: {error}') await asyncio.sleep(2) status = await client.get_task_status(token) print(f'Pipeline finished with exit code: {status["exitCode"]}') ``` **Polling Until Completion (TypeScript)** ```typescript let status = await client.getTaskStatus(token); while (!status.completed) { console.log(`Processing: ${status.completedCount}/${status.totalCount}`); await new Promise(resolve => setTimeout(resolve, 2000)); status = await client.getTaskStatus(token); } console.log('Pipeline complete!'); ``` ### Task States | State | Value | Description | |---|---|---| | `NONE` | `0` | Initial state — no resources allocated | | `STARTING` | `1` | Resource allocation and subprocess preparation | | `INITIALIZING` | `2` | Subprocess initialization and service startup | | `RUNNING` | `3` | Operational — actively processing requests | | `STOPPING` | `4` | Graceful shutdown in progress | | `COMPLETED` | `5` | Finished successfully — resources cleaned up | | `CANCELLED` | `6` | Terminated before completion | ```