Skip to content

Interfaces API

Complete API reference for SDK interfaces.

Overview

Interfaces define contracts for extensible components. Implement these to create custom validators, search handlers, LLM services, and more.


ValidatorInterface

class ValidatorInterface(ABC):
    """Abstract interface for custom validators."""

Methods

validate

@abstractmethod
def validate(self, data: Dict[str, Any]) -> ValidationResult

Validate the input data.

Parameters:

Parameter Type Description
data Dict[str, Any] Data to validate

Returns: ValidationResult with validation status and any errors

get_validator_name

@abstractmethod
def get_validator_name(self) -> str

Get the name of this validator.

Returns: str - Validator name

Example Implementation

from akordi_agents.core.interfaces import ValidatorInterface
from akordi_agents.models.validation_models import ValidationResult, ValidationError

class MyValidator(ValidatorInterface):
    def validate(self, data: Dict[str, Any]) -> ValidationResult:
        errors = []

        # Validation logic
        if not data.get("query"):
            errors.append(ValidationError(
                field="query",
                message="Query is required"
            ))

        return ValidationResult(
            is_valid=len(errors) == 0,
            errors=errors
        )

    def get_validator_name(self) -> str:
        return "my_validator"

DataModelInterface

class DataModelInterface(ABC):
    """Abstract interface for custom data models."""

Methods

validate_data

@abstractmethod
def validate_data(self, data: Dict[str, Any]) -> bool

Validate that data conforms to this model.

Parameters:

Parameter Type Description
data Dict[str, Any] Data to validate

Returns: bool - True if data is valid

create_instance

@abstractmethod
def create_instance(self, data: Dict[str, Any]) -> BaseModel

Create an instance of this model from data.

Parameters:

Parameter Type Description
data Dict[str, Any] Data to create instance from

Returns: BaseModel - Model instance

get_model_name

@abstractmethod
def get_model_name(self) -> str

Get the name of this data model.

Returns: str - Model name

Example Implementation

from akordi_agents.core.interfaces import DataModelInterface
from pydantic import BaseModel

class UserRequest(BaseModel):
    query: str
    user_id: str
    max_tokens: int = 1000

class UserRequestModel(DataModelInterface):
    def validate_data(self, data: Dict[str, Any]) -> bool:
        try:
            UserRequest(**data)
            return True
        except Exception:
            return False

    def create_instance(self, data: Dict[str, Any]) -> BaseModel:
        return UserRequest(**data)

    def get_model_name(self) -> str:
        return "user_request"

SearchHandlerInterface

class SearchHandlerInterface(ABC):
    """Abstract interface for custom search handlers."""

Methods

@abstractmethod
def search(self, query: str, **kwargs) -> List[SearchResult]

Perform a search operation.

Parameters:

Parameter Type Description
query str Search query
**kwargs - Additional search parameters

Returns: List[SearchResult] - List of search results

get_handler_name

@abstractmethod
def get_handler_name(self) -> str

Get the name of this search handler.

Returns: str - Handler name

Example Implementation

from akordi_agents.core.interfaces import SearchHandlerInterface
from akordi_agents.models.types import SearchResult

class MySearchHandler(SearchHandlerInterface):
    def __init__(self, index_url: str, api_key: str):
        self.index_url = index_url
        self.api_key = api_key

    def search(self, query: str, **kwargs) -> List[SearchResult]:
        max_results = kwargs.get("max_results", 10)

        # Your search implementation
        raw_results = self.call_search_api(query, max_results)

        return [
            SearchResult(
                text=r["content"],
                score=r["relevance_score"],
                metadata=r.get("metadata", {})
            )
            for r in raw_results
        ]

    def get_handler_name(self) -> str:
        return "my_search_handler"

LLMServiceInterface

class LLMServiceInterface(ABC):
    """Abstract interface for custom LLM services."""

Methods

generate_response

@abstractmethod
def generate_response(
    self,
    prompt: str,
    context: Optional[str] = None,
    **kwargs
) -> Dict[str, Any]

Generate a response using the LLM.

Parameters:

Parameter Type Description
prompt str Input prompt
context str Optional context
**kwargs - Additional generation parameters

Returns: Dict[str, Any] - Generated response with metadata

Expected Return Format:

{
    "response": str,           # Generated text
    "model_info": {
        "model_id": str,
        "provider": str,
    },
    "token_usage": {
        "input_tokens": int,
        "output_tokens": int,
        "total_tokens": int,
    },
}

