> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baytos.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Listing and Pagination

> Browse and paginate through your prompts

# Listing and Pagination

Learn how to list prompts in your workspace and paginate through large result sets.

## Listing Prompts

Use the `list_prompts()` method to browse prompts:

```python theme={null}
from baytos.claro import BaytClient

client = BaytClient(api_key="your_api_key")

# Get first page of prompts
result = client.list_prompts(limit=20)

# Access prompts
for prompt in result['prompts']:
    print(f"{prompt.title} - {prompt.package_name}")
```

## Response Format

The `list_prompts()` method returns a dictionary:

```python theme={null}
{
    'prompts': [Prompt, Prompt, ...],  # List of Prompt objects
    'cursor': 'abc123...',              # Cursor for next page
    'hasMore': True                     # True if more pages available
}
```

### Accessing Results

```python theme={null}
result = client.list_prompts(limit=10)

# Get prompts
prompts = result['prompts']
print(f"Retrieved {len(prompts)} prompts")

# Check pagination
if result['hasMore']:
    print("More pages available")
    next_cursor = result['cursor']

# Access prompt details
for prompt in prompts:
    print(f"Title: {prompt.title}")
    print(f"Package: {prompt.package_name}")
    print(f"Version: {prompt.version}")
    print()
```

## Pagination

### Basic Pagination

Use the `cursor` parameter to fetch subsequent pages:

```python theme={null}
client = BaytClient(api_key="your_api_key")

# First page
page1 = client.list_prompts(limit=20)

# Second page
if page1['hasMore']:
    page2 = client.list_prompts(limit=20, cursor=page1['cursor'])

# Third page
if page2['hasMore']:
    page3 = client.list_prompts(limit=20, cursor=page2['cursor'])
```

### Iterating Through All Pages

```python theme={null}
def get_all_prompts(client):
    """Get all prompts across all pages"""
    all_prompts = []
    cursor = None

    while True:
        # Fetch page
        result = client.list_prompts(limit=100, cursor=cursor)

        # Add prompts to list
        all_prompts.extend(result['prompts'])

        # Check if more pages exist
        if not result['hasMore']:
            break

        # Get cursor for next page
        cursor = result['cursor']

    return all_prompts

# Usage
client = BaytClient(api_key="...")
prompts = get_all_prompts(client)
print(f"Total prompts: {len(prompts)}")
```

### Pagination with Limit

Control how many results to fetch:

```python theme={null}
def get_prompts_with_limit(client, max_count=1000):
    """Get prompts up to a maximum count"""
    prompts = []
    cursor = None

    while len(prompts) < max_count:
        # Calculate how many to fetch
        remaining = max_count - len(prompts)
        limit = min(remaining, 100)

        # Fetch page
        result = client.list_prompts(limit=limit, cursor=cursor)

        # Add prompts
        prompts.extend(result['prompts'])

        # Check if done
        if not result['hasMore']:
            break

        cursor = result['cursor']

    return prompts[:max_count]

# Usage
prompts = get_prompts_with_limit(client, max_count=500)
```

## Limit Parameter

Control page size with the `limit` parameter:

```python theme={null}
# Small pages (faster response, more requests)
result = client.list_prompts(limit=10)

# Medium pages (balanced)
result = client.list_prompts(limit=50)

# Large pages (fewer requests, slower response)
result = client.list_prompts(limit=100)
```

<Note>
  The `limit` parameter must be between 1 and 100. Default is 20.
</Note>

### Validation

```python theme={null}
from baytos.claro import BaytValidationError

try:
    # Too small
    result = client.list_prompts(limit=0)
except BaytValidationError:
    print("Limit must be at least 1")

try:
    # Too large
    result = client.list_prompts(limit=200)
except BaytValidationError:
    print("Limit cannot exceed 100")
```

## Complete Examples

### Example 1: Display All Prompts

```python theme={null}
#!/usr/bin/env python3
"""
List all prompts in your workspace
"""

import os
from baytos.claro import BaytClient

def list_all_prompts():
    client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))

    print("Your Prompts:")
    print("=" * 70)

    cursor = None
    total = 0

    while True:
        # Fetch page
        result = client.list_prompts(limit=50, cursor=cursor)

        # Display prompts
        for prompt in result['prompts']:
            total += 1
            print(f"{total}. {prompt.title}")
            print(f"   Package: {prompt.package_name}")

            if prompt.description:
                print(f"   Description: {prompt.description}")

            # Show if has context
            if prompt.has_context():
                file_count = len(prompt.get_file_contexts())
                url_count = len(prompt.get_url_contexts())
                print(f"   Context: {file_count} files, {url_count} URLs")

            print()

        # Check for more pages
        if not result['hasMore']:
            break

        cursor = result['cursor']

    print(f"\nTotal: {total} prompt(s)")

if __name__ == "__main__":
    list_all_prompts()
```

### Example 2: Search and Filter

```python theme={null}
#!/usr/bin/env python3
"""
Search for prompts by title
"""

import os
from baytos.claro import BaytClient

def search_prompts(search_term: str):
    """Find prompts matching search term"""
    client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))

    matching = []
    cursor = None

    print(f"Searching for: '{search_term}'\n")

    while True:
        result = client.list_prompts(limit=100, cursor=cursor)

        # Filter by title
        for prompt in result['prompts']:
            if search_term.lower() in prompt.title.lower():
                matching.append(prompt)

        if not result['hasMore']:
            break

        cursor = result['cursor']

    # Display results
    print(f"Found {len(matching)} matching prompt(s):\n")
    for i, prompt in enumerate(matching, 1):
        print(f"{i}. {prompt.title}")
        print(f"   {prompt.package_name}")
        print()

    return matching

if __name__ == "__main__":
    import sys

    search_term = sys.argv[1] if len(sys.argv) > 1 else "support"
    search_prompts(search_term)
```

