Skip to main content
Loading navigation
Back to prompt library

Agent Initialization and Perplexity Tool Integration

Linked challenge: Perplexity-Powered Growth Intelligence Agent with OpenAI Agents SDK

Prompt source

implementation59 lines9 sectionsNo variables1 code block
Your first task is to set up your OpenAI Agent environment. This involves initializing the OpenAI client and defining a custom tool for the Perplexity Search SDK. Implement a Python function, `perplexity_search(query: str, focus: Optional[str] = 'online') -> str`, that wraps the Perplexity API. Ensure it handles API key authentication and returns search results in a concise, useful format for the agent. Decorate this function with `@tool` from `openai.tool` to expose it to your agent. Instantiate an `openai.OpenAI` client and create a new Assistant (or load an existing one) with this tool enabled.

```python
import openai
from openai.types.beta.threads import Message
from openai import tool
from perplexity import Perplexity
import os
import json
from typing import Optional

# Ensure you have your API keys set as environment variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")

client = openai.OpenAI(api_key=OPENAI_API_KEY)
perplexity_client = Perplexity(api_key=PERPLEXITY_API_KEY)

@tool
def perplexity_search(query: str, focus: str = 'online') -> str:
    """
    Performs a web search using the Perplexity API.
    Args:
        query (str): The search query.
        focus (str): The search focus (e.g., 'online', 'academic', 'wolfram'). Defaults to 'online'.
    Returns:
        str: A JSON string of search results, including answers and relevant snippets.
    """
    try:
        response = perplexity_client.chat.completions.create(
            model="sonar-medium-online", # Or sonar-small-online
            messages=[
                {"role": "system", "content": "You are a helpful assistant that provides concise search summaries."},
                {"role": "user", "content": f"Search and summarize: {query}"}
            ],
            stream=False,
            max_tokens=500, # Limit response length
            temperature=0.1,
            return_citations=True
        )
        
        # Extract the main answer and citations
        full_response = response.choices[0].message.content
        citations = response.choices[0].message.citations if hasattr(response.choices[0].message, 'citations') else []

        # Format results for the agent
        formatted_citations = []
        for c in citations:
            formatted_citations.append({"url": c.url, "title": c.title, "snippet": c.snippet if hasattr(c, 'snippet') else 'No snippet provided.'})

        formatted_results = {
            "answer": full_response,
            "citations": formatted_citations
        }
        return json.dumps(formatted_results)
    except Exception as e:
        return json.dumps({"error": str(e)})

# Example Assistant creation (adjust as needed for your agent's specific role)
# assistant = client.beta.assistants.create(
#     name="Growth Intelligence Analyst",
#     instructions="You are an expert growth marketing analyst. Your goal is to identify growth opportunities for businesses by researching market trends, competitors, and customer pain points using search tools. You must provide detailed, actionable insights with full citations.",
#     tools=[{"type": "function", "function": perplexity_search.openai_schema}], # Attach the tool
#     model="gpt-4o" # Or gpt-4-turbo
# )
# print(f"Assistant ID: {assistant.id}")
```