Python client to interact with Aleph Alpha API endpoints
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Helper functions for loading and encoding media files from various sources. Provides convenient methods for preparing images and other binary data for use in multimodal prompts.
Load binary files and encode them as base64 strings for API consumption.
def load_base64_from_file(path_and_filename: str) -> str:
"""
Load a file from disk and return the base64 encoded content.
Parameters:
- path_and_filename: Path to the file to load
Returns:
Base64 encoded string representation of the file contents
Example:
>>> encoded = load_base64_from_file("./images/photo.jpg")
>>> image = Image(base_64=encoded)
"""
def load_base64_from_url(url: str) -> str:
"""
Download a file from URL and return the base64 encoded content.
Parameters:
- url: URL of the file to download
Returns:
Base64 encoded string representation of the downloaded file
Example:
>>> encoded = load_base64_from_url("https://example.com/image.png")
>>> image = Image(base_64=encoded)
"""Loading images and files for multimodal prompts:
from aleph_alpha_client import (
load_base64_from_file,
load_base64_from_url,
Image,
Prompt,
Text,
Client,
CompletionRequest
)
client = Client(token="your-api-token")
# Load image from local file
local_image_data = load_base64_from_file("./photos/vacation.jpg")
local_image = Image(base_64=local_image_data)
# Create multimodal prompt with local image
prompt = Prompt([
Text.from_text("Describe what you see in this vacation photo:"),
local_image
])
request = CompletionRequest(
prompt=prompt,
maximum_tokens=150,
temperature=0.5
)
response = client.complete(request, model="luminous-extended")
print("Local image description:")
print(response.completions[0].completion)
# Load image from URL
web_image_data = load_base64_from_url("https://example.com/chart.png")
web_image = Image(base_64=web_image_data)
# Analyze web image
web_prompt = Prompt([
Text.from_text("Analyze this chart and extract the key insights:"),
web_image
])
web_request = CompletionRequest(
prompt=web_prompt,
maximum_tokens=200,
temperature=0.3
)
web_response = client.complete(web_request, model="luminous-extended")
print("Chart analysis:")
print(web_response.completions[0].completion)
# Load multiple images for comparison
image1_data = load_base64_from_file("./images/before.jpg")
image2_data = load_base64_from_file("./images/after.jpg")
comparison_prompt = Prompt([
Text.from_text("Compare these two images and describe the differences:"),
Text.from_text("\nImage 1 (Before):"),
Image(base_64=image1_data),
Text.from_text("\nImage 2 (After):"),
Image(base_64=image2_data)
])
comparison_request = CompletionRequest(
prompt=comparison_prompt,
maximum_tokens=250,
temperature=0.4
)
comparison_response = client.complete(comparison_request, model="luminous-extended")
print("Image comparison:")
print(comparison_response.completions[0].completion)
# Load document or PDF for analysis
# Note: This works for any binary file that can be base64 encoded
document_data = load_base64_from_file("./documents/report.pdf")
# Error handling for file operations
import os
def safe_load_image(path: str) -> Image:
"""Safely load an image with error handling."""
try:
if not os.path.exists(path):
raise FileNotFoundError(f"Image file not found: {path}")
image_data = load_base64_from_file(path)
return Image(base_64=image_data)
except Exception as e:
print(f"Error loading image {path}: {e}")
return None
# Use with error handling
image_paths = ["./images/img1.jpg", "./images/img2.png", "./images/missing.jpg"]
for path in image_paths:
image = safe_load_image(path)
if image:
prompt = Prompt([
Text.from_text(f"Describe the image from {path}:"),
image
])
request = CompletionRequest(
prompt=prompt,
maximum_tokens=100,
temperature=0.5
)
try:
response = client.complete(request, model="luminous-extended")
print(f"\nDescription of {path}:")
print(response.completions[0].completion)
except Exception as e:
print(f"Error processing {path}: {e}")
# Batch loading for efficiency
def load_images_batch(image_paths: list) -> list:
"""Load multiple images efficiently."""
images = []
for path in image_paths:
try:
if path.startswith('http'):
data = load_base64_from_url(path)
else:
data = load_base64_from_file(path)
images.append(Image(base_64=data))
except Exception as e:
print(f"Failed to load {path}: {e}")
images.append(None)
return images
# Example batch usage
mixed_sources = [
"./local/image1.jpg",
"https://example.com/image2.png",
"./local/image3.jpg"
]
loaded_images = load_images_batch(mixed_sources)
valid_images = [img for img in loaded_images if img is not None]
print(f"Successfully loaded {len(valid_images)} out of {len(mixed_sources)} images")Install with Tessl CLI
npx tessl i tessl/pypi-aleph-alpha-client