PromptLayer Python Library

repository·master·Indexed 20 days ago

https://github.com/magnivorg/prompt-layer-library

A Python library for prompt engineering, versioning, testing, and monitoring LLM prompts and agents. It provides tools for tracing via OpenTelemetry, regression testing, and managing prompt templates. Features include an OpenAI proxy for automatic request logging, asynchronous support via AsyncPromptLayer, in-memory template caching, and a comprehensive evaluation framework with built-in scorers and a CLI for running .eval.py files.

Tokens
10.8K
Snippets
41
Records
47
Agent score
72%

What's inside promptlayer

  1. Enable Prompt Template Caching

    master

    The SDK can cache fetched prompt templates in memory to speed up repeat reads and provide fallback during API failures.

    • Enablement: Set cache_ttl_seconds > 0 when creating the client.
    • Scope: Applies to templates fetched via client.templates.get(...).
    • Bypassing: Requests with metadata_filters or model_parameter_overrides bypass the cache.
    • Limitations: Templates requiring server-side rendering (e.g., placeholder messages or tool-variable expansion) are not cached for local rendering.
    • Invalidation: Use client.invalidate(...) or client.templates.invalidate(...) to clear entries.
    # Example of enabling caching
    pl = PromptLayer(api_key="pl_xxxxx", cache_ttl_seconds=3600)
  2. Auto-instrument the OpenAI SDK

    master

    To trace direct OpenAI SDK calls using OpenTelemetry, install the instrumentation extra:

    pip install "promptlayer[otel-genai-instrumentation]" openai

    Option 1: Using a PromptLayer client

    Enable tracing on the client, and then use the standard OpenAI client. This uses the PromptLayer-managed tracer provider.

    from openai import OpenAI
    from promptlayer import PromptLayer
    
    promptlayer_client = PromptLayer(api_key="pl_xxxxx", enable_tracing=True)
    openai_client = OpenAI()
    
    response = openai_client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": "Hello."}],
    )

    Option 2: Using instrument_openai()

    If you don't want to create a PromptLayer client, you can use instrument_openai(). This reads the API key and endpoint from the environment.

    from openai import OpenAI
    from promptlayer import instrument_openai
    
    tracer_provider = instrument_openai()
    openai_client = OpenAI()
  3. Quick Start: Fetch a prompt template

    master

    To fetch a prompt template from PromptLayer, create a PromptLayer client and use the templates.get method. You must provide an api_key or set the PROMPTLAYER_API_KEY environment variable.

    from promptlayer import PromptLayer
    
    pl = PromptLayer(api_key="pl_xxxxx")
    
    prompt = pl.templates.get(
        "support-reply",
        {
            "input_variables": {
                "customer_name": "Ada",
                "question": "How do I reset my password?",
            }
        },
    )
    
    print(prompt["prompt_template"])
  4. Quick Start: Use AsyncPromptLayer

    master

    For asynchronous workflows, use AsyncPromptLayer. Every method in the client has an async version.

    import asyncio
    from promptlayer import AsyncPromptLayer
    
    async def main():
        pl = AsyncPromptLayer(api_key="pl_xxxxx")
    
        prompt = await pl.templates.get(
            "support-reply",
            {
                "input_variables": {
                    "customer_name": "Ada",
                    "question": "How do I reset my password?",
                }
            },
        )
    
        print(prompt["prompt_template"])
    
    asyncio.run(main())
  5. Configure PromptLayer Client Options

    master

    When initializing PromptLayer(...) or AsyncPromptLayer(...), you can pass the following parameters:

    • api_key: str | None = None: Your PromptLayer API key. If omitted, the SDK looks for PROMPTLAYER_API_KEY.
    • enable_tracing: bool = False: Enables OpenTelemetry tracing export to PromptLayer and auto-instruments the OpenAI SDK when the tracing extra is installed.
    • base_url: str | None = None: Overrides the PromptLayer API base URL. If omitted, the SDK uses PROMPTLAYER_BASE_URL or the default API URL.
    • throw_on_error: bool = True: Controls whether SDK methods raise PromptLayer exceptions or return None for many API errors.
    • cache_ttl_seconds: int = 0: Enables in-memory prompt-template caching when greater than 0.
    • tracer_provider: TracerProvider | None = None: Uses an application-owned OpenTelemetry SDK tracer provider instead of the default PromptLayer-managed provider.
  6. Initialize the PromptLayer client

    master

    To use PromptLayer, instantiate the PromptLayer class (for synchronous operations) or AsyncPromptLayer (for asynchronous operations). You must provide an api_key, which can also be set via the PROMPTLAYER_API_KEY environment variable.

    Parameters:

    • api_key (str): Your PromptLayer API key.
    • enable_tracing (bool): Whether to enable OpenTelemetry tracing. Defaults to False.
    • base_url (str): The API base URL. Defaults to https://api.promptlayer.com or the PROMPTLAYER_BASE_URL environment variable.
    • throw_on_error (bool): If True, the client will raise exceptions on API errors. Defaults to True.
    • cache_ttl_seconds (int): Time-to-live for the template cache in seconds. Defaults to 0 (no cache).
    • tracer_provider: An optional OpenTelemetry tracer provider.
    from promptlayer import PromptLayer
    
    # Using environment variable PROMPTLAYER_API_KEY
    pl = PromptLayer(enable_tracing=True)
    
    # Explicitly passing API key
    pl = PromptLayer(api_key="your_api_key_here", cache_ttl_seconds=3600)
  7. Handle PromptLayer Errors

    master

    The SDK raises PromptLayerError for failures. You can control whether these are raised or return None by setting throw_on_error=False during client initialization.

    Common error subclasses:

    • PromptLayerValidationError: Invalid input passed to the SDK.
    • PromptLayerAPIConnectionError: Could not connect to PromptLayer.
    • PromptLayerAPITimeoutError: Request or workflow run timed out.
    • PromptLayerAuthenticationError: Missing or invalid API key.
    • PromptLayerPermissionDeniedError: API key lacks permission.
    • PromptLayerNotFoundError: Resource (prompt, workflow, etc.) not found.
    • PromptLayerBadRequestError: Malformed request or invalid parameters.
    • PromptLayerConflictError: Request conflicts with current resource state.
    • PromptLayerUnprocessableEntityError: Well-formed but semantically invalid.
    • PromptLayerRateLimitError: Rate limiting applied.
    • PromptLayerInternalServerError: 5xx server error.
    • PromptLayerAPIStatusError: Other non-success API responses.
  8. Use PromptLayer as an OpenAI proxy

    master

    You can use the PromptLayer client as a proxy around supported provider SDKs (like OpenAI) to automatically log requests.

    from promptlayer import PromptLayer
    
    pl = PromptLayer(api_key="pl_xxxxx")
    openai = pl.openai
    
    response = openai.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": "Say hello in one short sentence."}],
        pl_tags=["proxy-example"],
    )
  9. Configure and use Table Scorecards

    master

    Scorecards are the preferred API for table scoring workflows. Use client.tables.sheets.scorecards to manage them.

    Configure a scorecard

    await client.tables.sheets.scorecards.configure(
        table_id,
        sheet_id,
        {
            "name": "Quality Scorecard",
            "evaluated_column_ids": [],
            "aggregation": {
                "method": "weighted_mean",
                "required_step_failure_behavior": "fail",
                "pass_threshold": 0.8,
                "warn_threshold": 0.6,
            },
            "steps": [],
        },
    )

    Migrate legacy scores

    await client.tables.sheets.scorecards.migrate_legacy_score(
        table_id,
        sheet_id,
        {"delete_legacy_score": False},
    )

    Recalculate and fetch results

    run = await client.tables.sheets.scorecards.recalculate(table_id, sheet_id)
    
    result = await client.tables.sheets.scorecards.get_calculation(
        table_id,
        sheet_id,
        run["calculation_id"],
    )

    Fetch row breakdowns

    rows = await client.tables.sheets.scorecards.list_rows(
        table_id,
        sheet_id,
        {
            "calculation_id": run["calculation_id"],
            "verdict": "fail",
        },
    )
    
    row = await client.tables.sheets.scorecards.get_row(
        table_id,
        sheet_id,
        0,
        {"calculation_id": run["calculation_id"]},
    )
  10. Configure PromptLayer tracing via environment variables

    master

    You can configure PromptLayer tracing without passing arguments to the functions by using the following environment variables:

    VariableDescription
    PROMPTLAYER_API_KEYYour PromptLayer API key. Required if api_key is not passed to functions.
    PROMPTLAYER_BASE_URLThe base URL for PromptLayer. Defaults to https://api.promptlayer.com.
    PROMPTLAYER_OTLP_TRACES_ENDPOINTThe specific OTLP endpoint for traces.
    OTEL_SEMCONV_STABILITY_OPT_INUsed to enable latest GenAI semantic conventions. PromptLayer automatically adds gen_ai_latest_experimental to this list if it's not present.
  11. Configure PromptLayer via Environment Variables

    master

    The SDK uses the following environment variables for configuration:

    VariableRequiredDescription
    PROMPTLAYER_API_KEYYes, unless passed as api_key=API key used to authenticate requests to PromptLayer
    PROMPTLAYER_BASE_URLNoOverrides the PromptLayer API base URL. Defaults to https://api.promptlayer.com
    PROMPTLAYER_OTLP_TRACES_ENDPOINTNoOverrides the OTLP trace endpoint (/v1/traces) used when SDK tracing is enabled
    PROMPTLAYER_TRACEPARENTNoOptional trace context passed through the Claude Agents integration
    | Variable | Required | Description |
    | --- | --- | --- |
    | `PROMPTLAYER_API_KEY` | Yes, unless passed as `api_key=` | API key used to authenticate requests to PromptLayer |
    | `PROMPTLAYER_BASE_URL` | No | Overrides the PromptLayer API base URL. Defaults to `https://api.promptlayer.com` |
    | `PROMPTLAYER_OTLP_TRACES_ENDPOINT` | No | Overrides the OTLP trace endpoint (`/v1/traces`) used when SDK tracing is enabled |
    | `PROMPTLAYER_TRACEPARENT` | No | Optional trace context passed through the Claude Agents integration |