### Example 3: Export to CSV

```python theme={null}
#!/usr/bin/env python3
"""
Export all prompts to CSV
"""

import os
import csv
from baytos.claro import BaytClient

def export_prompts_to_csv(filename: str = "prompts.csv"):
    """Export all prompts to a CSV file"""
    client = BaytClient(api_key=os.getenv("BAYT_API_KEY"))

    with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)

        # Header
        writer.writerow([
            'Title',
            'Package Name',
            'Version',
            'Description',
            'Has Context',
            'File Count',
            'URL Count'
        ])

        # Fetch all prompts
        cursor = None
        total = 0

        while True:
            result = client.list_prompts(limit=100, cursor=cursor)

            for prompt in result['prompts']:
                total += 1

                writer.writerow([
                    prompt.title,
                    prompt.package_name,
                    prompt.version,
                    prompt.description or '',
                    'Yes' if prompt.has_context() else 'No',
                    len(prompt.get_file_contexts()),
                    len(prompt.get_url_contexts())
                ])

            if not result['hasMore']:
                break

            cursor = result['cursor']

    print(f"Exported {total} prompts to {filename}")

if __name__ == "__main__":
    export_prompts_to_csv()
```

## Generator Pattern

Use a generator for memory-efficient iteration:

```python theme={null}
def iter_prompts(client, limit=100):
    """Generator that yields prompts one at a time"""
    cursor = None

    while True:
        result = client.list_prompts(limit=limit, cursor=cursor)

        # Yield each prompt
        for prompt in result['prompts']:
            yield prompt

        # Check if done
        if not result['hasMore']:
            break

        cursor = result['cursor']

# Usage - memory efficient for large result sets
client = BaytClient(api_key="...")

for prompt in iter_prompts(client):
    print(f"Processing: {prompt.title}")
    # Process one at a time without loading all into memory
```

## Best Practices

<AccordionGroup>
  <Accordion title="Choose Appropriate Page Sizes" icon="sliders">
    Balance between request count and response time:

    ```python theme={null}
    # ✅ Good: Reasonable page size
    result = client.list_prompts(limit=50)

    # ❌ Too small: Many requests
    result = client.list_prompts(limit=5)

    # ❌ Too large: May be slower
    result = client.list_prompts(limit=100)  # Only if needed
    ```

    Use larger pages for batch processing, smaller pages for interactive displays.
  </Accordion>

  <Accordion title="Handle Empty Results" icon="empty-set">
    Always check if results are empty:

    ```python theme={null}
    result = client.list_prompts(limit=20)

    if not result['prompts']:
        print("No prompts found")
    else:
        for prompt in result['prompts']:
            print(prompt.title)
    ```
  </Accordion>

  <Accordion title="Implement Progress Tracking" icon="spinner">
    Show progress when fetching many pages:

    ```python theme={null}
    def get_all_prompts_with_progress(client):
        all_prompts = []
        cursor = None
        page = 0

        while True:
            page += 1
            print(f"Fetching page {page}...", end='\r')

            result = client.list_prompts(limit=100, cursor=cursor)
            all_prompts.extend(result['prompts'])

            if not result['hasMore']:
                break

            cursor = result['cursor']

        print(f"\nFetched {len(all_prompts)} prompts across {page} pages")
        return all_prompts
    ```
  </Accordion>

  <Accordion title="Cache Results When Appropriate" icon="database">
    Cache results for repeated access:

    ```python theme={null}
    from functools import lru_cache
    from datetime import datetime, timedelta

    class PromptCache:
        def __init__(self, client, ttl_seconds=300):
            self.client = client
            self.cache = None
            self.cache_time = None
            self.ttl = timedelta(seconds=ttl_seconds)

        def get_prompts(self):
            now = datetime.now()

            # Check if cache is valid
            if (self.cache is None or
                self.cache_time is None or
                now - self.cache_time > self.ttl):

                # Refresh cache
                self.cache = get_all_prompts(self.client)
                self.cache_time = now

            return self.cache

    # Usage
    cache = PromptCache(client, ttl_seconds=300)
    prompts = cache.get_prompts()  # First call - fetches from API
    prompts = cache.get_prompts()  # Second call - returns cached
    ```
  </Accordion>
</AccordionGroup>

## Error Handling

Handle errors when listing prompts:

```python theme={null}
from baytos.claro import BaytClient, BaytAuthError, BaytAPIError

client = BaytClient(api_key="...")

try:
    result = client.list_prompts(limit=20)

    for prompt in result['prompts']:
        print(prompt.title)

except BaytAuthError:
    print("Authentication failed - check your API key")
except BaytAPIError as e:
    print(f"API error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Working with Prompts" icon="sparkles" href="/sdk/python/prompts">
    Learn about prompt content and metadata
  </Card>

  <Card title="Error Handling" icon="shield" href="/sdk/python/error-handling">
    Handle errors gracefully
  </Card>

  <Card title="Advanced Features" icon="rocket" href="/sdk/python/advanced">
    Performance optimization techniques
  </Card>

  <Card title="API Reference" icon="book" href="/sdk/python/api-reference">
    Complete API documentation
  </Card>
</CardGroup>
