### Project Installation Setup (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/perplexicart.mdx Clones the GitHub repository and initializes the backend virtual environment with Python dependencies, followed by frontend Node.js package installation. Requires Node.js 18+, Python 3.10+, npm/yarn, and git. Outputs configured project directories ready for API key setup and running. ```bash # Clone the repository git clone https://github.com/fizakhan90/perplexicart.git cd perplexicart # Backend (FastAPI) setup cd backend python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -r requirements.txt # Frontend (Next.js) setup cd ../frontend npm install ``` -------------------------------- ### Start Development Server (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/flow-and-focus.mdx Starts the Next.js development server for the Flow & Focus application, allowing local testing and development. Requires the project to be installed and configured. ```bash npm run dev ``` -------------------------------- ### Start Briefo Development Server Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/briefo.mdx This command starts the Expo development server for the Briefo application. Ensure Expo CLI is installed globally. ```bash npx expo start ``` -------------------------------- ### Start Backend and Frontend Servers (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/monday.mdx Starts the Node.js backend server and the frontend development server for the Monday application. ```bash # Start Backend Server node backend-server.js # Start frontend npm run dev ``` -------------------------------- ### Clone and Install Briefo Project Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/briefo.mdx This command sequence clones the Briefo public repository and installs its npm dependencies. Ensure you have Node.js and npm (or Yarn/pnpm) installed. ```bash git clone https://github.com/adamblackman/briefo-public.git cd briefo-public npm install ``` -------------------------------- ### Starting Next.js Frontend Development Server (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/perplexicart.mdx Launches the Next.js development server for the frontend application. Run from the frontend directory after installation; provides hot reloading for UI components consuming backend API. Accessible at http://localhost:3000 for product search and recommendation interface. ```bash cd frontend npm run dev ``` -------------------------------- ### Clone Repository and Install Dependencies (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/monday.mdx Clones the Monday project repository from GitHub, checks out the 'final' branch, navigates to the 'nidsmonday' directory, and installs the necessary Node.js dependencies. ```bash # Clone the repository git clone https://github.com/srivastavanik/monday.git cd monday git checkout final cd nidsmonday # Install dependencies npm install ``` -------------------------------- ### Start Backend Service (Python) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/greenify.mdx Initiates the Python Flask backend service for the Greenify application. This script should be run from the 'service' directory after all dependencies are installed and the configuration is set. It enables the backend to handle requests for image processing and Perplexity API integration. ```python cd service python app.py ``` -------------------------------- ### Environment Setup and Dependencies Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Sets up the Python environment by importing required packages including requests for API calls, pandas for data handling, IPython for notebook display capabilities, and system libraries for web browser integration. ```python import requests import json import pandas as pd from IPython.display import HTML, display, IFrame import os import webbrowser from pathlib import Path print('Setup complete.') ``` -------------------------------- ### Install and Build Obsidian Plugin Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/daily-news-briefing.mdx These bash commands are used to clone the plugin's repository, install its dependencies using npm, and build the plugin for use with Obsidian. Ensure you have Node.js and npm installed. ```bash # Clone the repository git clone https://github.com/ChenziqiAdam/Daily-News-Briefing.git cd Daily-News-Briefing # Install dependencies npm install # Build the plugin npm run build ``` -------------------------------- ### Execute Example Usage Functions Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Runs the example functions to demonstrate the API integration and browser UI. This includes testing the API call simulation and launching the browser application. Should be executed after defining the required functions. ```python # Run the examples test_api_in_notebook() launch_browser_app() print('Example usage executed.') ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/greenify.mdx Installs the necessary frontend and backend dependencies for the Greenify project. Requires Node.js, npm, Python, and pip. Clones the repository, navigates into the project directory, and then installs dependencies separately for the frontend (npm) and backend (pip). ```bash git clone https://github.com/deepjyotiipaulhere/greenify.git cd greenify # Install frontend dependencies npm install # Install backend dependencies cd service pip install -r requirements.txt ``` -------------------------------- ### Run TruthTracer Backend and Frontend Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/truth-tracer.mdx Starts the development servers for both the NestJS backend and the React frontend. Assumes dependencies are installed and configuration is complete. Access the application via http://localhost:3000. ```bash cd truth-tracer-backend npm run start:dev cd truth-tracer-front npm start ``` -------------------------------- ### Install Project Dependencies (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/flow-and-focus.mdx Installs the necessary Node.js dependencies for the Flow & Focus project after cloning the repository. Requires Node.js 18+ and npm. ```bash git clone https://github.com/michitomo/NewsReel.git cd NewsReel npm install ``` -------------------------------- ### Clone and Install 4Point Hoops Frontend and Backend Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/4point-Hoops.mdx Commands to clone both frontend and backend repositories from GitHub and install their respective dependencies using npm and pip. The frontend uses Node.js packages while the backend requires Python libraries listed in requirements.txt. ```bash # Clone the frontend repository git clone https://github.com/rapha18th/hoop-ai-frontend-44.git cd hoop-ai-frontend-44 npm install # Clone the backend repository git clone https://github.com/rapha18th/4Point-Hoops-Server.git cd 4Point-Hoops-Server pip install -r requirements.txt ``` -------------------------------- ### Start React Frontend Development Server Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/4point-Hoops.mdx Launches the React development server with hot reloading for local development. The frontend provides the user interface for NBA analytics, data visualization, and AI-powered insights. ```bash cd hoop-ai-frontend-44 npm run dev ``` -------------------------------- ### Install and Build Chrome Extension Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/uncovered.mdx Commands to clone the UnCovered repository, navigate into the directory, install project dependencies using npm, and build the Chrome extension. ```bash # Clone the repository git clone https://github.com/aayushsingh7/UnCovered.git cd UnCovered # Install dependencies npm install # Build the Chrome extension npm run build ``` -------------------------------- ### Test Perplexity API in Notebook Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Demonstrates how to test API calls to Perplexity within a Jupyter notebook. The function prints example questions and simulates API requests. Actual API calls are commented out to prevent quota usage. Requires a valid API key to be configured separately. ```python def test_api_in_notebook(): print("Example 1: Direct API Call") print("-------------------------") example_question = "What is diabetes?" print(f"Question: {example_question}") print("Sending request to Perplexity API...") # Uncomment the following lines to make an actual API call: # result = ask_disease_question(example_question) # display_results(result) print("(API call commented out to avoid using your API quota)") print("\n") ``` -------------------------------- ### Define Custom Instructions for Agent Behavior Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This example shows how to provide detailed, multi-line instructions to customize an agent's persona and behavior. The instructions guide the agent to act as a research assistant, emphasizing citations, verification, and conciseness, and specifying the use of particular tools. ```python agent = Agent( name="Research Assistant", instructions=""" You are a research assistant specializing in academic literature. Always provide citations and verify information through multiple sources. Be thorough but concise in your responses. """, model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client), tools=[search_papers, get_citations], ) ``` -------------------------------- ### JSON Output and jq Integration Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/financial-news-tracker/README.mdx Utilize the --json flag to get structured output from the financial_news_tracker script, enabling easy parsing with tools like jq. This example shows how to extract specific market sentiment data. ```bash ./financial_news_tracker.py "bitcoin" --json | jq '.market_analysis.market_sentiment' ``` -------------------------------- ### Starting FastAPI Backend Server (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/perplexicart.mdx Activates the Uvicorn server to run the FastAPI backend application in development mode with auto-reload. Must be executed from the backend directory after environment activation and configuration. Listens for requests, typically on port 8000, for integration with frontend. ```bash cd backend uvicorn main:app --reload # adapt module:app if your entrypoint differs ``` -------------------------------- ### Start Python Flask Backend Server Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/4point-Hoops.mdx Starts the Python Flask backend server that handles Basketball-Reference data scraping, Perplexity API calls, and Firebase integration. The server provides REST API endpoints for the frontend application. ```bash cd 4Point-Hoops-Server python app.py ``` -------------------------------- ### Install Dependencies using Pip Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md Installs the necessary Python packages: openai for interacting with OpenAI APIs and nest-asyncio to handle nested event loops, which can be useful in environments like Jupyter notebooks. ```bash pip install openai nest-asyncio ``` -------------------------------- ### Install Backend and Frontend Dependencies Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/truth-tracer.mdx Installs Node.js dependencies for both the backend (NestJS) and frontend (React) of the TruthTracer application. Requires Node.js 18+ and npm. ```bash # Clone the backend repository git clone https://github.com/anthony-okoye/truth-tracer-backend.git cd truth-tracer-backend # Install dependencies npm install # Clone the frontend repository git clone https://github.com/anthony-okoye/truth-tracer-front.git cd truth-tracer-front # Install frontend dependencies npm install ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/uncovered.mdx Example configuration for environment variables required by the UnCovered project, including API keys and connection strings for Perplexity, MongoDB, Cloudinary, and Google OAuth. ```ini PERPLEXITY_API_KEY=your_sonar_api_key MONGODB_URI=your_mongodb_connection_string CLOUDINARY_URL=your_cloudinary_credentials GOOGLE_OAUTH_CLIENT_ID=your_google_oauth_id ``` -------------------------------- ### Schedule Python Script with Cron Jobs (Linux/Mac) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb Provides instructions on how to schedule a Python script to run daily using cron jobs on Linux or macOS. It involves saving the script, making it executable, and adding a crontab entry. Example shown for running at 9 AM daily. ```bash # 1. Save the complete script as daily_knowledge_bot.py # 2. Make it executable with: chmod +x daily_knowledge_bot.py # 3. Edit your crontab with: crontab -e # 4. Add a line like this to run it at 9 AM daily: 0 9 * * * /path/to/python /path/to/daily_knowledge_bot.py ``` -------------------------------- ### Schedule Python Script with Task Scheduler (Windows) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb Explains how to schedule a Python script for daily execution using Windows Task Scheduler. This involves saving the script, creating a basic task, setting the trigger to daily, and configuring the action to 'Start a Program', specifying the Python executable and the script path as arguments. ```batch # 1. Save the script as daily_knowledge_bot.py # 2. Open Task Scheduler # 3. Create a Basic Task # 4. Set it to run daily # 5. Set the action to "Start a Program" # 6. Browse to your Python executable and add the script as an argument # Program: C:\Path\to\Python.exe # Arguments: C:\Path\to\daily_knowledge_bot.py ``` -------------------------------- ### Install Required Dependencies for LlamaIndex and Perplexity Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/memory-management/chat-summary-memory-buffer/README.mdx Lists core dependencies needed for the implementation including llama-index-core, llama-index-llms-openai, and openai packages. These versions ensure compatibility with ChatSummaryMemoryBuffer and Perplexity Sonar API integration. ```text llama-index-core>=0.10.0 llama-index-llms-openai>=0.10.0 openai>=1.12.0 ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/memory-management/chat-with-persistence/README.mdx Lists the required Python packages and their minimum versions for setting up the persistent chat memory project. These dependencies include LlamaIndex core, LanceDB vector store integration, LanceDB itself, OpenAI client, and python-dotenv. ```bash llama-index-core>=0.10.0 llama-index-vector-stores-lancedb>=0.1.0 lancedb>=0.4.0 openai>=1.12.0 python-dotenv>=0.19.0 ``` -------------------------------- ### Integrate Multiple Function Tools into an Agent Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This code snippet demonstrates how to equip an agent with multiple function tools, expanding its capabilities. It defines example tools for web searching and data analysis, then includes them in the agent's tool list, allowing the agent to choose the appropriate tool for different tasks. ```python @function_tool def search_web(query: str): """Search the web for current information.""" # Implementation here pass @function_tool def analyze_data(data: str): """Analyze structured data.""" # Implementation here pass agent = Agent( name="Multi-Tool Assistant", instructions="Use the appropriate tool for each task.", model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client), tools=[get_weather, search_web, analyze_data], ) ``` -------------------------------- ### Python: Combine Bot Components Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb This Python function serves as the main orchestrator for the daily knowledge bot. It calls other functions to get the day's topic, retrieve a fact, and save it to a file, returning a dictionary with the results. It depends on `get_todays_topic`, `get_daily_fact`, and `save_fact_to_file` (assumed to be defined elsewhere) and `datetime`. ```python from datetime import datetime def run_daily_knowledge_bot(): """ Main function that runs the daily knowledge bot. Gets a fact about today's topic and saves it to a file. """ # Get today's topic today_topic = get_todays_topic() # Assumes get_todays_topic is defined print(f"Getting today's fact about: {today_topic}") # Get the fact fact = get_daily_fact(today_topic) # Assumes get_daily_fact is defined print(f"\nToday's {today_topic} fact: {fact}") # Save the fact to a file saved_file = save_fact_to_file(today_topic, fact) # Assumes save_fact_to_file is defined return { "topic": today_topic, "fact": fact, "file": saved_file, "date": datetime.now().strftime("%Y-%m-%d") } # Run our daily knowledge bot result = run_daily_knowledge_bot() # Display the result in a more structured way print("\n" + "-"*50) print("DAILY KNOWLEDGE BOT RESULT") print("-"*50) print(f"Date: {result['date']}") print(f"Topic: {result['topic']}") print(f"Fact saved to: {result['file']}") print("-"*50) ``` -------------------------------- ### Python: Set up Perplexity API Key and Environment Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb Initializes the Python environment by importing necessary libraries and configuring the Perplexity API key. It checks if the API key is set, either directly or via an environment variable, and provides a warning if it's not configured. ```python import requests import json import os from datetime import datetime # Replace this with your actual Perplexity API key API_KEY = "your_perplexity_api_key" # Alternatively, you can set it as an environment variable # API_KEY = os.environ.get("PERPLEXITY_API_KEY") # Verify we have an API key if not API_KEY or API_KEY == "your_perplexity_api_key": print("āš ļø Warning: You need to set your actual API key to use this notebook.") else: print("āœ… API key is set.") ``` -------------------------------- ### Configure Environment Variables (INI) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/monday.mdx Creates a .env file to store sensitive API keys required for the project's backend services, including Perplexity, ElevenLabs, and YouTube. ```ini # Create a .env file and set your API keys PERPLEXITY_API_KEY=your_api_key ELEVENLABS_API_KEY=your_api_key YOUTUBE_API_KEY=your_api_key ``` -------------------------------- ### Configure Briefo Environment Variables Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/briefo.mdx This snippet shows the necessary environment variables for the Briefo project, including Supabase credentials, Perplexity API key, and other financial data API keys. These should be set in `.env` and `.env.local` files. ```ini # .env (project root) MY_SUPABASE_URL=https://.supabase.co MY_SUPABASE_SERVICE_ROLE_KEY=... PERPLEXITY_API_KEY=... LINKPREVIEW_API_KEY=... ALPACA_API_KEY=... ALPACA_SECRET_KEY=... # .env.local (inside supabase/) # duplicate or override any secrets needed by Edge Functions ``` -------------------------------- ### Launch Browser UI Application Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Generates an HTML file with an interactive UI and attempts to open it in a browser. The function displays the file path and tries to render a preview using IFrame. May not work in all environments due to display limitations. Depends on the launch_browser_ui() function being properly implemented. ```python def launch_browser_app(): print("Example 2: Launching Browser UI") print("-----------------------------") print("Generating HTML file and opening in browser...") path = launch_browser_ui() print(f"\nHTML file created at: {path}") print("\nIf the browser doesn't open automatically, you can manually open the file above.") try: display(HTML(f'

