or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

chat-interface.mdclient-management.mddocument-prompt-template.mdembeddings.mdevaluation.mdexplanations.mdindex.mdprompt-construction.mdsteering.mdstructured-output.mdtext-completion.mdtokenization.mdtranslation.mdutilities.md
tile.json

tessl/pypi-aleph-alpha-client

Python client to interact with Aleph Alpha API endpoints

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/aleph-alpha-client@11.2.x

To install, run

npx @tessl/cli install tessl/pypi-aleph-alpha-client@11.2.0

index.mddocs/

Aleph Alpha Client

A comprehensive Python client library for interacting with Aleph Alpha's language model APIs. The library provides both synchronous and asynchronous client implementations for accessing various AI capabilities including text completion, embeddings, semantic search, chat interfaces, and task-specific endpoints.

Package Information

  • Package Name: aleph-alpha-client
  • Language: Python
  • Installation: pip install aleph-alpha-client
  • Python Requirements: >=3.9,<3.14

Core Imports

from aleph_alpha_client import Client, AsyncClient

Common imports for different functionality:

from aleph_alpha_client import (
    Client, AsyncClient,
    CompletionRequest, CompletionResponse,
    ChatRequest, ChatResponse, Message, TextMessage, Role,
    Prompt, Text, Image, Tokens,
    EmbeddingRequest, EmbeddingV2Request, SemanticEmbeddingRequest,
    ExplanationRequest, EvaluationRequest,
    TokenizationRequest, DetokenizationRequest,
    TranslationRequest, TranslationResponse,
    Document, PromptTemplate,
    JSONSchema, ResponseFormat,
    SteeringPairedExample, SteeringConceptCreationRequest,
    load_base64_from_file, load_base64_from_url
)

Basic Usage

from aleph_alpha_client import Client, CompletionRequest, Prompt

# Initialize client
client = Client(token="your-api-token")

# Simple text completion
request = CompletionRequest(
    prompt=Prompt.from_text("Tell me about artificial intelligence"),
    maximum_tokens=100
)
response = client.complete(request, model="luminous-extended")
print(response.completions[0].completion)

# Async client usage
import asyncio
from aleph_alpha_client import AsyncClient

async def main():
    async with AsyncClient(token="your-api-token") as client:
        response = await client.complete(request, model="luminous-extended")
        print(response.completions[0].completion)

asyncio.run(main())

Architecture

The library is organized around several key components:

  • Client Classes: Client and AsyncClient provide the main interface to Aleph Alpha APIs
  • Request/Response Objects: Structured data classes for each API endpoint
  • Prompt System: Flexible multimodal prompt construction with Prompt, Text, Image, and Tokens
  • Control Mechanisms: Fine-grained attention control through TextControl, ImageControl, and TokenControl
  • Exception Handling: Custom exceptions for quota limits (QuotaError) and service availability (BusyError)

This design enables comprehensive access to Aleph Alpha's language models while providing strong typing, async support, and advanced features like prompt templating, model explanations, and structured output generation.

Capabilities

Client Management

Core client classes for synchronous and asynchronous API access, with connection management, authentication, retry logic, and error handling.

class Client:
    def __init__(
        self,
        token: str,
        host: str = "https://api.aleph-alpha.com",
        hosting: Optional[str] = None,
        request_timeout_seconds: int = 305,
        total_retries: int = 8,
        nice: bool = False,
        verify_ssl: bool = True
    ): ...

class AsyncClient:
    def __init__(
        self,
        token: str,
        host: str = "https://api.aleph-alpha.com",
        hosting: Optional[str] = None,
        request_timeout_seconds: int = 305,
        total_retries: int = 8,
        nice: bool = False,
        verify_ssl: bool = True
    ): ...
    
    async def close(self) -> None: ...

Client Management

Prompt Construction

Flexible multimodal prompt system supporting text, images, and tokens with advanced attention control mechanisms.

class Prompt:
    def __init__(self, items: Union[str, Sequence[PromptItem]]): ...
    
    @staticmethod
    def from_text(text: str, controls: Optional[Sequence[TextControl]] = None) -> Prompt: ...
    
    @staticmethod 
    def from_image(image: Image) -> Prompt: ...

class Text:
    text: str
    controls: Sequence[TextControl]

class Image:
    base_64: str
    cropping: Optional[Cropping]
    controls: Sequence[ImageControl]
    
    @classmethod
    def from_file(cls, path: Union[str, Path], controls: Optional[Sequence[ImageControl]] = None) -> Image: ...

Prompt Construction

Text Completion

Generate text continuations with extensive sampling controls, multiple completions, and streaming support.

class CompletionRequest:
    prompt: Prompt
    maximum_tokens: Optional[int] = None
    temperature: float = 0.0
    top_k: int = 0
    top_p: float = 0.0
    presence_penalty: float = 0.0
    frequency_penalty: float = 0.0
    stop_sequences: Optional[List[str]] = None
    n: int = 1

def complete(self, request: CompletionRequest, model: str) -> CompletionResponse: ...
async def complete_with_streaming(self, request: CompletionRequest, model: str) -> AsyncGenerator: ...

Text Completion

Chat Interface

Conversational AI interface with message handling, streaming, and structured output support.

class ChatRequest:
    model: str
    messages: Sequence[Union[Message, TextMessage]]
    maximum_tokens: Optional[int] = None
    temperature: Optional[float] = None
    response_format: Optional[ResponseFormat] = None

