Skip to content

promptlyagentai/perplexity-integration

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Perplexity AI Research Integration for PromptlyAgent

This package provides seamless integration between PromptlyAgent and Perplexity AI's research capabilities, enabling AI-powered research with real-time web search and citation-backed responses.

Screenshots

Configure and use Perplexity AI research through the PromptlyAgent interface:

Perplexity Integration Configuration

Configure Perplexity API key, select models (sonar, sonar-pro, sonar-reasoning), and customize research parameters

Features

  • Real-time Web Research: Leverage Perplexity AI's powerful web search capabilities
  • Multiple Research Models: Support for sonar, sonar-pro, and sonar-reasoning models
  • Flexible Report Types: Generate comprehensive, quick, or technical research reports
  • Citation Management: Automatic extraction and processing of citations with markdown links
  • Integration Token Management: Secure API key storage via integration_tokens table
  • Status Reporting: Real-time status updates during research operations
  • Configurable Parameters: Customize max_tokens, temperature, and more

Installation

Via Composer

composer require promptlyagentai/perplexity-integration:@dev

The package is automatically discovered by Laravel via Composer's package auto-discovery feature.

Requirements

  • PHP 8.2 or higher
  • Laravel 11.0 or 12.0
  • Prism PHP 0.90.0 or higher
  • Active Perplexity AI API subscription

Configuration

API Key Setup

This package uses the integration_tokens table for secure API key management.

1. Configure Integration via Settings

Navigate to your application settings and add a new Perplexity integration:

  1. Go to Settings > Integrations
  2. Click Add Integration
  3. Select Perplexity as the provider
  4. Enter your Perplexity API key
  5. Set status to Active

2. Programmatic Token Creation

Alternatively, create an integration token programmatically:

use App\Models\IntegrationToken;

IntegrationToken::create([
    'user_id' => auth()->id(),
    'provider_id' => 'perplexity',
    'provider_name' => 'Perplexity AI',
    'token_type' => 'api_key',
    'access_token' => 'your-perplexity-api-key',
    'status' => 'active',
]);

Configuration File

Optionally publish the configuration file:

./vendor/bin/sail artisan vendor:publish --tag=perplexity-config

This creates config/perplexity.php with the following options:

return [
    'api_endpoint' => env('PERPLEXITY_API_ENDPOINT', 'https://api.perplexity.ai/chat/completions'),
    'default_model' => env('PERPLEXITY_DEFAULT_MODEL', 'sonar'),
    'default_report_type' => env('PERPLEXITY_DEFAULT_REPORT_TYPE', 'comprehensive'),
    'default_max_tokens' => env('PERPLEXITY_DEFAULT_MAX_TOKENS', 4000),
    'default_temperature' => env('PERPLEXITY_DEFAULT_TEMPERATURE', 0.2),
    'timeout' => env('PERPLEXITY_TIMEOUT', 120),
    'models' => ['sonar', 'sonar-pro', 'sonar-reasoning'],
    'report_types' => ['comprehensive', 'quick', 'technical'],
];

Usage

The package automatically registers the perplexity_research tool with the PromptlyAgent ToolRegistry.

Available Parameters

  • query (required): The research query to investigate
  • model (optional): Perplexity model to use
    • sonar (default): Balanced performance and speed
    • sonar-pro: Enhanced capabilities for complex research
    • sonar-reasoning: Advanced reasoning for in-depth analysis
  • report_type (optional): Type of report to generate
    • comprehensive (default): Full research report with detailed analysis
    • quick: Concise summary with key points
    • technical: Technical report with implementation details
  • max_tokens (optional): Maximum tokens for response (100-8000, default: 4000)
  • temperature (optional): Response creativity (0.0-1.0, default: 0.2)

Using in Agent Tools

The tool is automatically available to agents configured with the perplexity_research tool:

// The tool will be called by AI agents with parameters like:
[
    'query' => 'Latest developments in AI research',
    'model' => 'sonar-pro',
    'report_type' => 'comprehensive',
    'max_tokens' => 4000,
    'temperature' => 0.2
]

