Perplexity API Cookbook

repository·main·Indexed 42 days ago

https://github.com/perplexityai/api-cookbook

A collection of practical examples, integration guides, and community showcases for building hosted agents using the Perplexity Agent API. Includes guides on integrating the Sonar API with the OpenAI Agents SDK, implementing token-aware memory with LlamaIndex's ChatSummaryMemoryBuffer, and creating persistent chat memory using LanceDB.

Tokens
33K
Snippets
116
Records
159
Agent score
51%

What's inside Perplexity API Cookbook

  1. Explore Perplexity API Cookbook contents

    main

    The cookbook is organized into three main sections to help you build with the Perplexity API Platform:

    • Examples: Ready-to-run projects demonstrating specific use cases and implementation patterns.
    • Showcase: Real-world applications built by the community using the API Platform.
    • Integration Guides: In-depth tutorials for advanced implementations, such as memory management and integration with other tools.

    Note: The documentation provides guides and explanations, while the GitHub repository contains the complete code, scripts, and project files required to run the implementations.

  2. Explore Perplexity Sonar API Examples

    main

    This collection contains production-ready applications demonstrating various use cases for the Perplexity Sonar API.

    Common Requirements for all examples:

    • Python 3.7+
    • Perplexity API Key
    • Internet connection

    Note: Specific dependencies for each example are listed in their respective requirements.txt files.

  3. Greenify Architecture and AI Integration Overview

    main

    Greenify uses a split architecture to provide AI-powered plant recommendations:

    • Frontend: A React Native application built with Expo for cross-platform (iOS, Android, Web) support.
    • Backend: A Python Flask API that manages image processing and coordinates with the Perplexity API.
    • AI Layer:
      • Perplexity Sonar Pro: Used for initial image analysis.
      • Perplexity Sonar Deep Research: Used to generate detailed plant recommendations.
    • Data Handling: Uses Pydantic models to ensure structured JSON output and consistent data validation between the AI responses and the application.
  4. Understand Finance Chart (Sandbox) pricing and limitations

    main

    The Finance Chart (Sandbox) example uses the Perplexity sandbox tool to fetch and render financial data.

    Pricing Model

    • sandbox: $0.03 per container session.
    • Model tokens: Billed separately according to standard Agent API token pricing.
    • Usage Tracking: Sandbox invocations are tracked via usage.tool_calls_details.sandbox.invocation. File sharing is tracked via usage.tool_calls_details.share_file.invocation.

    Limitations and Risks

    • Preview Status: The sandbox tool is currently in preview and must be executed as a background task.
    • Data Accuracy: Financial data is fetched from third-party sources (Yahoo v8 chart JSON or Stooq fallback) inside the sandbox. Accuracy depends on these external providers.
    • Ticker Formatting: For non-US tickers, Stooq may require a .us suffix.
    • Best-Effort Fetching: Rate limits on data sources may cause fetching to fail. While the script includes retry logic, a run may still fail.
    • Billing Note: Each retry attempt counts as a separate billed sandbox session.
  5. Prompting guidance for finance_search

    main

    When using the finance_search tool, focus your prompts on business outcomes rather than requesting specific data shapes.

    To ensure high-quality, quantitative reports, your system prompt should instruct the model to:

    • Be quantitative and attribute numbers to the correct periods (e.g., FY2025, Q3 FY26).
    • Never invent numbers; if finance_search does not return a specific field, the model should explicitly state that the data is unavailable.
    • Format the final output in clean Markdown.
  6. How PerplexiGrid uses Perplexity Sonar API modes

    main

    PerplexiGrid utilizes the Perplexity Sonar API through four distinct prompt modes to handle different dashboard lifecycle stages. The system relies on structured JSON schema responses from Sonar to generate ECharts-compatible configurations for interactive visualizations.

    • Full Dashboard Generation (f1): Used when a user starts with an empty canvas. It produces a complete dashboard layout containing multiple widgets.
    • Lightweight Mode (l1): Designed for quick insights or previews. It is faster and more cost-effective but returns fewer widgets and less instruction depth.
    • Full Dashboard Regeneration (r1): Used when a user wants to replace all existing widgets with a new prompt while keeping the overall layout intact.
    • Targeted Widget Update (r2): Used for precise control over a single component (e.g., changing a bar chart to a pie chart) without affecting the rest of the dashboard.
    | Mode | Description | Use Case | Notes |
    |------|-------------|----------|-------|
    | `f1` | First-time full dashboard generation | User starts with an empty canvas and enters an initial prompt | Produces a complete dashboard layout with multiple widgets |
    | `l1` | Lightweight dashboard generation | Used for quick insights or previews with minimal tokens | Faster and cheaper, but returns fewer widgets with less instruction depth |
    | `r1` | Full dashboard regeneration | User wants to replace all existing widgets with a new prompt | Rebuilds the entire dashboard while keeping layout intact |
    | `r2` | Targeted widget update | User wants to change a specific widget (e.g. "make this a pie chart") | Only the selected widget is modified based on the new instruction |
  7. How the sandbox tool works with background tasks

    main

    When using the sandbox tool, you must use a background task. Synchronous or streaming requests will be rejected with streaming failed: ... unknown tool "sandbox".

    Workflow:

    1. Submit a request with background: true.
    2. Poll the response by its id until the status is no longer queued or in_progress.
    3. Retrieve files from the share_file output items in the response. Each item contains a file_id, filename, and a URL in the format /v1/responses/{id}/files/{file_id}/content.
    # 1. Submit background request
    payload = {
        "model": "openai/gpt-5.5",
        "instructions": "...",
        "input": "...",
        "tools": [{"type": "sandbox"}],
        "background": True,  # REQUIRED for sandbox
        "max_output_tokens": 8192,
        "max_steps": 15,
    }
    
    # 2. Poll the response
    while body["status"] in ("queued", "in_progress"):
        time.sleep(3)
        body = get(f"/v1/responses/{body['id']}")
    
    # 3. Download files from share_file items
    for item in body["output"]:
        if item["type"] == "share_file":
            url = item["url"]
            data = get_raw(url)
  8. How Valetudo AI uses the Perplexity Sonar API

    main

    Valetudo AI is a medical assistant showcase that demonstrates how to use specific Perplexity Sonar API fields to constrain and enhance domain-specific search results. It utilizes the following API configurations to ensure medical accuracy and relevance:

    • Context Control: Uses search_context_size: medium to balance response speed with the depth required for medical Q&A.
    • Domain Filtering: Uses search_domain_filter to restrict search results to a curated list of trusted medical domains.
    • Visual Analysis: Uses image_url to enable queries based on photos of medication, packaging, or medical conditions.
    • Temporal Filtering: Uses search_after/before_date_filter to ensure findings are recent and relevant.
    • Localization: Uses user_location to tailor medical insights to the user's specific region.
  9. How StarPlex uses the Perplexity Sonar API

    main

    StarPlex implements a multi-module intelligence architecture using Perplexity's Sonar API to power various startup research features:

    • Market Analysis Engine: Uses Sonar Pro to combine Google Trends data with AI analysis. It generates market cap estimates, AI-disruption scores, and growth projections using structured JSON outputs.
    • Competitor Intelligence: Executes multiple concurrent Sonar queries to identify competitors, funding status, and threat levels (scored 1-10).
    • VC & Co-founder Matching: Uses Sonar's real-time web knowledge to match investors and co-founders based on investment thesis, expertise, and geographic proximity.
    • Context-Aware Business Assistant: Implements RAG (Retrieval-Augmented Generation) by feeding research data into Sonar conversations to provide strategic advice.
    • Geographic Intelligence: Combines Sonar's demographic insights with Mapbox geocoding to create interactive heatmaps.
  10. How TruthTracer uses the Sonar API

    main

    TruthTracer implements a multi-layered analysis by executing three different Perplexity Sonar models in parallel. This approach combines fact-checking, deep research for trust chains, and logical reasoning.

    • Fact-checking: Uses the sonar model.
    • Trust Chain Analysis: Uses the sonar-deep-research model for extensive sourcing.
    • Socratic Reasoning: Uses the sonar-reasoning model for logical evaluation.

    Results from these three calls are combined using a weighted scoring system defined in the configuration.

    // Parallel execution of multiple Sonar models
    const [factCheckResult, trustChainResult, socraticResult] = await Promise.all([
      sonarClient.chat.completions.create({
        model: "sonar",
        messages: [{ role: "user", content: factCheckPrompt }],
        max_tokens: 500
      }),
      sonarClient.chat.completions.create({
        model: "sonar-deep-research", 
        messages: [{ role: "user", content: trustChainPrompt }],
        max_tokens: 2500
      }),
      sonarClient.chat.completions.create({
        model: "sonar-reasoning",
        messages: [{ role: "user", content: socraticPrompt }],
        max_tokens: 4000
      })
    ]);
  11. How PerplexiCart uses the Perplexity Sonar API

    main

    PerplexiCart uses the Perplexity Sonar API as its core intelligence engine to perform live web research. The integration follows this pattern:

    1. Dynamic Prompt Engineering: The FastAPI backend constructs customized prompts based on the user's search query, selected priorities (e.g., Eco-Friendly, Durability, Ethical), and additional context (e.g., skin type, region).
    2. Structured Output: The application enforces a strict JSON schema using the response_format parameter. This ensures the API returns consistent data that the Next.js frontend can reliably render.
    3. Web Research & Semantic Analysis: The API is directed to search e-commerce platforms, forums (Reddit, Quora), review blogs, and sustainability reports. It extracts:
      • Research summaries and top recommendations.
      • Value alignment reasoning.
      • Pros/Cons and key specifications.
      • User sentiment and community insights.
      • Transparent citations for all findings.
  12. BazaarAISaathi technical architecture and AI integration

    main

    BazaarAISaathi is structured as follows:

    • Frontend: Streamlit web application providing interactive pages and real-time data visualization.
    • Backend: Python-based logic utilizing Pandas for data manipulation and analysis.
    • AI Integration: Uses Perplexity Sonar API models, specifically sonar-deep-research, sonar-reasoning-pro, and sonar-pro, to perform financial analysis.
    • Text Extraction: Uses EasyOCR to process investment tips from images.
    • Data Processing: Handles real-time stock data fetching, CSV management, and market insight generation.