### Install Surreal Commands Library Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This snippet shows how to install the `surreal-commands` Python library using pip, the standard package installer for Python. ```bash pip install surreal-commands ``` -------------------------------- ### Bash Commands: Running Surreal Commands Examples Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md Provides `bash` commands to execute various example scripts included in the repository, demonstrating basic, advanced, and integration test functionalities of `surreal-commands`. ```bash # Basic example python examples/basic_example.py # Advanced example python examples/advanced_example.py # Integration test python examples/test_integration.py ``` -------------------------------- ### Start and Manage Surreal Commands Worker via CLI Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This section provides comprehensive Bash commands for starting and managing the `surreal-commands-worker`. It covers importing modules, using environment variables, enabling debug logging, setting task limits, and importing multiple modules for command discovery. ```bash surreal-commands-worker start --import-modules "my_app.tasks" ``` ```bash export SURREAL_COMMANDS_MODULES="my_app.tasks" surreal-commands-worker start ``` ```bash surreal-commands-worker start --debug --import-modules "my_app.tasks" ``` ```bash surreal-commands-worker start --max-tasks 10 --import-modules "my_app.tasks" ``` ```bash surreal-commands-worker start --import-modules "my_app.tasks,analytics.commands" ``` ```bash surreal-commands-worker start --debug --max-tasks 20 --import-modules "my_app.tasks" ``` -------------------------------- ### Handle Surreal Commands Asynchronously in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python example demonstrates asynchronous command handling using `asyncio`. It shows how to submit a command, get its status, and await its completion, suitable for non-blocking operations. ```python import asyncio from surreal_commands import submit_command, get_command_status, wait_for_command async def async_example(): # Submit command cmd_id = submit_command("analytics", "analyze", {"text": "data"}) # Monitor status status = await get_command_status(cmd_id) print(f"Status: {status.status}") # Wait for completion result = await wait_for_command(cmd_id, timeout=60) if result.is_success(): print(f"Result: {result.result}") # Run async asyncio.run(async_example()) ``` -------------------------------- ### Python Example: Testing Surreal Commands Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md Demonstrates how to write a Python test for `surreal-commands` using `registry`, `submit_command`, and `execute_command_sync`. It shows how to import command modules, execute a command, and assert its success and result. ```python # test_commands.py from surreal_commands import registry, submit_command, execute_command_sync def test_process_text(): # Import your commands to register them import my_app.tasks # Test command execution result = execute_command_sync( "my_app", "process_text", {"text": "test", "uppercase": True}, timeout=10 ) assert result.is_success() assert result.result["result"] == "TEST" print("✅ Test passed!") if __name__ == "__main__": test_process_text() ``` -------------------------------- ### Surreal Commands Project Directory Structure Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md Illustrates the recommended directory structure for a `surreal-commands` project, including command definitions, application entry point, environment variables, and dependencies. ```text your_project/ ├── my_app/ │ ├── __init__.py │ └── tasks.py # Command definitions ├── main.py # Application entry point ├── .env # Environment variables └── requirements.txt # Dependencies ``` -------------------------------- ### Configure SurrealDB Environment Variables Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This snippet provides an example of a `.env` file used to configure connection details for SurrealDB, including the URL, user credentials, namespace, and database for `surreal-commands`. ```env # SurrealDB Configuration SURREAL_URL=ws://localhost:8000/rpc SURREAL_USER=root SURREAL_PASSWORD=root SURREAL_NAMESPACE=surreal_commands SURREAL_DATABASE=commands ``` -------------------------------- ### Submit and Synchronously Monitor Surreal Commands Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python example illustrates how to submit a command to the Surreal Commands system and then synchronously wait for its completion. It demonstrates checking the command's success status and retrieving the result or error message. ```python from surreal_commands import submit_command, wait_for_command_sync # Submit a command cmd_id = submit_command("my_app", "process_text", { "text": "hello world", "uppercase": True }) print(f"Command submitted: {cmd_id}") # Wait for completion result = wait_for_command_sync(cmd_id, timeout=30) if result.is_success(): print(f"Result: {result.result}") else: print(f"Failed: {result.error_message}") ``` -------------------------------- ### Enabling Debug Mode for Surreal Commands Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md Provides methods to enable debug logging for `surreal-commands`, either via a `bash` command for the worker or programmatically in Python using the `logging` module, to get detailed information for troubleshooting. ```bash surreal-commands-worker start --debug ``` ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Pass Context and Metadata to Surreal Commands Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python example shows how to define a command that accepts an optional `context` parameter and how to pass custom metadata when submitting a command. This allows for injecting user-specific or session-specific information into command execution. ```python @command("contextual_task") def contextual_task(input_data: dict, context: dict = None) -> dict: user_id = context.get("user_id") if context else "unknown" return {"processed_by": user_id, "data": input_data} # Submit with context cmd_id = submit_command( "my_app", "contextual_task", {"message": "hello"}, context={"user_id": "user123", "session": "abc"} ) ``` -------------------------------- ### Start SurrealDB Docker Container Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This command demonstrates how to run a SurrealDB instance using Docker, exposing port 8000 and setting initial root user credentials for local development. ```bash docker run --rm -p 8000:8000 surrealdb/surrealdb:latest start --user root --pass root ``` -------------------------------- ### Define Surreal Commands with Python Decorators Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python code demonstrates how to define commands using the `@command` decorator from `surreal_commands`. It includes examples of defining input/output models with Pydantic and overriding the application name for a command. ```python # my_app/tasks.py from surreal_commands import command from pydantic import BaseModel class TextInput(BaseModel): text: str uppercase: bool = False class TextOutput(BaseModel): result: str length: int @command("process_text") # Auto-detects app name as "my_app" def process_text(input_data: TextInput) -> TextOutput: result = input_data.text.upper() if input_data.uppercase else input_data.text return TextOutput(result=result, length=len(result)) @command("analyze", app="analytics") # Override app name def analyze_data(input_data: TextInput) -> TextOutput: return TextOutput( result=f"Analyzed: {input_data.text}", length=len(input_data.text) ) ``` -------------------------------- ### Install Surreal Commands Python Package Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This command installs the `surreal-commands` library using pip, the Python package installer, making it available for use in your Python projects. ```bash pip install surreal-commands ``` -------------------------------- ### Submit and Monitor Commands in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This Python example demonstrates how to submit a command to the Surreal Commands system using `submit_command` and then synchronously wait for its completion and retrieve the result using `wait_for_command_sync`. ```python from surreal_commands import submit_command, wait_for_command_sync # Submit a command cmd_id = submit_command("my_app", "process_text", { "message": "hello world", "uppercase": True }) print(f"Submitted command: {cmd_id}") # Wait for completion result = wait_for_command_sync(cmd_id, timeout=30) if result.is_success(): print(f"Result: {result.result}") ``` -------------------------------- ### Monitor Surreal Commands with CLI Tools Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This snippet shows how to use the `surreal-commands-dashboard` and `surreal-commands-logs` CLI tools to monitor the status and real-time logs of commands, providing visibility into the system's operation. ```bash surreal-commands-dashboard ``` ```bash surreal-commands-logs ``` -------------------------------- ### Start Surreal Commands Worker Process Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md These bash commands illustrate various ways to start the Surreal Commands worker process. Options include importing modules via environment variables or CLI arguments, enabling debug logging, and setting a custom concurrent task limit. ```bash export SURREAL_COMMANDS_MODULES="tasks" surreal-commands-worker # Or specify modules directly via CLI surreal-commands-worker --import-modules "tasks" # With debug logging surreal-commands-worker --debug --import-modules "tasks" # With custom concurrent task limit surreal-commands-worker --max-tasks 10 --import-modules "tasks" # Import multiple modules surreal-commands-worker --import-modules "tasks,my_app.commands" ``` -------------------------------- ### Register Surreal Commands Directly with Registry Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python snippet demonstrates how to manually register a command with the `surreal_commands` registry, bypassing the decorator. It also shows how to list all registered commands, providing flexibility for advanced integration. ```python from surreal_commands import registry from langchain_core.runnables import RunnableLambda def my_function(data): return {"processed": data} # Register manually my_runnable = RunnableLambda(my_function) registry.register("manual_app", "my_command", my_runnable) # List all commands commands = registry.list_commands() for app_name, app_commands in commands.items(): print(f"App: {app_name}") for cmd_name in app_commands: print(f" Command: {cmd_name}") ``` -------------------------------- ### Implement Error Handling for Surreal Commands Source: https://github.com/lfnovo/surreal-commands/blob/main/examples/README.md This Python snippet illustrates how to define a command that intentionally raises an error and how to handle such failures when submitting and waiting for the command. It demonstrates catching `TimeoutError` and checking `CommandStatus` for failed tasks. ```python from surreal_commands import submit_command, wait_for_command_sync, CommandStatus @command("failing_task") def failing_task(input_data: dict) -> dict: raise ValueError("Something went wrong") # Submit and handle errors cmd_id = submit_command("test", "failing_task", {"data": "test"}) try: result = wait_for_command_sync(cmd_id, timeout=30) if result.status == CommandStatus.FAILED: print(f"Task failed: {result.error_message}") except TimeoutError: print("Task timed out") ``` -------------------------------- ### Implement Asynchronous Commands in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This example shows how to define an asynchronous command using async def for long-running or I/O-bound operations. It also illustrates how LangChain's RunnableLambda can wrap both synchronous and asynchronous functions for command execution. ```python async def async_process(input_data: MyInput) -> MyOutput: # Async processing await some_async_operation() return MyOutput(...) # LangChain handles both sync and async command = RunnableLambda(async_process) ``` -------------------------------- ### View Worker Logs and Filter by Level using Bash Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md These bash commands show how to run the worker process and view its logs. It includes examples for enabling debug output and filtering log messages by severity level using the LOGURU_LEVEL environment variable. ```bash # Worker logs with debug info uv run python run_worker.py --debug # Filter logs by level LOGURU_LEVEL=INFO uv run python run_worker.py ``` -------------------------------- ### Configure SurrealDB Environment Variables Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This snippet shows the essential environment variables required to configure the connection to a SurrealDB instance, including the URL, user credentials, namespace, and database. ```env # SurrealDB Configuration SURREAL_URL=ws://localhost:8000/rpc SURREAL_USER=root SURREAL_PASSWORD=root SURREAL_NAMESPACE=test SURREAL_DATABASE=test ``` -------------------------------- ### Run Project Tests with Pytest in Bash Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md These bash commands demonstrate how to execute tests for the project using pytest. It includes options for running all tests and generating code coverage reports, essential for development and quality assurance. ```bash # Run tests (when implemented) uv run pytest # With coverage uv run pytest --cov=commands ``` -------------------------------- ### Run Surreal Commands Tests Source: https://github.com/lfnovo/surreal-commands/blob/main/tests/README.md Instructions on how to execute the unit tests for the Surreal Commands library using `uv run pytest`, including options for running all tests, specific files, with coverage, or by test categories (unit/integration). ```bash # Run all tests uv run pytest tests/ # Run only passing tests (registration) uv run pytest tests/test_command_registration.py -v # Run with coverage (for working modules) uv run pytest tests/test_command_registration.py --cov=src/surreal_commands # Run specific test categories uv run pytest -m unit # Unit tests only uv run pytest -m integration # Integration tests only ``` -------------------------------- ### Surreal Commands Library Directory Structure Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This outline details the directory structure of the `surreal-commands` library, showing the organization of its core components, including application directories, CLI tools, command management, and database layers. ```filesystem surreal-commands/ ├── apps/ # Your command applications │ └── text_utils/ # Example app │ ├── __init__.py │ └── commands.py # Command definitions ├── cli/ # CLI components │ ├── __init__.py │ ├── launcher.py # Dynamic CLI generator │ ├── dashboard.py # (Future) Dashboard UI │ └── logs.py # (Future) Log viewer ├── commands/ # Core command system │ ├── __init__.py │ ├── command_service.py # Command lifecycle management │ ├── executor.py # Command execution engine │ ├── loader.py # Command discovery │ ├── registry.py # Command registry (singleton) │ ├── registry_types.py # Type definitions │ └── worker.py # Worker process ├── repository/ # Database layer │ └── __init__.py # SurrealDB helpers ├── cli.py # CLI entry point ├── run_worker.py # Worker entry point └── .env # Environment configuration ``` -------------------------------- ### Monitor Surreal Commands with CLI Tools Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md These bash commands demonstrate how to use the built-in CLI tools to monitor the Surreal Commands system, including viewing a command dashboard and real-time logs. ```bash surreal-commands-dashboard # View real-time logs surreal-commands-logs ``` -------------------------------- ### System Architecture Overview with Mermaid Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This Mermaid diagram illustrates the high-level architecture of the Surreal Commands system, showing the flow from the CLI interface through SurrealDB to the Worker Process and Registered Commands. ```Mermaid graph TD CLI[CLI Interface] --> SurrealDB[(SurrealDB Queue)] SurrealDB --> Worker[Worker Process] Worker --> Registry[Command Registry] Registry --> Commands[Registered Commands] Worker --> |Execute| Commands Commands --> |Results| SurrealDB ``` -------------------------------- ### SurrealDB Command Schema Definition Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This snippet defines the JSON-like schema for commands stored in SurrealDB. It outlines the fields such as ID, application, name, arguments, context, status, result, error messages, and timestamps, providing a clear structure for command records. ```javascript { id: "command:unique_id", app: "app_name", name: "command_name", args: { /* command arguments */ }, context: { /* optional context */ }, status: "new" | "running" | "completed" | "failed", result: { /* command output */ }, error_message: "error details if failed", created: "2024-01-07T10:30:00Z", updated: "2024-01-07T10:30:05Z" } ``` -------------------------------- ### Define Asynchronous Commands with Python Decorator Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This Python code defines two asynchronous commands, `process_text` and `analyze_data`, using the `@command` decorator. It showcases Pydantic models for type-safe input and output, demonstrating how to structure command definitions for the Surreal Commands system. ```python # my_app/tasks.py from surreal_commands import command, submit_command from pydantic import BaseModel class ProcessInput(BaseModel): message: str uppercase: bool = False class ProcessOutput(BaseModel): result: str length: int @command("process_text") # Auto-detects app name as "my_app" def process_text(input_data: ProcessInput) -> ProcessOutput: result = input_data.message.upper() if input_data.uppercase else input_data.message return ProcessOutput(result=result, length=len(result)) # Alternative: explicit app name @command("analyze", app="analytics") def analyze_data(input_data: ProcessInput) -> ProcessOutput: return ProcessOutput(result=f"Analyzed: {input_data.message}", length=len(input_data.message)) ``` -------------------------------- ### Check SurrealDB Command Status in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This Python script connects to SurrealDB to query and display the status of recent commands. It uses asyncio for asynchronous database interaction and iterates through results to print command IDs and their current statuses. ```python # check_results.py import asyncio from repository import db_connection async def check_status(): async with db_connection() as db: commands = await db.query( "SELECT * FROM command ORDER BY created DESC LIMIT 10" ) for cmd in commands: print(f"{cmd['id']}: {cmd['status']}") asyncio.run(check_status()) ``` -------------------------------- ### Access Command Context in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This snippet demonstrates how a command function can access additional context data, such as user IDs, passed during its execution. The context is provided as a dictionary, allowing flexible data injection into command processing. ```python def contextual_command(input_data: MyInput, context: dict) -> MyOutput: user_id = context.get("user_id") # Use context in processing ``` -------------------------------- ### Define Custom Command with Pydantic Models in Python Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md This snippet demonstrates how to define a custom command's input and output types using Pydantic BaseModel for complex data structures like lists, optional fields, and datetime. It ensures type validation and clear data contracts for command arguments. ```python from typing import List, Optional from datetime import datetime from pydantic import BaseModel, Field class AnalysisInput(BaseModel): data: List[float] method: str = Field(default="mean", description="Analysis method") threshold: Optional[float] = None class AnalysisOutput(BaseModel): result: float method_used: str items_processed: int warnings: List[str] = [] def analyze_data(input_data: AnalysisInput) -> AnalysisOutput: # Your analysis logic here pass ``` -------------------------------- ### Enable Debug Mode for CLI and Worker in Bash Source: https://github.com/lfnovo/surreal-commands/blob/main/README.md These bash commands show how to enable detailed debug logging for both the command-line interface (CLI) and the worker process. Setting LOGURU_LEVEL=DEBUG provides verbose output for troubleshooting and development. ```bash # Debug CLI LOGURU_LEVEL=DEBUG uv run python cli.py text_utils uppercase --text "test" # Debug Worker uv run python run_worker.py --debug ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.