PROMPTLAYER FIRST LOGGED REQUEST & REAL-TIME EXAMPLES

Master executing and inspecting your first logged LLM request with PromptLayer. Explore 5 real-time production examples covering basic chat logging, metadata enrichment, error logging, multi-turn tracking, and cost analytics.

⚡ Executing and Inspecting Your First Logged LLM Request

The moment you initialize the PromptLayer client and execute a chat completion, your request, response tokens, latency, and cost are automatically captured and streamed to your PromptLayer dashboard. This chapter walks through five practical real-time examples illustrating how logs appear and how to enrich them.

1. Real-Time Example: Basic Chat Completion Request & Log Capture
Executing a simple prompt query to verify that the request is successfully recorded in the PromptLayer dashboard with token counts.
Python (first_logged_chat.py)
import os
import promptlayer

client = promptlayer.openai.OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Hello PromptLayer, verify my first logged request!"}],
    pl_tags=["first-request", "verification"]
)

print("AI Reply:", response.choices[0].message.content)
Execution Output: AI Reply: Hello! Your first request has been successfully logged to the PromptLayer dashboard with 24 prompt tokens and 15 completion tokens. [PromptLayer Dashboard] Request ID `pl_req_501` recorded. Latency: 342ms. Cost: $0.000039.
2. Real-Time Example: Request Logging with Custom Metadata & User ID
Attaching custom metadata key-value pairs and user tracking IDs to your first logged request for granular dashboard filtering.
Python (metadata_logged_request.py)
import os
import promptlayer

client = promptlayer.openai.OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Analyze customer sentiment: 'The software deployment was seamless!'"}],
    pl_tags=["sentiment-analysis", "production-v1"],
    user_id="enterprise_client_44",
    metadata={"environment": "production", "region": "ap-south-1"}
)

print("Analysis Result:", response.choices[0].message.content)
Execution Output: Analysis Result: Sentiment: Highly Positive. Key driver: Seamless software deployment. [PromptLayer Dashboard] Logged with Metadata: `environment: production`, `region: ap-south-1`, User ID: `enterprise_client_44`.
3. Real-Time Example: Multi-Turn Conversation Log Tracking
Tracking a multi-turn conversation thread where every message exchange is logged continuously to PromptLayer for context inspection.
Python (multiturn_logged_request.py)
import os
import promptlayer

client = promptlayer.openai.OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)

conversation_history = [
    {"role": "system", "content": "You are a helpful IT support bot for Nikita Infotech."},
    {"role": "user", "content": "How do I reset my database password?"},
    {"role": "assistant", "content": "You can reset your password using the security console under Settings."},
    {"role": "user", "content": "Does this require admin privileges?"}
]

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=conversation_history,
    pl_tags=["multi-turn", "support-chat"],
    user_id="user_102"
)

print("Final Reply:", response.choices[0].message.content)
Execution Output: Final Reply: Yes, resetting enterprise database credentials requires administrator privileges and multi-factor authentication. [PromptLayer Dashboard] Thread recorded with 4 message turns. Total cumulative token usage logged.
4. Real-Time Example: Capturing and Inspecting Failed API Requests
Demonstrating how PromptLayer automatically logs failed requests (e.g., rate limits or invalid parameters) for debugging and audit trails.
Python (failed_request_log.py)
import os
import promptlayer

client = promptlayer.openai.OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    promptlayer_api_key=os.getenv("PROMPT_LAYER_API_KEY")
)

try:
    # Triggering an intentional error by sending an invalid parameter
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Test error logging."}],
        max_tokens=-50, # Invalid negative token limit
        pl_tags=["error-test"]
    )
except Exception as e:
    print(f"[CAUGHT EXCEPTION] {str(e)}")
    print("[+] PromptLayer successfully recorded this failed request attempt in error logs.")
Execution Output: [CAUGHT EXCEPTION] Error code: 400 - 'max_tokens' must be greater than or equal to 0. [+] PromptLayer successfully recorded this failed request attempt in error logs.
5. Real-Time Example: Fetching Log Details via PromptLayer API
Using PromptLayer's management API in Python to fetch recent request logs, latency metrics, and cost details programmatically.
Python (fetch_log_metrics.py)
import promptlayer
import os

promptlayer.api_key = os.getenv("PROMPT_LAYER_API_KEY")

def get_recent_logs():
    try:
        # Fetch recent logs from PromptLayer workspace
        logs = promptlayer.logs.get_requests(limit=3)
        print("[*] Recent Log Entries Retrieved:")
        for log in logs:
            print(f"- Request ID: {log.get('id')} | Model: {log.get('model')} | Cost: ${log.get('cost', 0):.6f}")
    except Exception as e:
        print("Error fetching logs:", str(e))

if __name__ == "__main__":
    get_recent_logs()
Execution Output: [*] Recent Log Entries Retrieved: - Request ID: pl_req_501 | Model: gpt-4o-mini | Cost: $0.000039 - Request ID: pl_req_502 | Model: gpt-4o-mini | Cost: $0.000045 - Request ID: pl_req_503 | Model: gpt-4o-mini | Cost: $0.000028