Skip to main content

Core Concepts & APIs (optimizely-opal.opal-tools-sdk)

Outline

To access the SDK, please visit:
https://pypi.org/project/optimizely-opal.opal-tools-sdk/

This module introduces you to the fundamental building blocks of the Optimizely Opal Tools SDK for Python. We'll explore how to install it, and understand the key features and APIs that simplify the process of creating Opal-compatible tool services using Python.

By the end of this module, you will be able to:

  • Install and set up the Python SDK in your project.

  • Create and configure a project directory and virtual environment.

  • Run a basic Opal tool service using FastAPI.

Installation and Project Setup

Before you can use the SDK, you need to set up your Python project and install the package.

Prerequisites:

  • Python 3.10+ installed.
  • pip (Python's package installer) installed.
  • A basic understanding of Python and virtual environments.
  • An IDE like VS Code or PyCharm.

Steps to Install:

  • Create a new project directory (if you haven't already):

mkdir my-opal-python-tools
cd my-opal-python-tools

  • Create and activate a virtual environment: This is a best practice to isolate your project's dependencies.

python -m venv venv
# On Windows:
.\venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

  • Install the Optimizely Opal Tools SDK and FastAPI:

pip install optimizely-opal.opal-tools-sdk "fastapi[all]" uvicorn

  • optimizely-opal.opal-tools-sdk: The core SDK.
  • fastapi[all]: The FastAPI framework, including all optional dependencies for features like Pydantic for data validation.
  • uvicorn: An ASGI server to run your FastAPI application.

The @tool Decorator

The @tool decorator is the primary way to define your Opal tools in Python. You apply it to an async function to tell the Opal SDK that this function should be exposed as a callable tool.

  • Purpose: It simplifies the process of registering your tool with the SDK. The decorator handles the underlying mechanics of generating the tool manifest and setting up the necessary HTTP endpoints (discovery and execution) within your FastAPI application.
  • Usage: You'll typically apply @tool() to an async function that contains your tool's logic. The decorator takes a name and description, and the function's parameters will be automatically inferred or explicitly defined.

FastAPI Integration

The Python SDK is designed to work seamlessly with FastAPI, a modern, fast (high-performance) web framework for building APIs with Python.

  • Automatic Endpoint Setup: The SDK leverages FastAPI to automatically set up:
    • The /discovery endpoint: This is the endpoint Opal calls to discover all the tools your service offers. The SDK generates and serves the tool manifest dynamically.
    • Tool execution routes: For each tool you define with @tool(), the SDK creates a corresponding HTTP route (e.g., /tools/your_tool_name) that Opal will call to execute your tool.
  • Benefits: FastAPI's automatic data validation, serialization, and interactive API documentation (Swagger UI/ReDoc) greatly enhance the development experience for Opal tools.

Parameter Handling and Type Hinting

Python's type hints are crucial for defining your tool's parameters. The SDK uses these type hints to automatically generate the tool's schema in the manifest and perform validation.

  • Importance: Specifying types allows the SDK to validate incoming data, preventing common errors and ensuring your tool receives data in the expected format. This also helps Opal's AI understand how to use your tool correctly.
  • Supported Types: Standard Python types like str, int, float, bool, list, dict, and Pydantic models for complex objects.

Authentication Helpers

Security is crucial for any tool that interacts with sensitive data or performs critical operations. The SDK provides utilities to assist with managing authentication flows and securing your tool's endpoints.

  • Purpose: These helpers allow you to validate incoming requests from Opal, ensuring that only authorized calls trigger your tools. This often involves checking for specific headers (like Authorization: Bearer <token>) and validating the provided token or credentials.
  • Usage: The SDK provides mechanisms to define authentication requirements in your tool's manifest and to enforce them on tool functions using decorators like @requires_auth.

Example of a Basic main.py for an Opal Tool Service:

from fastapi import FastAPI
from optimizely_opal.opal_tools_sdk import OpalToolsService, tool
from pydantic import BaseModel

# Define a Pydantic model for tool parameters (optional, but good practice for complex types)
class GreetingParams(BaseModel):
    name: str
    language: str = "en" # Default value

# Initialize FastAPI app
app = FastAPI()

# Initialize OpalToolsService
opal_tools_service = OpalToolsService(app)

# Define a simple tool using the @tool decorator
@tool(name="hello_world", description="A simple tool that returns a greeting.")
async def hello_world_tool(params: GreetingParams):
    """
    Greets a person by name in a specified language.
    """
    if params.language == "es":
        greeting = f"¡Hola, {params.name} desde la herramienta Opal!"
    else:
        greeting = f"Hello, {params.name} from Opal Tool!"
    return {"message": greeting}

# Register the tool with the service
opal_tools_service.register_tool(hello_world_tool)

# To run this application:
# Save this code as main.py
# Run from your terminal: uvicorn main:app --reload --port 8000
#
# Then access:
# Discovery endpoint: http://localhost:8000/discovery
# Try calling the tool: POST http://localhost:8000/tools/hello_world with JSON body:
# { "name": "Opal", "language": "es" }

In the next module, we'll dive deeper into defining tools and their parameters with more practical examples.