Preview of UI (may not work in all environments):

')) display(IFrame(path, width='100%', height=600)) except Exception as e: print("Preview not available in this environment.") ``` -------------------------------- ### Python: Create and Launch HTML UI for Perplexity API Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb This Python function 'launch_browser_ui' orchestrates the creation of an HTML file for a user interface and then opens it in a web browser. It relies on another function 'create_html_ui' to generate the HTML content, passing the Perplexity API key and a desired filename. It returns the absolute path to the generated HTML file. ```python # Step 6: Launch the Browser UI def launch_browser_ui(api_key=API_KEY, html_path="disease_qa.html"): """ Generate and open the HTML UI in a web browser. Args: api_key (str): The Perplexity API key. html_path (str): Path to save the HTML file. Returns: str: The absolute path to the created HTML file. """ full_path = create_html_ui(api_key, html_path) file_url = f"file://{full_path}" print(f"Opening browser UI: {file_url}") webbrowser.open(file_url) return full_path print('launch_browser_ui function defined.') ``` -------------------------------- ### Run Financial News Tracker Script Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/financial-news-tracker/README.mdx Execute the financial_news_tracker script with different queries to gather market-related information. This script takes a search query as an argument and can output results in various formats. ```bash # Track geopolitical impacts on markets ./financial_news_tracker.py "oil prices Middle East geopolitics" # Monitor economic indicators ./financial_news_tracker.py "inflation CPI unemployment Federal Reserve" ``` -------------------------------- ### Daily Knowledge Bot Script Boilerplate in Python Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb A Python script boilerplate for a 'Daily Knowledge Bot'. It includes necessary imports for API requests, JSON handling, OS interactions, and date/time management. It suggests secure API key storage using environment variables and provides basic usage instructions. ```python # Below is the complete script you can save as daily_knowledge_bot.py #!/usr/bin/env python3 """ Daily Knowledge Bot This script uses the Perplexity API to fetch an interesting fact about a rotating topic each day. It can be scheduled to run daily using cron or Task Scheduler. Usage: python daily_knowledge_bot.py Requirements: - requests """ import requests import json import os from datetime import datetime # Store your API key securely (consider using environment variables in production) ``` -------------------------------- ### Configure Environment Variables (INI) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/flow-and-focus.mdx Sets up the required API keys and model configuration for the Flow & Focus application by creating a .env.local file. Requires Perplexity API key and Runware API key. ```ini PERPLEXITY_API_KEY=your_perplexity_api_key_here RUNWARE_API_KEY=your_runware_api_key_here PERPLEXITY_FOCUS_MODEL=sonar-deep-research ``` -------------------------------- ### Perplexity API Configuration Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Configures the Perplexity API credentials and endpoint for making disease-related queries. Requires users to replace the placeholder API key with their actual Perplexity (Sonar) API key to enable functionality. ```python # Replace with your Perplexity API key API_KEY = 'YOUR_API_KEY' API_ENDPOINT = 'https://api.perplexity.ai/chat/completions' print('API configuration set.') ``` -------------------------------- ### Add Logging to Function Tools Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This example integrates Python's built-in logging module into a function tool. By using `logger.info`, you can track when specific tool functions are called and with what arguments, which is crucial for debugging and monitoring agent behavior in production environments. ```python import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @function_tool def get_weather(city: str): logger.info(f"Fetching weather for {city}") # Implementation here ``` -------------------------------- ### Implement Robust Error Handling for Agent Execution Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This Python function implements error handling for agent execution using a try-except block. It ensures that if any exception occurs during agent setup or execution, an error message is logged and a user-friendly fallback response is returned, preventing application crashes. ```python async def robust_main(): try: agent = Agent( name="Assistant", instructions="Be helpful and accurate.", model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client), tools=[get_weather], ) result = await Runner.run(agent, "What's the weather in Tokyo?") return result.final_output except Exception as e: print(f"Error running agent: {e}") return "Sorry, I encountered an error processing your request." ``` -------------------------------- ### Configure Perplexity API Key (INI) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/greenify.mdx Sets up the Perplexity API key for the backend service. This involves creating a .env file in the 'service' directory and adding the PPLX_API_KEY variable with your actual API key. This configuration is crucial for the backend to authenticate with the Perplexity API for image analysis and recommendations. ```ini PPLX_API_KEY=your_perplexity_api_key_here ``` -------------------------------- ### Configure Backend Environment Variables Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/4point-Hoops.mdx Creates a .env file in the backend directory containing required API keys and Firebase credentials. Includes Perplexity API key for Sonar Pro access and Firebase configuration for authentication and data storage. ```ini PERPLEXITY_API_KEY=your_sonar_pro_api_key FIREBASE_PROJECT_ID=your_firebase_project_id FIREBASE_PRIVATE_KEY=your_firebase_private_key FIREBASE_CLIENT_EMAIL=your_firebase_client_email ``` -------------------------------- ### Create an Agent with Custom Instructions and Tools Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This snippet demonstrates the creation of an `Agent` instance, combining language model capabilities with predefined instructions and tools. It utilizes an `OpenAIChatCompletionsModel` configured with a specific model name and the previously initialized client, along with a list of available function tools. ```python agent = Agent( name="Assistant", instructions="Be precise and concise.", model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client), tools=[get_weather], ) ``` -------------------------------- ### Get Real-Time Local Information with Sonar Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/citypulse-ai-search.mdx This Python snippet demonstrates how to use the Perplexity API's 'sonar' model to retrieve current local information based on geographic coordinates. It requires a Perplexity client instance and specifies a JSON schema for the expected response, enabling structured data retrieval for events, restaurants, and alerts. ```python client.chat.completions.create( model="sonar", messages=[{ "role": "user", "content": f"Find current events, restaurants, and alerts near {lat}, {lng}" }], response_format={"type": "json_schema", "json_schema": {"schema": LOCAL_INFO_SCHEMA}} ) ``` -------------------------------- ### Create HTML Disease Q&A UI (Python) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb Generates an HTML file that provides a user interface for asking questions about diseases. It includes input fields, a submit button, and areas to display knowledge cards and citations. This function requires a Perplexity API key. ```python def create_html_ui(api_key, output_path="disease_qa.html"): """ Create an HTML file with the disease Q&A interface. Args: api_key (str): The Perplexity API key. output_path (str): Path where the HTML file will be saved. Returns: str: The absolute path to the created HTML file. """ html_content = f""" market_report.txt echo "Date: $(date)" >> market_report.txt echo "" >> market_report.txt ./financial_news_tracker.py "S&P 500 market overview" >> market_report.txt ./financial_news_tracker.py "top gaining stocks" >> market_report.txt ./financial_news_tracker.py "cryptocurrency bitcoin ethereum" >> market_report.txt ``` -------------------------------- ### Complete OpenAI Agents Integration Implementation Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.mdx Full Python implementation for integrating Perplexity's Sonar API with OpenAI Agents. It sets up an async client, defines a function tool for fetching weather, configures an agent, and runs a query using the agent. Requires environment variables to be set. ```python # Import necessary standard libraries import asyncio # For running asynchronous code import os # To access environment variables # Import AsyncOpenAI for creating an async client from openai import AsyncOpenAI # Import custom classes and functions from the agents package. # These handle agent creation, model interfacing, running agents, and more. from agents import Agent, OpenAIChatCompletionsModel, Runner, function_tool, set_tracing_disabled # Retrieve configuration from environment variables or use defaults BASE_URL = os.getenv("EXAMPLE_BASE_URL") or "https://api.perplexity.ai" API_KEY = os.getenv("EXAMPLE_API_KEY") MODEL_NAME = os.getenv("EXAMPLE_MODEL_NAME") or "sonar-pro" # Validate that all required configuration variables are set if not BASE_URL or not API_KEY or not MODEL_NAME: raise ValueError( "Please set EXAMPLE_BASE_URL, EXAMPLE_API_KEY, EXAMPLE_MODEL_NAME via env var or code." ) # Initialize the custom OpenAI async client with the specified BASE_URL and API_KEY. client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY) # Disable tracing to avoid using a platform tracing key; adjust as needed. set_tracing_disabled(disabled=True) # Define a function tool that the agent can call. # The decorator registers this function as a tool in the agents framework. @function_tool def get_weather(city: str): """ Simulate fetching weather data for a given city. Args: city (str): The name of the city to retrieve weather for. Returns: str: A message with weather information. """ print(f"[debug] getting weather for {city}") return f"The weather in {city} is sunny." # Import nest_asyncio to support nested event loops import nest_asyncio # Apply the nest_asyncio patch to enable running asyncio.run() # even if an event loop is already running. nest_asyncio.apply() async def main(): """ Main asynchronous function to set up and run the agent. This function creates an Agent with a custom model and function tools, then runs a query to get the weather in Tokyo. """ # Create an Agent instance with: # - A name ("Assistant") # - Custom instructions ("Be precise and concise.") # - A model built from OpenAIChatCompletionsModel using our client and model name. # - A list of tools; here, only get_weather is provided. agent = Agent( name="Assistant", instructions="Be precise and concise.", model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client), tools=[get_weather], ) # Execute the agent with the sample query. result = await Runner.run(agent, "What's the weather in Tokyo?") # Print the final output from the agent. print(result.final_output) # Standard boilerplate to run the async main() function. if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Complete Python Implementation for OpenAI Agents Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md Provides the full Python code for integrating Perplexity's Sonar API with OpenAI Agents. It sets up an asynchronous client, defines a weather-fetching function tool, and configures necessary environment variables. Requires Python 3.7+ and a Perplexity API key. ```python # Import necessary standard libraries import asyncio # For running asynchronous code import os # To access environment variables # Import AsyncOpenAI for creating an async client from openai import AsyncOpenAI # Import custom classes and functions from the agents package. # These handle agent creation, model interfacing, running agents, and more. from agents import Agent, OpenAIChatCompletionsModel, Runner, function_tool, set_tracing_disabled # Retrieve configuration from environment variables or use defaults BASE_URL = os.getenv("EXAMPLE_BASE_URL") or "https://api.perplexity.ai" API_KEY = os.getenv("EXAMPLE_API_KEY") MODEL_NAME = os.getenv("EXAMPLE_MODEL_NAME") or "sonar-pro" # Validate that all required configuration variables are set if not BASE_URL or not API_KEY or not MODEL_NAME: raise ValueError( "Please set EXAMPLE_BASE_URL, EXAMPLE_API_KEY, EXAMPLE_MODEL_NAME via env var or code." ) # Initialize the custom OpenAI async client with the specified BASE_URL and API_KEY. client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY) # Disable tracing to avoid using a platform tracing key; adjust as needed. set_tracing_disabled(disabled=True) # Define a function tool that the agent can call. # The decorator registers this function as a tool in the agents framework. @function_tool def get_weather(city: str): """ Simulate fetching weather data for a given city. Args: city (str): The name of the city to retrieve weather for. Returns: str: A message with weather information. """ print(f"[debug] getting weather for {city}") return f"The weather in {city} is sunny." # Import nest_asyncio to support nested event loops import nest_asyncio # Apply the nest_asyncio patch to enable running asyncio.run() ``` -------------------------------- ### Set Up Perplexity API Key Environment Variable Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/memory-management/chat-summary-memory-buffer/README.mdx Configures required authentication for Perplexity Sonar API by exporting API key as environment variable. Must be set before running the application to enable API access. ```bash export PERPLEXITY_API_KEY="your_pplx_key_here" ``` -------------------------------- ### Deploy Briefo Supabase Edge Functions Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/briefo.mdx This command deploys the Supabase Edge Functions for the Briefo project. These functions handle interactions with external APIs like Perplexity and Alpaca. ```bash supabase functions deploy perplexity-news perplexity-chat perplexity-research portfolio-tab-data ``` -------------------------------- ### Select Different Sonar Models for AI Tasks Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This code illustrates how to select different Sonar models based on the complexity and requirements of the task. Options range from 'sonar' for lightweight queries to 'sonar-pro' for general use and 'sonar-reasoning-pro' for advanced reasoning. ```python # For quick, lightweight queries MODEL_NAME = "sonar" # For complex research and analysis (default) MODEL_NAME = "sonar-pro" # For deep reasoning tasks MODEL_NAME = "sonar-reasoning-pro" ``` -------------------------------- ### Clone repository for Chromium patch Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/sonar-chromium-browser.mdx Clones the GitHub repository containing the Chromium patch files. This is the first step in setting up the custom Chromium build with Sonar API integration. ```bash git clone https://github.com/KoushikBaagh/perplexity-hackathon-chromium.git cd perplexity-hackathon-chromium ``` -------------------------------- ### Save fact to timestamped text file Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb Writes daily facts to text files with formatted timestamps and topic information. Creates unique filenames based on current date and includes structured formatting with headers. ```python def save_fact_to_file(topic, fact): """ Saves the fact to a text file with timestamp. Args: topic (str): The topic of the fact fact (str): The fact content """ timestamp = datetime.now().strftime("%Y-%m-%d") filename = f"daily_fact_{timestamp}.txt" with open(filename, "w") as f: f.write(f"DAILY FACT - {timestamp}\n") f.write(f"Topic: {topic}\n\n") f.write(fact) print(f"Fact saved to {filename}") ``` -------------------------------- ### Configure Async OpenAI Client for Perplexity Sonar API Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This code snippet initializes an asynchronous OpenAI client specifically configured to communicate with Perplexity's Sonar API. It requires the API endpoint URL and an API key, ensuring compatibility with the standard OpenAI interface for seamless integration. ```python client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY) ``` -------------------------------- ### Interact with Perplexity Sonar API for News and Summarization (TypeScript) Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/showcase/daily-news-briefing.mdx This TypeScript code demonstrates how to use the Perplexity Sonar API to gather news articles based on a topic and then summarize the content. It requires the Perplexity client to be initialized and assumes user preferences and topic are defined. ```typescript // News gathering with Perplexity Sonar API const newsQuery = `latest news about ${topic} in the past 24 hours`; const searchResponse = await perplexityClient.search({ query: newsQuery, max_results: 5, include_domains: userPreferences.trustedSources || [] }); // AI-powered summarization const summaryPrompt = `Summarize these news articles about ${topic}`; const summaryResponse = await perplexityClient.generate({ prompt: summaryPrompt, model: "sonar-medium-online", max_tokens: 500 }); ``` -------------------------------- ### Run an Agent with a Specific Query Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/openai-agents-integration/README.md This Python code executes a configured agent with a given natural language query. The `Runner.run` method asynchronously processes the query, leveraging the agent's model and tools to produce a final output, which is then printed. ```python result = await Runner.run(agent, "What's the weather in Tokyo?") print(result.final_output) ``` -------------------------------- ### Python: Email Daily Fact Function Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/daily-knowledge-bot/daily_knowledge_bot.ipynb This Python function demonstrates how to send the daily fact via email using `smtplib` and `email.mime`. It constructs an HTML email and includes placeholders for sender credentials and SMTP server details. It requires `datetime` and the `email.mime` module. Note that actual sending is commented out. ```python import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime def send_email(topic, fact, recipient): """ Sends the daily fact via email. Args: topic (str): The topic of the fact fact (str): The fact content recipient (str): Email address to send to Note: This is just a template. You would need to fill in your SMTP server details. """ # Email details sender_email = "your_email@example.com" # Update this password = "your_password" # Update this (consider using app passwords for security) # Create message message = MIMEMultipart() message["Subject"] = f"Daily Knowledge: {topic.capitalize()}" message["From"] = sender_email message["To"] = recipient # Email body current_date = datetime.now().strftime("%Y-%m-%d") email_content = f"""