class Message:
    role: Role
    content: Union[str, List[Union[str, Image]]]

def chat(self, request: ChatRequest, model: str) -> ChatResponse: ...
async def chat_with_streaming(self, request: ChatRequest, model: str) -> AsyncGenerator: ...

Chat Interface

Embeddings & Semantic Search

Generate vector embeddings for text and images with multiple representation types and batch processing capabilities.

class SemanticEmbeddingRequest:
    prompt: Prompt
    representation: SemanticRepresentation
    compress_to_size: Optional[int] = None
    normalize: bool = False

class BatchSemanticEmbeddingRequest:
    prompts: Sequence[Prompt]
    representation: SemanticRepresentation
    compress_to_size: Optional[int] = None
    normalize: bool = False

def semantic_embed(self, request: SemanticEmbeddingRequest, model: str) -> SemanticEmbeddingResponse: ...
def batch_semantic_embed(self, request: BatchSemanticEmbeddingRequest, model: Optional[str] = None) -> BatchSemanticEmbeddingResponse: ...

Embeddings & Semantic Search

Model Explanations

Generate explanations for model predictions showing which parts of the input influenced the output, with configurable granularity and postprocessing.

class ExplanationRequest:
    prompt: Prompt
    target: str
    prompt_granularity: Optional[Union[PromptGranularity, str, CustomGranularity]] = None
    target_granularity: Optional[TargetGranularity] = None
    postprocessing: Optional[ExplanationPostprocessing] = None

def explain(self, request: ExplanationRequest, model: str) -> ExplanationResponse: ...

Model Explanations

Tokenization & Text Processing

Convert between text and tokens, with support for different tokenization strategies and detokenization.

class TokenizationRequest:
    prompt: str
    tokens: bool
    token_ids: bool

class DetokenizationRequest:
    token_ids: Sequence[int]

def tokenize(self, request: TokenizationRequest, model: str) -> TokenizationResponse: ...
def detokenize(self, request: DetokenizationRequest, model: str) -> DetokenizationResponse: ...

Tokenization & Text Processing

Evaluation & Testing

Evaluate model performance against expected outputs with detailed metrics and analysis.

class EvaluationRequest:
    prompt: Prompt
    completion_expected: str

def evaluate(self, request: EvaluationRequest, model: str) -> EvaluationResponse: ...

Evaluation & Testing

Structured Output & Response Formatting

Generate structured JSON output that conforms to specified schemas, with support for both manual JSON schemas and automatic Pydantic model integration.

class JSONSchema:
    schema: Mapping[str, Any]
    name: str
    description: Optional[str] = None
    strict: Optional[bool] = False
    
    @classmethod
    def from_pydantic(cls, model_class: Type[BaseModel]) -> JSONSchema: ...

ResponseFormat = Union[JSONSchema, Type[BaseModel]]

Structured Output

Translation Services

Translate text between languages using Aleph Alpha's translation models with quality scoring and segment-level analysis.

class TranslationRequest:
    model: str
    source: str
    target_language: str

class TranslationResponse:
    translation: str
    score: float
    segments: Optional[List[TranslationSegment]]
    num_tokens_prompt_total: int
    num_tokens_generated: int

def translate(self, request: TranslationRequest) -> TranslationResponse: ...

Translation Services

Steering & Content Control

Create and use steering concepts to guide model behavior and output style through positive and negative examples.

class SteeringPairedExample:
    negative: str
    positive: str

class SteeringConceptCreationRequest:
    examples: List[SteeringPairedExample]

def create_steering_concept(self, request: SteeringConceptCreationRequest) -> SteeringConceptCreationResponse: ...

Steering & Content Control

Document & Prompt Templates

Advanced prompt construction tools supporting DOCX documents and reusable template generation with Liquid syntax.

class Document:
    @classmethod
    def from_docx_file(cls, path: str) -> Document: ...
    
    @classmethod
    def from_text(cls, text: str) -> Document: ...

class PromptTemplate:
    def __init__(self, template_str: str): ...
    
    def placeholder(self, prompt_item: Union[Image, Tokens]) -> Placeholder: ...
    
    def to_prompt(self, **kwargs) -> Prompt: ...

Document & Prompt Templates

Utility Functions

Helper functions for loading and encoding media files from various sources for use in multimodal prompts.

def load_base64_from_file(path_and_filename: str) -> str: ...

def load_base64_from_url(url: str) -> str: ...

Utility Functions

Types

# Core enums
class Role(str, Enum):
    User = "user"
    Assistant = "assistant"
    System = "system"

class SemanticRepresentation(Enum):
    Symmetric = "symmetric"
    Document = "document"
    Query = "query"

class ControlTokenOverlap(Enum):
    Partial = "partial"
    Complete = "complete"

class FinishReason(str, Enum):
    Stop = "stop"
    Length = "length"
    ContentFilter = "content_filter"

# Structured output types
ResponseFormat = Union[JSONSchema, Type[BaseModel]]

# Steering types
class SteeringPairedExample:
    negative: str
    positive: str

class SteeringConceptCreationResponse:
    id: str

# Translation types
class TranslationSegment:
    source: str
    translation: str
    score: float

# Template types
Placeholder = NewType("Placeholder", UUID)

# Exception classes
class QuotaError(Exception): ...
class BusyError(Exception): ...

# Constants
POOLING_OPTIONS: List[str] = ["mean", "max", "last_token", "abs_max"]