Response Format

The tool returns a structured JSON response:

{
    "success": true,
    "data": {
        "query": "Your research query",
        "model": "sonar-pro",
        "report_type": "comprehensive",
        "content": "Raw research content with citations",
        "enhanced_content": "Formatted markdown with headings and TOC",
        "citations": [
            {
                "text": "Citation text",
                "url": "https://source-url.com",
                "type": "markdown_link"
            }
        ],
        "word_count": 1500,
        "summary": "Brief summary of research completed"
    },
    "metadata": {
        "executed_at": "2025-01-01T12:00:00.000Z",
        "tool_version": "1.0.0",
        "execution_time_ms": 5000,
        "usage": {
            "total_tokens": 3500,
            "prompt_tokens": 500,
            "completion_tokens": 3000
        }
    }
}

Report Types

Comprehensive Report

Generates a full research report including:

  • Executive Summary
  • Key Findings (numbered points)
  • Detailed Analysis (with subheadings)
  • Data & Statistics (formatted tables)
  • Conclusions & Implications
  • Sources section with clickable links

Quick Report

Provides concise analysis:

  • Brief summary (2-3 sentences)
  • 3-5 key points with evidence
  • Sources section with links

Technical Report

Creates technical documentation:

  • Technical Overview
  • Implementation Details
  • Performance Metrics (tables)
  • Best Practices
  • Sources section with technical references

Citation System

The package includes advanced citation processing:

  1. Inline Citations: Automatically formatted as markdown links [claim](url)
  2. Citation Extraction: Extracts both markdown links and numbered citations
  3. Sources Section: Comprehensive list of all sources with proper formatting
  4. Fallback Handling: Gracefully handles numbered citations when URLs aren't available

Error Handling

The tool includes comprehensive error handling:

  • Missing API Key: Returns clear error message with setup instructions
  • API Failures: Detailed error reporting with status codes
  • Invalid Responses: Validation and safe fallbacks
  • JSON Encoding: Safe encoding with UTF-8 cleaning
  • Timeouts: Configurable timeout with proper error messages

Security

  • API keys are encrypted in the database via Laravel's built-in encryption
  • Keys are stored in access_token column with encrypted cast
  • Per-user token isolation ensures data security
  • No API keys stored in configuration files or environment variables

Troubleshooting

Tool Not Available

If the tool doesn't appear in agent configurations:

# Clear Laravel caches
./vendor/bin/sail artisan config:clear
./vendor/bin/sail artisan cache:clear

# Verify package is installed
composer show promptlyagentai/perplexity-integration

# Check service provider registration
./vendor/bin/sail artisan config:show app.providers

API Key Not Found

Ensure your integration token is properly configured:

// Check if token exists
$token = \App\Models\IntegrationToken::where('user_id', auth()->id())
    ->where('provider_id', 'perplexity')
    ->where('status', 'active')
    ->first();

if (!$token) {
    // Create token via Settings > Integrations
}

Request Timeouts

Increase timeout in config:

# In .env
PERPLEXITY_TIMEOUT=180  # 3 minutes

Or programmatically:

config(['perplexity.timeout' => 180]);

License

The MIT License (MIT). Please see License File for more information.

Architecture

This package follows the PromptlyAgent integration pattern:

Core Components

  • Service Provider: PerplexityIntegrationServiceProvider - Registers package with Laravel
  • Integration Provider: PerplexityIntegrationProvider - Handles configuration UI and metadata
  • Tool: PerplexityResearchTool - Implements Prism tool for AI agent integration
  • Traits: SafeJsonResponse - Safe JSON encoding with UTF-8 handling

Package Structure

src/
├── PerplexityIntegrationServiceProvider.php  # Main service provider
├── Providers/
│   └── PerplexityIntegrationProvider.php     # Integration configuration
├── Tools/
│   └── PerplexityResearchTool.php            # Prism tool implementation
└── Concerns/
    └── SafeJsonResponse.php                  # JSON encoding utilities

Support

For issues and questions:

Credits

About

Perplexity AI integration for PromptlyAgentAI

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published