### Run your first MCP tool Source: https://github.com/sema4ai/actions/blob/master/action_server/README.md Guides through bootstrapping a new project and starting the Sema4.ai Action Server. This involves creating a new project directory and then running the server within that directory. ```shell # Bootstrap a new project using this template. # You'll be prompted for the name of the project (directory): action-server new # Start Action Server cd my-project action-server start ``` -------------------------------- ### Setup Fixture Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md The `setup` fixture allows you to run code before actions start. It can be used as a decorator with or without a `scope` argument ('action' or 'session') to control when the setup code is executed. It also supports running code after execution by using `yield`. ```APIDOC ## POST /setup ### Description Runs code before any actions start, or before each separate action. ### Method POST (or decorator usage) ### Endpoint N/A (decorator) or internal endpoint for setup execution ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (when used as decorator) ### Request Example ```python from sema4ai.actions import setup @setup def my_fixture(action): print(f"Before action: {action.name}") @setup(scope="action") def before_each(action): print(f"Running action '{action.name}'") @setup(scope="session") def before_all(actions): print(f"Running {len(actions)} action(s)") @setup def measure_time(action): start = time.monotonic() yield # Action executes here duration = time.monotonic() - start print(f"Action took {duration} seconds") ``` ### Response #### Success Response (200) N/A (decorator usage, returns callable) #### Response Example N/A ``` -------------------------------- ### Action Server Installation Source: https://context7.com/sema4ai/actions/llms.txt Instructions for installing the Sema4.ai Action Server using pip, Homebrew, or a direct binary download. ```APIDOC ## Installation ### Install Action Server via pip ```bash pip install sema4ai-action-server ``` ### Install Action Server via Homebrew (macOS) ```bash brew update brew install sema4ai/tools/action-server ``` ### Install Action Server binary (Linux) ```bash curl -o action-server https://cdn.sema4.ai/action-server/releases/latest/linux64/action-server chmod a+x action-server sudo mv action-server /usr/local/bin/ ``` ``` -------------------------------- ### Python setup Function Signature Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Shows the type signature for the `setup` function, indicating its flexibility with arguments and return types for creating fixtures. ```python setup( *args, **kwargs ) → Union[Callable[[IAction], Any], Callable[[Callable[[IAction], Any]], Callable[[IAction], Any]], Callable[[Callable[[Sequence[IAction]], Any]], Callable[[Sequence[IAction]], Any]]] ``` -------------------------------- ### Python Setup Fixture Decorator Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Demonstrates how to use the `@setup` decorator in Python to run code before an action. The fixture function receives the action object as an argument. ```python from sema4ai.actions import setup @setup def my_fixture(action): print(f"Before action: {action.name}") ``` -------------------------------- ### Install Action Server binary (Linux) Source: https://context7.com/sema4ai/actions/llms.txt Installs the Sema4.ai Action Server on Linux by downloading the binary, making it executable, and moving it to a system path. This method is suitable for Linux environments without package managers. ```bash curl -o action-server https://cdn.sema4.ai/action-server/releases/latest/linux64/action-server chmod a+x action-server sudo mv action-server /usr/local/bin/ ``` -------------------------------- ### Python Setup Fixture with Yield for Post-Execution Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Illustrates using `yield` within a `@setup` fixture to execute code after the action has completed. This is useful for tasks like measuring execution time. ```python import time from sema4ai.actions import setup @setup def measure_time(action): start = time.monotonic() yield # Action executes here duration = time.monotonic() - start print(f"Action took {duration} seconds") @action def my_long_action(): ... ``` -------------------------------- ### Bootstrap a New Project Source: https://context7.com/sema4ai/actions/llms.txt Steps to create a new Action Package project and start the Action Server. ```APIDOC ## Bootstrap a New Project Create and start a new Action Package with the `action-server new` command. ```bash # Create a new project (prompts for project name) action-server new # Navigate to project and start the server cd my-project action-server start # Server runs at http://localhost:8080 # MCP endpoint available at http://localhost:8080/mcp # OpenAPI spec at http://localhost:8080/openapi.json ``` ``` -------------------------------- ### Python Setup Fixture with Scope Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Shows how to use the `@setup` decorator with a `scope` argument to control when the fixture runs. 'action' scope runs before each action, while 'session' scope runs once before all actions. ```python from sema4ai.actions import setup @setup(scope="action") def before_each(action): print(f"Running action '{action.name}'") @setup(scope="session") def before_all(actions): print(f"Running {len(actions)} action(s)") ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/sema4ai/actions/blob/master/CONTRIBUTING.md Installs the necessary development dependencies for the project using pip and a requirements file. This is a prerequisite for setting up the development environment. ```bash pip install -r devutils/requirements.txt ``` -------------------------------- ### Bootstrap New Project with Action Server Source: https://context7.com/sema4ai/actions/llms.txt Creates and starts a new Sema4.ai Actions project. This involves using the `action-server new` command to scaffold the project and then `action-server start` to run the server. ```bash # Create a new project (prompts for project name) action-server new # Navigate to project and start the server cd my-project action-server start # Server runs at http://localhost:8080 # MCP endpoint available at http://localhost:8080/mcp # OpenAPI spec at http://localhost:8080/openapi.json ``` -------------------------------- ### Install Action Server on macOS Source: https://github.com/sema4ai/actions/blob/master/action_server/README.md Installs the Sema4.ai Action Server on macOS using Homebrew. This command updates Homebrew and installs the action-server tool. ```shell # Install Sema4.ai Action Server brew update brew install sema4ai/tools/action-server ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/sema4ai/actions/blob/master/CONTRIBUTING.md Installs project-specific development dependencies using Invoke. This command sets up the environment for a specific project within the monorepo. ```bash inv install ``` -------------------------------- ### Implement Setup and Teardown Fixtures in Python Actions Source: https://context7.com/sema4ai/actions/llms.txt Illustrates how to use setup and teardown fixtures in Python actions for managing initialization and cleanup code. Fixtures can be scoped to the session or individual actions, enabling tasks like database connection management and context preparation/cleanup before and after action execution. ```python from sema4ai.actions import action from sema4ai.actions._fixtures import setup, teardown # Run once before any actions @setup(scope="session") def initialize_database(): """Initialize database connection pool.""" print("Initializing database connection...") # Setup code here return {"db_pool": "initialized"} # Run before each action @setup(scope="action") def prepare_action_context(): """Prepare context for each action.""" print("Preparing action context...") return {"request_id": "req-123"} # Run after each action @teardown(scope="action") def cleanup_action_context(): """Clean up after each action.""" print("Cleaning up action context...") # Run once after all actions @teardown(scope="session") def close_database(): """Close database connections.""" print("Closing database connections...") @action def my_action(input_data: str) -> str: """Action that uses setup/teardown fixtures.""" return f"Processed: {input_data}" ``` -------------------------------- ### Example package.yaml Structure and Fields Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/01-package-yaml.md A commented example demonstrating the structure and required/optional fields of a package.yaml file. It shows how to define package metadata, dependencies (conda-forge and PyPI), development dependencies, development tasks, pythonpath, post-install commands, and packaging exclusions. ```yaml # Required: Defines the name of the `Action Package`. name: My awesome cookie maker # Required: Defines the version of the `Action Package`. # Must be defined as 3 integers separated by dots (major, minor, patch). version: 0.0.1 # The version of the `package.yaml` format. If not specified, defaults to v1. # Note that newer versions of the `Action Server` can usually run an older version # of the `package.yaml` format, but the reverse is not true (older `Action Server` # versions may not be able to run a `package.yaml` with a newer format version). spec-version: v2 # Required: A description of the `Action Package`. description: This does cookies # Required: # Defines the Python dependencies which should be used to launch the # actions. # The `Action Server` will automatically create a new python environment # based on this specification. # Note that at this point the only operator supported is `=`. dependencies: conda-forge: # This section is required: at least the python version must be specified. - python=3.10.12 - uv=0.4.19 pypi: # This section is required: at least `sema4ai-actions` must # be specified. # Note: sema4ai-actions is special case because the `Action Server` # has coupling with the library (so, a newer version of the `Action Server` # might require a newer version of `sema4ai-actions`). - sema4ai-actions=1.3.13 - robocorp=1.4.3 - pytz=2023.3 # Optional (requires Action Server 2.0.0): Defines the development dependencies # which should be used to run development tasks. dev-dependencies: conda-forge: - pytest=8.3.3 pypi: - ruff=0.7.0 - mypy=1.13.0 # Optional (requires Action Server 2.0.0): Defines tasks used during development (they are # run with an environment which has both `dependencies` and `dev-dependencies`). dev-tasks: test: pytest tests lint: ruff check src tests # Optional (requires Action Server 2.0.0): specifies directories to add to the PYTHONPATH. # If it is not specified, only the directory containing the `package.yaml` is added to the pythonpath. pythonpath: - src - tests post-install: # This can be used to run custom commands which will still affect the # environment after it is created (the changes to the environment will # be cached). - python -m robocorp.browser install chrome --isolated packaging: # This section is optional. # By default all files and folders in this directory are packaged when uploaded. # Add exclusion rules below (expects glob format: https://docs.python.org/3/library/glob.html) exclude: - tests/** - "*.temp" - .vscode/** ``` -------------------------------- ### Install Sema4AI MCP Library Source: https://github.com/sema4ai/actions/blob/master/mcp/README.md This command installs the Sema4AI MCP library using pip. Ensure you have Python and pip installed. ```bash pip install sema4ai-mcp ``` -------------------------------- ### Python IAction Input Schema Example Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Provides an example of the `input_schema` property for an `IAction` object, illustrating the structure of expected action inputs. ```json { "properties": { "value": { "type": "integer", "description": "Some value.", "title": "Value", "default": 0 } }, "type": "object" } ``` -------------------------------- ### Python IAction Managed Parameters Schema Example Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Shows an example of the `managed_params_schema` for an `IAction`, detailing how managed parameters like secrets or requests are defined. ```json { "my_password": { "type": "Secret" }, "request": { "type": "Request" } } ``` -------------------------------- ### Install Action Server on Windows Source: https://github.com/sema4ai/actions/blob/master/action_server/README.md Downloads the Sema4.ai Action Server executable for Windows 64-bit and adds it to the system's PATH environment variable. This allows the server to be run from any directory. ```shell # Download Sema4.ai Action Server curl -o action-server.exe https://cdn.sema4.ai/action-server/releases/latest/windows64/action-server.exe # Add to PATH or move to a folder that is in PATH setx PATH=%PATH%;%CD% ``` -------------------------------- ### Python IAction Output Schema Example Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md Presents an example of the `output_schema` property for an `IAction`, defining the structure and type of the action's return value. ```json { "type": "string", "description": "" } ``` -------------------------------- ### Synchronous Action Execution Example (Python) Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/16-run-action-sync-async.md Demonstrates a simple synchronous action 'greet' in Python. The client waits for the action to complete and receives the result in the response body along with the x-action-server-run-id header. ```python @action def greet(name: str) -> str: return f"Hello {name}!" ``` -------------------------------- ### Install Action Server on Linux Source: https://github.com/sema4ai/actions/blob/master/action_server/README.md Downloads the Sema4.ai Action Server executable for Linux 64-bit, makes it executable, and moves it to the system's PATH. This makes the action-server command available globally. ```shell # Download Sema4.ai Action Server curl -o action-server https://cdn.sema4.ai/action-server/releases/latest/linux64/action-server chmod a+x action-server # Add to PATH or move to a folder that is in PATH sudo mv action-server /usr/local/bin/ ``` -------------------------------- ### Install Sema4.ai Action Server via Pip Source: https://github.com/sema4ai/actions/blob/master/README.md Installs the Sema4.ai Action Server using pip, making the `action-server` executable available in your Python environment's scripts or bin directory. ```shell pip install sema4ai-action-server ``` -------------------------------- ### Start Sema4.ai Action Server Source: https://github.com/sema4ai/actions/blob/master/README.md Starts the Sema4.ai Action Server within a project directory. It provides access to the web UI at http://localhost:8080 and the MCP endpoint at http://localhost:8080/mcp. ```shell cd my-project action-server start ``` -------------------------------- ### Start Sema4.ai Action Server with Auto-Reload Source: https://github.com/sema4ai/actions/blob/master/README.md Starts the Sema4.ai Action Server with the `--auto-reload` flag, which is useful during development as it automatically reloads tools and actions when changes are made. ```shell action-server start --auto-reload ``` -------------------------------- ### Install Sema4.ai Action Server CLI for Windows Source: https://github.com/sema4ai/actions/blob/master/README.md Downloads the latest standalone Windows 64-bit executable for the Sema4.ai Action Server. The downloaded file can be moved to a directory in your system's PATH for easy access. ```shell # Download Sema4.ai Action Server curl -o action-server.exe https://cdn.sema4.ai/action-server/releases/latest/windows64/action-server.exe ``` -------------------------------- ### Configure Library Logging and Default Exclusion (TOML) Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/10-generated-logs-and-artifacts.md This example configures specific libraries ('RPA', 'selenium', 'SeleniumLibrary') to be logged with 'log_on_project_call' and sets the default logging kind for all other libraries to 'exclude'. This is useful for controlling log verbosity for external dependencies. ```toml [tool.robocorp.log] log_filter_rules = [ {name = "RPA", kind = "log_on_project_call"}, {name = "selenium", kind = "log_on_project_call"}, {name = "SeleniumLibrary", kind = "log_on_project_call"}, ] default_library_filter_kind = "exclude" ``` -------------------------------- ### Agent Integration - Intelligent Response Action Source: https://context7.com/sema4ai/actions/llms.txt Example of a Python action using agent integration helpers to access context and generate prompts. ```APIDOC ## Python Action: `intelligent_response` ### Description This action demonstrates how to use agent integration helpers like `get_agent_id`, `get_thread_id`, `list_data_frames`, and `prompt_generate` to create context-aware AI responses. ### Method Decorated Python function (`@action`) ### Endpoint (Not directly exposed as a REST endpoint, but callable via the REST API after deployment) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Implicit via function arguments) - **user_query** (string) - Required - The user's question or input. ### Request Example (Python code) ```python from sema4ai.actions import action from sema4ai.actions.agent import ( get_agent_id, get_thread_id, prompt_generate, list_data_frames, get_data_frame ) from sema4ai.actions.agent._models import Prompt, PromptUserMessage, PromptTextContent @action def intelligent_response(user_query: str) -> str: """ Generate an intelligent response using agent context. Args: user_query: The user's question Returns: AI-generated response """ # Get context identifiers agent_id = get_agent_id() thread_id = get_thread_id() # List available data frames available_frames = list_data_frames() # Create a prompt for the AI prompt = Prompt( model="gpt-4", messages=[ PromptUserMessage( content=[ PromptTextContent(text=user_query) ] ) ] ) # Generate response using the prompt response = prompt_generate(prompt) return f"Agent {agent_id} in thread {thread_id}: {response}" ``` ### Response #### Success Response (200) - **result** (string) - The AI-generated response, prefixed with agent and thread information. #### Response Example (from executed action) ``` Agent agent-abc123 in thread thread-xyz789: The weather forecast for Helsinki for the next 3 days is sunny with a high of 15 degrees Celsius. ``` ``` -------------------------------- ### Define MCP Prompt with @prompt Decorator (Python) Source: https://context7.com/sema4ai/actions/llms.txt Creates reusable prompt templates for MCP clients using the `@prompt` decorator. This allows for consistent prompt formatting for LLM interactions. The example defines a prompt for summarizing text. ```python from sema4ai.mcp import prompt @prompt def summarize_document(text: str, max_length: int = 200) -> str: """ Generate a prompt for summarizing text content. Args: text: The text to summarize max_length: Maximum length of the summary Returns: A formatted prompt for the LLM """ return f"Please summarize the following text in {max_length} words or less:\n\n{text}" ``` -------------------------------- ### Calling Actions via REST API Source: https://context7.com/sema4ai/actions/llms.txt Examples of interacting with actions through the auto-generated REST API, including fetching the OpenAPI specification, calling actions without authentication, and using API key or secret-based authentication. ```bash # Get OpenAPI specification curl http://localhost:8080/openapi.json # Call an action (without authentication) curl -X POST http://localhost:8080/api/actions/get-weather-forecast/run \ -H "Content-Type: application/json" \ -d '{"city": "Helsinki", "days": 3, "scale": "celsius"}' # Call with API key authentication curl -X POST http://localhost:8080/api/actions/process-order/run \ -H "Content-Type: application/json" \ -H "Authorization: Bearer my-api-key" \ -d '{"order_id": "ORD-123", "quantity": 5}' # Call with secrets via X-Action-Context header # First, encode the secrets payload SECRETS=$(echo -n '{"secrets":{"api_key":"secret123"}}' | base64) curl -X POST http://localhost:8080/api/actions/query-api/run \ -H "Content-Type: application/json" \ -H "X-Action-Context: $SECRETS" \ -d '{"query": "SELECT * FROM users"}' # View action run history curl http://localhost:8080/api/runs ``` -------------------------------- ### Define AI Action with @action Decorator (Python) Source: https://context7.com/sema4ai/actions/llms.txt Defines an AI action using the `@action` decorator in Python. It includes type hints and a Google-style docstring for documentation and AI agent interaction. The example shows a function to get weather forecasts. ```python from sema4ai.actions import action @action def get_weather_forecast(city: str, days: int, scale: str = "celsius") -> str: """ Returns weather conditions forecast for a given city. Args: city: Target city to get the weather conditions for days: How many day forecast to return scale: Temperature scale to use, should be one of "celsius" or "fahrenheit" Returns: The requested weather conditions forecast """ # Implementation here return f"Weather forecast for {city} for {days} days in {scale}" # Run from command line: # python -m sema4ai.actions run -- --city=Helsinki --days=3 --scale=celsius ``` -------------------------------- ### Running Development Tasks with Action Server Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/14-dev-tasks.md This section provides command-line examples for executing development tasks defined in the `package.yaml` file using the `action-server devenv task` command. It demonstrates how to run tests and linting checks within the action package's environment. ```bash action-server devenv task test ``` ```bash action-server devenv task lint ``` -------------------------------- ### Initialize Bedrock Platform Parameters (Python) Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.agent.md Demonstrates how to initialize BedrockPlatformParameters with different configurations. This class encapsulates parameters for AWS Bedrock client initialization, supporting direct parameters and advanced configuration via botocore.Config. ```python params = BedrockPlatformParameters(region_name='us-east-1') ``` ```python params = BedrockPlatformParameters( endpoint_url='https://bedrock.custom.endpoint', aws_access_key_id='YOUR_KEY', aws_secret_access_key='YOUR_SECRET' ) ``` ```python params = BedrockPlatformParameters( region_name='us-east-1', retries={'max_attempts': 3}, config_params={'connect_timeout': 5, 'read_timeout': 60} ) ``` -------------------------------- ### Document Action Purpose and Inputs/Outputs with Docstrings Source: https://github.com/sema4ai/actions/blob/master/actions/README.md This example shows how to document an action's purpose, arguments, and return values using Google Style Docstrings. This documentation is crucial for AI models and humans to understand the action's functionality. The `get_weather_forecast` action takes city, days, and an optional scale, returning a string forecast. ```python from sema4ai.actions import action @action def get_weather_forecast(city: str, days: int, scale: str = "celsius") -> str: """ Returns weather conditions forecast for a given city. Args: city (str): Target city to get the weather conditions for days: How many day forecast to return scale (str): Temperature scale to use, should be one of "celsius" or "fahrenheit" Returns: str: The requested weather conditions forecast """ ... ``` -------------------------------- ### Alternative Action Server Execution Source: https://github.com/sema4ai/actions/blob/master/action_server/README.md Demonstrates an alternative way to run the Action Server using the Python module directly. This is useful if the 'action-server' executable is not found in the PATH. ```shell python -m sema4ai.action_server ``` -------------------------------- ### Action Server CLI Commands for Management Source: https://context7.com/sema4ai/actions/llms.txt Lists common bash commands for managing the Sema4.ai Action Server. This includes starting the server with various options like auto-reloading, public exposure, custom ports, and API keys, as well as importing actions from multiple directories and building action packages for distribution. ```bash # Start server with default settings action-server start # Start with auto-reload for development action-server start --auto-reload # Start with public exposure (generates public URL) action-server start --expose # Start with custom port and API key action-server start --port=9000 --api-key=my-secret-key # Import actions from multiple directories action-server import --dir=./package1 --datadir=./mydata action-server import --dir=./package2 --datadir=./mydata action-server start --actions-sync=false --datadir=./mydata # Build action package for distribution action-server package build # Output: my-actions.zip ``` -------------------------------- ### Example Native SQL Query Execution Source: https://github.com/sema4ai/actions/blob/master/templates/data-access-native/README.md This example illustrates how a native SQL query, specifically designed for PostgreSQL, would be executed with a given parameter. The query utilizes the `~*` operator for case-insensitive string matching, which is a PostgreSQL-specific feature. The `FROM` clause implicitly refers to the active datasource. ```sql SELECT * FROM public_demo ( SELECT * FROM demo_customers WHERE country ~* 'er' ); ``` -------------------------------- ### Get Artifacts List Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/10-generated-logs-and-artifacts.md Retrieves a list of artifacts generated for a specific action run. ```APIDOC ## GET /api/runs/{run_id}/artifacts ### Description Retrieves a list of artifacts generated for a specific action run. Artifacts typically include output, inputs, results, and logs. ### Method GET ### Endpoint /api/runs/{run_id}/artifacts ### Parameters #### Path Parameters - **run_id** (string) - Required - The unique identifier of the action run. ### Response #### Success Response (200) - **artifacts** (array) - A list of artifact names generated for the run. #### Response Example ```json { "artifacts": [ "__action_server_output.txt", "__action_server_inputs.json", "__action_server_result.json", "log.html", "output.robolog" ] } ``` ``` -------------------------------- ### Get Log HTML Content Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/10-generated-logs-and-artifacts.md Retrieves the HTML content of the log generated during an action run. ```APIDOC ## GET /api/runs/{runId}/log.html ### Description Retrieves the HTML content of the log generated during an action run. This provides a human-readable view of the action's execution. ### Method GET ### Endpoint /api/runs/{runId}/log.html ### Parameters #### Path Parameters - **runId** (string) - Required - The unique identifier of the action run. ### Response #### Success Response (200) - **html_content** (string) - The HTML content of the log file. #### Response Example ```html Action Log

