Skip to main content
This guide shows how to download and use files attached to prompts as context. Context files can include documentation, examples, datasets, or any other files that provide additional information to your prompts.

Prerequisites

pip install baytos-claro
export BAYT_API_KEY="your_api_key_here"

Example 1: Check for Attached Files

First, check if a prompt has any files attached:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

# Check if prompt has any context
if prompt.has_context():
    files = prompt.get_file_contexts()
    print(f"This prompt has {len(files)} file(s) attached")

    for file in files:
        print(f"  - {file.file_name} ({file.file_size:,} bytes)")
else:
    print("No files attached to this prompt")
This prompt has 2 file(s) attached
  - example-data.csv (15,243 bytes)
  - documentation.pdf (523,891 bytes)

Example 2: Download a Single File

Download a file and save it to disk:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/prompt-with-files:v1")

# Get list of files
files = prompt.get_file_contexts()

if files:
    file = files[0]  # Get first file
    print(f"Downloading '{file.file_name}'...")

    # Download file content
    content = client.download_context_file(file.id)

    # Save to disk
    with open(file.file_name, 'wb') as f:
        f.write(content)

    print(f"Saved to: {file.file_name}")
    print(f"Size: {len(content):,} bytes")

Example 3: Download All Files

Download all files attached to a prompt:
import os
from pathlib import Path
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

# Create directory for downloads
download_dir = Path("downloads")
download_dir.mkdir(exist_ok=True)

# Get all files
files = prompt.get_file_contexts()

if not files:
    print("No files to download")
    exit(0)

print(f"Downloading {len(files)} file(s)...")

for i, file in enumerate(files, 1):
    print(f"\n{i}. {file.file_name}")

    # Download file content
    content = client.download_context_file(file.id)

    # Save to downloads directory
    file_path = download_dir / file.file_name
    with open(file_path, 'wb') as f:
        f.write(content)

    print(f"   Saved to: {file_path}")
    print(f"   Size: {len(content):,} bytes")

print(f"\nAll files saved to: {download_dir.absolute()}")

Example 4: Download and Process Text Files

Download and read text-based files:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

for file in files:
    # Check if it's a text file
    if file.mime_type.startswith('text/') or file.file_name.endswith('.txt'):
        print(f"\nReading {file.file_name}...")

        # Download and decode as text
        content = client.download_context_file(file.id)
        text = content.decode('utf-8')

        # Display preview
        preview = text[:200] + "..." if len(text) > 200 else text
        print(preview)

Example 5: Download CSV Files

Download and parse CSV files:
import os
import csv
from io import StringIO
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/data-analysis:v1")

files = prompt.get_file_contexts()

for file in files:
    if file.file_name.endswith('.csv'):
        print(f"\nProcessing {file.file_name}...")

        # Download content
        content = client.download_context_file(file.id)
        text = content.decode('utf-8')

        # Parse CSV
        reader = csv.DictReader(StringIO(text))
        rows = list(reader)

        print(f"Rows: {len(rows)}")
        print(f"Columns: {', '.join(reader.fieldnames)}")

        # Display first few rows
        for i, row in enumerate(rows[:3], 1):
            print(f"  Row {i}: {row}")

Example 6: Download JSON Files

Download and parse JSON files:
import os
import json
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

for file in files:
    if file.file_name.endswith('.json'):
        print(f"\nProcessing {file.file_name}...")

        # Download and parse JSON
        content = client.download_context_file(file.id)
        data = json.loads(content.decode('utf-8'))

        print(f"Type: {type(data).__name__}")
        print(f"Preview: {json.dumps(data, indent=2)[:200]}...")

Example 7: Download Images

Download image files:
import os
from pathlib import Path
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

# Create images directory
images_dir = Path("images")
images_dir.mkdir(exist_ok=True)

files = prompt.get_file_contexts()

# Common image MIME types
image_types = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']

for file in files:
    if file.mime_type in image_types:
        print(f"Downloading image: {file.file_name}")

        # Download image
        content = client.download_context_file(file.id)

        # Save image
        image_path = images_dir / file.file_name
        with open(image_path, 'wb') as f:
            f.write(content)

        print(f"Saved to: {image_path}")

Example 8: Get File Information

Examine file metadata before downloading:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

print("File Information:")
print("=" * 80)

for i, file in enumerate(files, 1):
    print(f"\n{i}. {file.file_name}")
    print(f"   ID: {file.id}")
    print(f"   Size: {file.file_size:,} bytes ({file.file_size / 1024:.1f} KB)")
    print(f"   MIME Type: {file.mime_type}")

    if file.label:
        print(f"   Label: {file.label}")

    # Estimate download time (assuming 1 MB/s)
    download_time = file.file_size / (1024 * 1024)
    print(f"   Est. download time: {download_time:.2f}s")

Example 9: Download with Progress

Show download progress for large files:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

for file in files:
    print(f"\nDownloading {file.file_name}...")
    print(f"Size: {file.file_size:,} bytes")

    # Download
    content = client.download_context_file(file.id)

    # Show progress
    downloaded = len(content)
    if downloaded == file.file_size:
        print("✓ Download complete")
    else:
        print(f"⚠ Expected {file.file_size}, got {downloaded} bytes")

    # Save
    with open(file.file_name, 'wb') as f:
        f.write(content)

Example 10: Conditional Downloads

Only download files that meet certain criteria:
import os
from pathlib import Path
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

# Download only small text files (< 1MB)
max_size = 1024 * 1024  # 1 MB
text_types = ['text/plain', 'text/csv', 'application/json']

for file in files:
    # Check conditions
    if file.mime_type in text_types and file.file_size < max_size:
        print(f"Downloading {file.file_name}...")

        content = client.download_context_file(file.id)

        with open(file.file_name, 'wb') as f:
            f.write(content)

        print(f"✓ Saved ({file.file_size:,} bytes)")
    else:
        print(f"⊘ Skipping {file.file_name} (doesn't meet criteria)")

Example 11: Use Signed URLs

Get signed URLs for direct download access:
import os
from baytos.claro import BaytClient

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))
prompt = client.get_prompt("@workspace/my-prompt:v1")

files = prompt.get_file_contexts()

for file in files:
    # Get signed URL (if available in file object)
    if hasattr(file, 'url') and file.url:
        print(f"{file.file_name}:")
        print(f"  Direct URL: {file.url}")
    else:
        print(f"{file.file_name}: Use download_context_file() method")
Signed URLs are temporary and expire after a certain period. Always download files when needed rather than storing URLs.

Example 12: Handle Download Errors

Robust error handling for file downloads:
import os
from baytos.claro import BaytClient, BaytNotFoundError, BaytAPIError

client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))

try:
    prompt = client.get_prompt("@workspace/my-prompt:v1")
    files = prompt.get_file_contexts()

    for file in files:
        try:
            print(f"Downloading {file.file_name}...")
            content = client.download_context_file(file.id)

            with open(file.file_name, 'wb') as f:
                f.write(content)

            print(f"✓ Downloaded successfully")

        except BaytNotFoundError:
            print(f"✗ File not found: {file.file_name}")

        except BaytAPIError as e:
            print(f"✗ Download failed: {e}")

        except IOError as e:
            print(f"✗ Could not save file: {e}")

except Exception as e:
    print(f"Error: {e}")

Next Steps