Your Daily Interesting Fact - {current_date}

Topic: {topic.capitalize()}

{fact}


Brought to you by Daily Knowledge Bot

""" message.attach(MIMEText(email_content, "html")) # Connect to server and send (commented out as this requires actual credentials) """ with smtplib.SMTP_SSL("smtp.example.com", 465) as server: # Update with your SMTP server server.login(sender_email, password) server.send_message(message) print(f"Email sent to {recipient}") """ # Since we're just displaying the concept, print what would be sent print(f"\nWould send email to: {recipient}") print(f"Subject: Daily Knowledge: {topic.capitalize()}") print("Content:") print(f"Topic: {topic.capitalize()}") print(f"Fact: {fact}") ``` -------------------------------- ### Python: Display API Results in a Structured Format Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/examples/disease-qa/disease_qa_tutorial.ipynb This Python function 'display_results' takes structured data from an API and presents it using a pandas DataFrame for textual information (overview, causes, treatments) and a simple list for citations. It enhances the DataFrame's appearance with basic styling for better readability in a notebook environment. ```python # Step 5: Display API Results in the Notebook def display_results(data): """ Display the API results in a structured format using a pandas DataFrame and text output. Args: data (dict): The parsed JSON data from the API. """ if not data: print("No data to display.") return df = pd.DataFrame({ "Category": ["Overview", "Causes", "Treatments"], "Information": [ data.get("overview", "N/A"), data.get("causes", "N/A"), data.get("treatments", "N/A") ] }) print("\nšŸ’” Knowledge Card:") display(df.style.set_table_styles([ {'selector': 'th', 'props': [('background-color', '#fafafa'), ('color', '#333'), ('font-weight', 'bold'))}, {'selector': 'td', 'props': [('padding', '10px')]}, ])) print("\nšŸ“š Citations:") if data.get("citations") and isinstance(data["citations"], list) and len(data["citations"]) > 0: for i, citation in enumerate(data["citations"], 1): print(f"{i}. {citation}") else: print("No citations provided.") print('display_results function defined.') ``` -------------------------------- ### Execute Chat Application with Memory Management Source: https://github.com/ppl-ai/api-cookbook/blob/main/docs/articles/memory-management/chat-summary-memory-buffer/README.mdx Runs the complete chat application with integrated memory management. Executes the example_usage.py script to demonstrate multi-turn conversations with persistent memory and summarization capabilities. ```bash python3 scripts/example_usage.py ```