Action Execution Log

Log details here...

``` ``` -------------------------------- ### Package Management and Development Tasks Source: https://context7.com/sema4ai/actions/llms.txt Commands for packaging actions into a zip file, extracting them to a directory, and running development tasks like testing and linting. ```bash action-server package extract my-actions.zip --output-dir=./extracted action-server devenv task test action-server devenv task lint ``` -------------------------------- ### Create New Sema4.ai Action Project Source: https://github.com/sema4ai/actions/blob/master/README.md Initializes a new Sema4.ai action project from a template. This command prompts the user for the project name and sets up the basic project structure. ```shell action-server new ``` -------------------------------- ### Build and Sign Executable with Sema4AI Build Common (Python) Source: https://github.com/sema4ai/actions/blob/master/build_common/README.md This Python code snippet demonstrates how to integrate the `build_and_sign_executable` function from the `sema4ai.build_common.workflows` module. It handles building an executable using PyInstaller, optionally signing it for macOS or Windows, and can also build an accompanying Go wrapper. The function requires the project's root directory, name, and various build configuration options. ```python import typer from pathlib import Path app = typer.Typer() @app.command() def build_executable( debug: bool = typer.Option(False, help="Build in debug mode"), ci: bool = typer.Option( True, help="Build in CI mode, disabling interactive prompts" ), dist_path: Path = typer.Option("dist", help="Path to the dist directory"), sign: bool = typer.Option(False, help="Sign the executable"), go_wrapper: bool = typer.Option(False, help="Build the Go wrapper too"), version: str | None = typer.Option( None, help="Version of the executable (gotten from github tag/pr if not passed)" ), ) -> None: """Build the project executable via PyInstaller.""" from sema4ai.build_common.root_dir import get_root_dir from sema4ai.build_common.workflows import build_and_sign_executable from sema4ai.action_server import __version__ if version is None: version = __version__ # Get version from the project... root_dir = get_root_dir() build_and_sign_executable( root_dir=root_dir, name="action-server", debug=debug, ci=ci, dist_path=root_dir / dist_path, sign=sign, go_wrapper=go_wrapper, version=__version__, ) ``` -------------------------------- ### Get Agent ID Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.agent.md Retrieves the agent ID from the action context or request headers. Raises an ActionError if the agent ID cannot be found. ```APIDOC ## GET /actions/agent/agent_id ### Description Get the agent ID from the action context or the request headers. **Note:** This will raise an ActionError if the agent ID cannot be found. This is expected when calling this function directly from VSCode unless the `x-invoked_by_assistant_id` header is set in the request in configured inputs. ### Method GET ### Endpoint `/actions/agent/agent_id` ### Parameters #### Query Parameters - **x-invoked-by-assistant-id** (string) - Optional - The assistant ID header. ### Response #### Success Response (200) - **agent_id** (string) - The identifier for the current agent. #### Response Example ```json { "agent_id": "agent_abcde" } ``` ``` -------------------------------- ### Get Thread ID Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.agent.md Retrieves the thread ID from the action context or request headers. Raises an ActionError if the thread ID cannot be found. ```APIDOC ## GET /actions/agent/thread_id ### Description Get the thread ID from the action context or the request headers. **Note:** This will raise an ActionError if the thread ID cannot be found. This is expected when calling this function directly from VSCode unless the `x-invoked_for_thread_id` header is set in the request in configured inputs. ### Method GET ### Endpoint `/actions/agent/thread_id` ### Parameters #### Query Parameters - **x-invoked-for-thread-id** (string) - Optional - The thread ID header. ### Response #### Success Response (200) - **thread_id** (string) - The identifier for the current thread. #### Response Example ```json { "thread_id": "thread_12345" } ``` ``` -------------------------------- ### Build SSL Context Source: https://github.com/sema4ai/actions/blob/master/sema4ai-http-helper/README.md Creates an SSL context that utilizes the operating system's certificate store and optionally enables legacy server renegotiation support. ```APIDOC ## Build SSL Context ### Description Constructs an `ssl.SSLContext` object that integrates with the system's trusted certificate authorities and can be configured for legacy server compatibility. ### Method `build_ssl_context(protocol: int = None, *, enable_legacy_server_connect: bool = False) -> ssl.SSLContext` ### Parameters #### Query Parameters - **protocol** (int) - Optional - Specifies the SSL/TLS protocol version to use (e.g., `ssl.PROTOCOL_TLS_CLIENT`). If `None`, a default is used. - **enable_legacy_server_connect** (bool) - Optional - If `True`, enables support for legacy SSL/TLS renegotiation, which might be required for older servers. Defaults to `False`. ### Returns - **ssl.SSLContext** - An `ssl.SSLContext` object configured with system trust store and specified protocol/renegotiation settings. ### Request Example ```python import ssl from sema4ai_http import build_ssl_context # Build a default SSL context context = build_ssl_context() # Build an SSL context with legacy support legacy_context = build_ssl_context(enable_legacy_server_connect=True) # Build an SSL context with a specific protocol tls_context = build_ssl_context(protocol=ssl.PROTOCOL_TLS_CLIENT) ``` ### Response Example (This function returns an `ssl.SSLContext` object, not a JSON response. The example above shows how to use the returned object.) ``` -------------------------------- ### Get File Content Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.chat.md Retrieves the raw content of a file from the current action chat. Raises an exception if the file does not exist or cannot be retrieved. ```APIDOC ## `get_file_content` ### Description Gets the content of a file in the current action chat. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (str) - Required - Name of the file. ### Request Example ```python file_data = get_file_content(name='example.txt') ``` ### Response #### Success Response (bytes) - **Returns** - Raw content of the file. #### Response Example ``` b'file content' ``` #### Error Response - **Exception** - If the file does not exist or cannot be retrieved. ``` -------------------------------- ### GitHub Actions Workflow for Building and Signing Executable (YAML) Source: https://github.com/sema4ai/actions/blob/master/build_common/README.md This YAML snippet outlines a GitHub Actions workflow job for building and signing a Sema4AI server binary. It utilizes `uv run python -m sai_tasks build-executable` and configures necessary environment variables for both macOS and Windows signing processes, including certificate details, Apple IDs, and Azure Key Vault credentials. ```yaml - name: Build SAI Server binary run: uv run python -m sai_tasks build-executable --sign --go-wrapper env: MACOS_SIGNING_CERT: ${{ secrets.MACOS_SIGNING_CERT_SEMA4AI }} MACOS_SIGNING_CERT_PASSWORD: ${{ secrets.MACOS_SIGNING_CERT_PASSWORD_SEMA4AI }} MACOS_SIGNING_CERT_NAME: ${{ secrets.MACOS_SIGNING_CERT_NAME_SEMA4AI }} APPLEID: ${{ secrets.MACOS_APP_ID_FOR_NOTARIZATION_SEMA4AI }} APPLETEAMID: ${{ secrets.MACOS_TEAM_ID_FOR_NOTARIZATION_SEMA4AI }} APPLEIDPASS: ${{ secrets.MACOS_APP_ID_PASSWORD_FOR_NOTARIZATION_SEMA4AI }} VAULT_URL: ${{ secrets.WIN_SIGN_AZURE_KEY_VAULT_URL_SEMA4AI }} CLIENT_ID: ${{ secrets.WIN_SIGN_AZURE_KEY_VAULT_CLIENT_ID_SEMA4AI }} TENANT_ID: ${{ secrets.WIN_SIGN_AZURE_KEY_VAULT_TENANT_ID_SEMA4AI }} CLIENT_SECRET: ${{ secrets.WIN_SIGN_AZURE_KEY_VAULT_CLIENT_SECRET_SEMA4AI }} CERTIFICATE_NAME: ${{ secrets.WIN_SIGN_AZURE_KEY_VAULT_CERTIFICATE_NAME_SEMA4AI }} GITHUB_EVENT_NAME: ${{ github.event_name }} GITHUB_REF_NAME: ${{ github.ref_name }} GITHUB_PR_NUMBER: ${{ github.event.pull_request.number }} ``` -------------------------------- ### Get Specific Artifact Content Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/10-generated-logs-and-artifacts.md Retrieves the content of a specific artifact from an action run. Supports text or binary content. ```APIDOC ## GET /api/runs/{runId}/artifacts/{artifact_name}/text-content ### Description Retrieves the text content of a specific artifact from an action run. ### Method GET ### Endpoint /api/runs/{runId}/artifacts/{artifact_name}/text-content ### Parameters #### Path Parameters - **runId** (string) - Required - The unique identifier of the action run. - **artifact_name** (string) - Required - The name of the artifact to retrieve. ### Response #### Success Response (200) - **content** (string) - The text content of the artifact. #### Response Example ```json { "content": "This is the text content of the artifact." } ``` ## GET /api/runs/{runId}/artifacts/{artifact_name}/binary-content ### Description Retrieves the binary content of a specific artifact from an action run. ### Method GET ### Endpoint /api/runs/{runId}/artifacts/{artifact_name}/binary-content ### Parameters #### Path Parameters - **runId** (string) - Required - The unique identifier of the action run. - **artifact_name** (string) - Required - The name of the artifact to retrieve. ### Response #### Success Response (200) - **content** (binary) - The binary content of the artifact. #### Response Example (Binary data would be returned here) ``` -------------------------------- ### Get Data Frame Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.agent.md Retrieves a specific data frame by name from the current thread, with options for limiting rows, offsetting, selecting columns, and ordering. ```APIDOC ## GET /actions/agent/get_data_frame ### Description Get a data frame by name from the current thread. **Note:** This function requires the agent-server to support the dataframes API endpoint. If the endpoint is not available, this will raise an ActionError. ### Method GET ### Endpoint `/actions/agent/get_data_frame` ### Parameters #### Query Parameters - **name** (string) - Required - Name of the data frame to retrieve. - **limit** (integer) - Optional - Maximum number of rows to fetch (default: 1000). For very large dataframes, consider using SQL to filter data before fetching. - **offset** (integer) - Optional - Number of rows to skip from the beginning (default: 0). Useful for pagination when combined with limit. - **column_names** (list[string]) - Optional - List of specific column names to retrieve. If not provided, all columns are returned. - **order_by** (string) - Optional - Column name to sort by. ### Response #### Success Response (200) - **table** (Table) - An object representing the data frame contents, including: - **columns** (list[string]) - **rows** (list[list]) - **name** (str | None) - **description** (str | None) #### Response Example ```json { "table": { "columns": ["Date", "Product", "Quantity"], "rows": [ ["2023-01-01", "Laptop", 10], ["2023-01-01", "Mouse", 50] ], "name": "sales_data_subset", "description": "First 2 rows of sales data" } } ``` ``` -------------------------------- ### Configure httpx Client with Proxies and SSL Source: https://github.com/sema4ai/actions/blob/master/sema4ai-http-helper/README.md Demonstrates how to configure an httpx client with proxy and SSL settings obtained from sema4ai_http's get_network_profile(). This allows for secure and proxied network requests. ```python from sema4ai_http import get_network_profile from itertools import chain import httpx # Get the network profile which contains SSL context and proxy configuration network_config = get_network_profile() # Set up mounts for proxy configuration mounts: dict[str, httpx.HTTPTransport | None] = {} for http_proxy in chain( network_config.proxy_config.http, network_config.proxy_config.https ): mounts[http_proxy] = httpx.HTTPTransport(network_config.ssl_context) for no_proxy in network_config.proxy_config.no_proxy: mounts[no_proxy] = None # Create httpx client with the configured mounts and SSL context client = httpx.Client(mounts=mounts, verify=network_config.ssl_context) ``` -------------------------------- ### Configure Pyenv for Python Version (Bash) Source: https://github.com/sema4ai/actions/blob/master/CONTRIBUTING.md Installs and sets the local Python version using Pyenv, ensuring isolated interpreter usage for development. ```bash pyenv install 3.10.12 pyenv local 3.10.12 ``` -------------------------------- ### Python: Configure Data Context for Action Server Source: https://github.com/sema4ai/actions/blob/master/action_server/docs/guides/21-call-action.md This Python code snippet demonstrates how to construct the `data_context` dictionary for the `X-Data-Context` header. It iterates through available data server endpoints and populates the context with connection details for HTTP and MySQL protocols, including credentials. ```python data_context = {"data-server": {}} for endpoint in self.data_server_details.data_server_endpoints: if endpoint.kind == DataServerEndpointKind.HTTP: data_context["data-server"]["http"] = { "url": f"http://{endpoint.full_address}", "user": self.data_server_details.username, "password": self.data_server_details.password_str, } elif endpoint.kind == DataServerEndpointKind.MYSQL: data_context["data-server"]["mysql"] = { "host": endpoint.host, "port": endpoint.port, "user": self.data_server_details.username, "password": self.data_server_details.password_str, } ``` -------------------------------- ### REST API - Get OpenAPI Specification Source: https://context7.com/sema4ai/actions/llms.txt Retrieve the OpenAPI specification for the Actions REST API. This specification describes all available endpoints, parameters, and response formats. ```APIDOC ## GET /openapi.json ### Description Retrieves the OpenAPI specification for the Actions REST API. ### Method GET ### Endpoint /openapi.json ### Parameters None ### Request Example ```bash curl http://localhost:8080/openapi.json ``` ### Response #### Success Response (200) - **openapi_spec** (object) - The OpenAPI specification in JSON format. #### Response Example (Content will be the OpenAPI JSON specification) ``` -------------------------------- ### Prompt Class Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.agent.md Documentation for the `Prompt` class, which represents a complete prompt for an AI model interaction. ```APIDOC ## Class `Prompt` Represents a complete prompt for an AI model interaction. This class encapsulates all components needed for an AI interaction, including the system instruction, temperature setting, and the conversation history. The conversation history must follow a strict user-agent interleaving pattern (starting with a user message, then alternating between groups of user and agent messages). ``` -------------------------------- ### AI Platform Parameters Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/README.md Classes for configuring parameters for various AI platforms. ```APIDOC ## Class: AzureOpenAIPlatformParameters ### Description Parameters for the Azure OpenAI platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: BedrockPlatformParameters ### Description Parameters for the Bedrock platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: CortexPlatformParameters ### Description Parameters for the Snowflake Cortex platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: GooglePlatformParameters ### Description Parameters for the Google platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: GroqPlatformParameters ### Description Parameters for the Groq platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: OpenAIPlatformParameters ### Description Parameters for the OpenAI platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: ReductoPlatformParameters ### Description Parameters for the Reducto platform. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Get current action information Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md The `get_current_action` function returns information about the action currently being executed, or `None` if no action is running. This can be useful for context-aware logic within an action. ```python get_current_action() → Optional[IAction] ``` -------------------------------- ### Teardown Fixture Source: https://github.com/sema4ai/actions/blob/master/actions/docs/api/sema4ai.actions.md The `teardown` fixture allows you to run code after actions have been executed. Similar to `setup`, it can be used as a decorator with or without a `scope` argument ('action' or 'session') to define the execution timing. ```APIDOC ## POST /teardown ### Description Runs code after actions have been run, or after each separate action. ### Method POST (or decorator usage) ### Endpoint N/A (decorator) or internal endpoint for teardown execution ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (when used as decorator) ### Request Example ```python from sema4ai.actions import teardown @teardown def my_fixture(action): print(f"After action: {action.name}) @teardown(scope="action") def after_each(action): print(f"Action '{action.name}' status is '{action.status}'") @teardown(scope="session") def after_all(actions): print(f"Executed {len(actions)} action(s)") ``` ### Response #### Success Response (200) N/A (decorator usage, returns callable) #### Response Example N/A ``` -------------------------------- ### Python Agent Integration Helpers Source: https://context7.com/sema4ai/actions/llms.txt Python code demonstrating how to use agent integration helpers to access agent context, list and retrieve data frames, and generate prompts for AI models. ```python from sema4ai.actions import action from sema4ai.actions.agent import ( get_agent_id, get_thread_id, prompt_generate, list_data_frames, get_data_frame ) from sema4ai.actions.agent._models import Prompt, PromptUserMessage, PromptTextContent @action def intelligent_response(user_query: str) -> str: """ Generate an intelligent response using agent context. Args: user_query: The user's question Returns: AI-generated response """ # Get context identifiers agent_id = get_agent_id() thread_id = get_thread_id() # List available data frames available_frames = list_data_frames() # Create a prompt for the AI prompt = Prompt( model="gpt-4", messages=[ PromptUserMessage( content=[PromptTextContent(text=user_query)] ) ] ) # Generate response using the prompt response = prompt_generate(prompt) return f"Agent {agent_id} in thread {thread_id}: {response}" ```