get_service_name

@abstractmethod
def get_service_name(self) -> str

Get the name of this LLM service.

Returns: str - Service name

Example Implementation

from akordi_agents.core.interfaces import LLMServiceInterface

class MyLLMService(LLMServiceInterface):
    def __init__(self, api_key: str, model: str = "default"):
        self.api_key = api_key
        self.model = model

    def generate_response(
        self,
        prompt: str,
        context: Optional[str] = None,
        **kwargs
    ) -> Dict[str, Any]:
        # Prepare request
        messages = []
        if context:
            messages.append({"role": "system", "content": context})
        messages.append({"role": "user", "content": prompt})

        # Call your LLM API
        response = self.call_api(messages, **kwargs)

        return {
            "response": response["text"],
            "model_info": {
                "model_id": self.model,
                "provider": "my_provider",
            },
            "token_usage": {
                "input_tokens": response["input_tokens"],
                "output_tokens": response["output_tokens"],
                "total_tokens": response["total_tokens"],
            },
        }

    def get_service_name(self) -> str:
        return "my_llm_service"

AgentInterface

class AgentInterface(ABC):
    """Abstract interface for custom agents."""

Methods

process_request

@abstractmethod
def process_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]

Process a request and return a response.

Parameters:

Parameter Type Description
request_data Dict[str, Any] Input request data

Returns: Dict[str, Any] - Response data

initialize

@abstractmethod
def initialize(self, config: Dict[str, Any]) -> None

Initialize the agent with configuration.

Parameters:

Parameter Type Description
config Dict[str, Any] Agent configuration

get_agent_name

@abstractmethod
def get_agent_name(self) -> str

Get the name of this agent.

Returns: str - Agent name

Example Implementation

from akordi_agents.core.interfaces import AgentInterface

class MyAgent(AgentInterface):
    def __init__(self, name: str):
        self.name = name
        self.config = {}
        self._initialized = False

    def initialize(self, config: Dict[str, Any]) -> None:
        self.config = config
        self._initialized = True

    def process_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        if not self._initialized:
            self.initialize({})

        query = request_data.get("query", "")

        # Process the request
        response = self.generate_response(query)

        return {
            "success": True,
            "agent": self.name,
            "response": response,
        }

    def get_agent_name(self) -> str:
        return self.name

Validation Models

ValidationResult

@dataclass
class ValidationResult:
    """Result of validation operation."""

    is_valid: bool                    # Whether validation passed
    errors: List[ValidationError]     # List of validation errors

ValidationError

@dataclass
class ValidationError:
    """A single validation error."""

    field: str       # Field that failed validation
    message: str     # Error message

SearchResult

@dataclass
class SearchResult:
    """A single search result."""

    text: str                          # Result text content
    score: float                       # Relevance score
    metadata: Dict[str, Any] = {}      # Additional metadata

Registration Functions

register_validator

def register_validator(name: str, validator_class: type) -> None

Register a validator class for use with AgentBuilder.

from akordi_agents.core import register_validator

register_validator("my_validator", MyValidator)

register_data_model

def register_data_model(name: str, model_class: type) -> None

Register a data model class.

register_search_handler

def register_search_handler(name: str, handler_class: type) -> None

Register a search handler class.

register_llm_service

def register_llm_service(name: str, service_class: type) -> None

Register an LLM service class.


Retrieval Functions

get_validator

def get_validator(name: str) -> Optional[type]

Get a registered validator class by name.

get_data_model

def get_data_model(name: str) -> Optional[type]

Get a registered data model class by name.

get_search_handler

def get_search_handler(name: str) -> Optional[type]

Get a registered search handler class by name.

get_llm_service

def get_llm_service(name: str) -> Optional[type]

Get a registered LLM service class by name.


ComponentRegistry

class ComponentRegistry:
    """Thread-safe registry for managing components."""

Methods

def register(self, category: str, name: str, component: type) -> None
def get(self, category: str, name: str) -> Optional[type]
def list_all(self, category: str) -> Dict[str, type]
def unregister(self, category: str, name: str) -> bool

Usage

from akordi_agents.core import ComponentRegistry

registry = ComponentRegistry()

# Register
registry.register("validators", "my_validator", MyValidator)

# Retrieve
validator_class = registry.get("validators", "my_validator")

# List all
all_validators = registry.list_all("validators")