Skip to content

Commit c8eb3aa

Browse files
authored
Merge branch 'main' into main
2 parents f2be219 + 7ef978d commit c8eb3aa

17 files changed

+650
-33
lines changed

.github/workflows/pr-validation.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ jobs:
3030
run: |
3131
# Simple check for common broken link patterns
3232
echo "Checking for potential broken links..."
33-
if grep -r "http://localhost\|http://127.0.0.1" docs/; then
33+
if grep -r "http://localhost\|http://127.0.0.1" docs/ --exclude-dir=showcase; then
3434
echo "❌ Found localhost links that should be removed"
3535
exit 1
3636
fi
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.env.example
2+
DISCORD_TOKEN="YOUR_DISCORD_BOT_TOKEN_HERE"
3+
PERPLEXITY_API_KEY="YOUR_PPLX_API_KEY_HERE"
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
title: Perplexity Discord Bot
3+
description: A runnable discord.py bot that adds a /ask_perplexity command to your server, using the Sonar API for web-connected answers.
4+
sidebar_position: 4
5+
keywords: [discord, bot, discord.py, python, chatbot, perplexity, sonar api, command, slash command]
6+
---
7+
8+
# Perplexity Discord Bot
9+
10+
A runnable `discord.py` application that adds a `/ask_perplexity` slash command to your Discord server, using Perplexity's Sonar API for real-time, web-connected answers.
11+
12+
## 🌟 Features
13+
14+
- **Direct Sonar API Integration**: Uses Perplexity's API for real-time, web-connected answers.
15+
- **Slash Command Ready**: Implements a modern `/ask_perplexity` command that's easy to use.
16+
- **Secure Configuration**: Uses environment variables (`.env`) for both Discord and Perplexity keys, keeping them safe.
17+
- **Administrator Permissions**: Locked to server administrators by default for easy control over API usage.
18+
- **Formatted Embeds**: Delivers answers in a clean, professional Discord embed.
19+
- **Self-Contained Example**: Minimal, single-file code designed to be easy to run and understand.
20+
21+
## 📋 Prerequisites
22+
23+
- **Python 3.8+**
24+
- **A Perplexity API Key**
25+
- **A Discord Bot Token**
26+
27+
## 🚀 Installation & Setup
28+
29+
1. **Clone the Repository:** Fork and clone the `api-cookbook` repository to your local machine.
30+
31+
2. **Navigate to this Example:**
32+
```bash
33+
cd docs/examples/discord-py-bot/
34+
```
35+
3. **Install Dependencies:**
36+
```bash
37+
pip install -r requirements.txt
38+
```
39+
4. **Get Your Secret Keys:**
40+
- **Perplexity API Key:** Get your key from the [Perplexity AI Account Settings](https://www.perplexity.ai/settings/api).
41+
- **Discord Bot Token:**
42+
1. Go to the [Discord Developer Portal](https://discord.com/developers/applications).
43+
2. Click **"New Application"** and give it a name.
44+
3. Go to the **"Bot"** tab and click **"Reset Token"** (or "Add Bot" first if needed).
45+
4. Copy the token. This is your bot's password – keep it safe!
46+
47+
5. **Set Up Your Environment File:**
48+
- Rename the `.env.example` file to `.env`.
49+
- Open the `.env` file and add your secret keys:
50+
```
51+
DISCORD_TOKEN="YOUR_DISCORD_BOT_TOKEN_HERE"
52+
PERPLEXITY_API_KEY="YOUR_PPLX_API_KEY_HERE"
53+
```
54+
55+
## 🔧 Usage
56+
57+
### 1. Invite Your Bot to a Server
58+
59+
- In the Discord Developer Portal, go to "OAuth2" -> "URL Generator".
60+
- Select the `bot` and `applications.commands` scopes.
61+
- Under "Bot Permissions," select **Administrator**.
62+
- Copy the generated URL, paste it into your browser, and invite the bot to your server.
63+
64+
### 2. Run the Bot Script
65+
66+
Simply execute the `bot.py` script from your terminal:
67+
```bash
68+
python bot.py
69+
This will connect the bot to Discord and sync the /ask_perplexity command.
70+
3. Use the Command in Discord
71+
In any channel in your server, an administrator can type:
72+
code
73+
Code
74+
/ask_perplexity prompt:What is the latest news in the world of generative AI?
75+
📄 Output Example
76+
The bot will defer the interaction and then respond with a formatted embed containing the answer:
77+
code
78+
Code
79+
HatchMate [APP]
80+
🌐 Perplexity's Response
81+
82+
The latest news in generative AI includes advancements in large language models... (and so on).
83+
84+
Your Prompt```
85+
What is the latest news in the world of generative AI?
86+
Requested by YourUsername
87+
code
88+
Code
89+
## 🛠️ Extending the Bot
90+
91+
- **Role-Based Access**: Modify the permission checks to allow specific roles, not just administrators.
92+
- **Model Selection**: Add an option to the slash command to choose between different models like `sonar-pro` or `sonar-small-online`.
93+
- **Conversation History**: Implement a database (like SQLite or Redis) to store recent messages and send them with new prompts for conversational context.
94+
95+
## ⚠️ Limitations
96+
97+
- The permission system is basic (administrator-only) to keep the example simple and database-free.
98+
- The command is single-turn and does not remember conversation history.
99+
- API rate limits may apply based on your Perplexity account status.
100+
101+
## 🙏 Acknowledgements
102+
103+
- This project uses the [Perplexity AI API](https://docs.perplexity.ai/).
104+
- Built with the [discord.py](https://discordpy.readthedocs.io/en/stable/) library.

docs/examples/discord-py-bot/bot.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# This code is a simplified example of a Discord bot that integrates with the Perplexity AI API. This is a complete, minimal bot script that someone can run directly. Notice I have simplified the permission logic to only check for administrators to remove the need for an external database, making the example much more focused on the Perplexity API.
2+
3+
# bot.py
4+
import os
5+
import discord
6+
from discord.ext import commands
7+
from discord import app_commands
8+
import openai
9+
from dotenv import load_dotenv
10+
11+
# --- Step 1: Load Environment Variables ---
12+
# This ensures your secret keys are kept safe in a .env file.
13+
load_dotenv()
14+
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
15+
PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY")
16+
17+
# --- Step 2: Bot Setup ---
18+
# We define the bot's intents, which tell Discord what events our bot needs to receive.
19+
intents = discord.Intents.default()
20+
bot = commands.Bot(command_prefix="!", intents=intents)
21+
22+
# --- Step 3: Create a Command Cog ---
23+
# Cogs are how modern discord.py bots organize commands, listeners, and state.
24+
class AIChatCog(commands.Cog):
25+
def __init__(self, bot: commands.Bot):
26+
self.bot = bot
27+
28+
# Initialize the Perplexity AI Client using the key from our .env file.
29+
# The `base_url` is the crucial part that directs the OpenAI library to Perplexity's API.
30+
if PERPLEXITY_API_KEY:
31+
self.perplexity_client = openai.OpenAI(
32+
api_key=PERPLEXITY_API_KEY,
33+
base_url="https://api.perplexity.ai"
34+
)
35+
print("Perplexity AI Client Initialized.")
36+
else:
37+
self.perplexity_client = None
38+
print("CRITICAL: PERPLEXITY_API_KEY not found in .env file.")
39+
40+
# Define the slash command.
41+
# The `has_permissions` check restricts this command to server administrators.
42+
@app_commands.command(name="ask_perplexity", description="Ask a question to Perplexity AI (with web access).")
43+
@app_commands.describe(prompt="The question you want to ask.")
44+
@app_commands.checks.has_permissions(administrator=True)
45+
async def ask_perplexity(self, interaction: discord.Interaction, prompt: str):
46+
if not self.perplexity_client:
47+
return await interaction.response.send_message(
48+
"The Perplexity AI service is not configured on this bot.",
49+
ephemeral=True
50+
)
51+
52+
# Defer the response to give the API time to process without a timeout.
53+
await interaction.response.defer(thinking=True)
54+
55+
try:
56+
# Create the list of messages for the API call, following the standard format.
57+
messages = [{"role": "user", "content": prompt}]
58+
59+
# Call the Perplexity API with the desired model.
60+
response = self.perplexity_client.chat.completions.create(
61+
model="sonar-pro",
62+
messages=messages
63+
)
64+
65+
answer = response.choices[0].message.content
66+
67+
# Create and send a nicely formatted Discord embed for the response.
68+
embed = discord.Embed(
69+
title="🌐 Perplexity's Response",
70+
description=answer,
71+
color=discord.Color.from_rgb(0, 255, 0) # Perplexity Green
72+
)
73+
embed.set_footer(text=f"Requested by {interaction.user.display_name}")
74+
75+
# Truncate the original prompt if it's too long to fit in an embed field.
76+
truncated_prompt = (prompt[:1020] + '...') if len(prompt) > 1024 else prompt
77+
embed.add_field(name="Your Prompt", value=f"```{truncated_prompt}```", inline=False)
78+
79+
await interaction.followup.send(embed=embed)
80+
81+
except Exception as e:
82+
# Inform the user if an error occurs.
83+
error_message = f"An error occurred with the Perplexity API: {e}"
84+
print(error_message)
85+
await interaction.followup.send(error_message, ephemeral=True)
86+
87+
# A local error handler specifically for this command's permission check.
88+
@ask_perplexity.error
89+
async def on_ask_perplexity_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
90+
if isinstance(error, app_commands.MissingPermissions):
91+
await interaction.response.send_message("You must be an administrator to use this command.", ephemeral=True)
92+
else:
93+
# For other errors, print them to the console.
94+
print(f"An unhandled error occurred: {error}")
95+
# Potentially send a generic error message back to the user as well.
96+
if not interaction.response.is_done():
97+
await interaction.response.send_message("An unexpected error occurred.", ephemeral=True)
98+
99+
100+
# --- Step 4: Main Bot Events and Startup Logic ---
101+
@bot.event
102+
async def on_ready():
103+
print(f'Logged in as {bot.user}!')
104+
try:
105+
# Add the cog to the bot so its commands are registered.
106+
await bot.add_cog(AIChatCog(bot))
107+
108+
# Sync the slash commands to Discord. This makes them appear for users.
109+
synced = await bot.tree.sync()
110+
print(f"Synced {len(synced)} command(s).")
111+
except Exception as e:
112+
print(f"Error during setup: {e}")
113+
114+
# This is the entry point for running the bot.
115+
if __name__ == "__main__":
116+
if not DISCORD_TOKEN or not PERPLEXITY_API_KEY:
117+
print("CRITICAL: DISCORD_TOKEN and/or PERPLEXITY_API_KEY not found in .env file. Bot cannot start.")
118+
else:
119+
bot.run(DISCORD_TOKEN)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# requirements.txt
2+
discord.py
3+
openai
4+
python-dotenv

docs/showcase/Ellipsis.mdx

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
---
2+
title: Ellipsis | One-Click Podcast Generation Agent
3+
description: A next-gen podcast generation agent that brings human-like, high-quality audio content to life on any topic with just one click
4+
sidebar_position: 10
5+
keywords: [Ellipsis, podcast, audio, generation, TTS, Perplexity, multi-speaker, AI]
6+
---
7+
8+
**Ellipsis** is a next-generation podcast generation agent that brings human-like, high-quality audio content to life on any topic with just one click. Whether it's breaking news, deep-dive tech explainers, movie reviews, or post-match sports breakdowns, Ellipsis crafts intelligent podcast episodes that sound like they were created by seasoned hosts in a professional studio.
9+
10+
## Features
11+
12+
* **Intelligent Multi-Speaker Dialogue** with multiple distinct voices and personalities
13+
* **Comprehensive Topic Coverage** from LLM architectures to lunar eclipses
14+
* **Custom Evaluation Engine** ensuring factual accuracy, legal compliance, and conversational quality
15+
* **Fully Automated Podcast Generation** with human-like, podcast-ready audio output
16+
* **Real-time Streaming Updates** via Server-Sent Events (SSE)
17+
* **Podbean Integration** for direct podcast publishing
18+
* **Trending Topics Detection** using Perplexity API
19+
20+
## Prerequisites
21+
22+
* Node.js v16+ and npm/yarn
23+
* Python 3.10+ and pip
24+
* Redis server running (default on port 6380)
25+
* Perplexity API key, Podbean credentials
26+
27+
## Installation
28+
29+
```bash
30+
# Clone the repository
31+
git clone https://github.com/dineshkannan010/Ellipsis.git
32+
cd Ellipsis
33+
34+
# Backend setup
35+
cd backend
36+
python -m venv venv
37+
source venv/bin/activate # macOS/Linux
38+
pip install -r requirements.txt
39+
40+
# Install native packages
41+
pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
42+
pip install git+https://github.com/freddyaboulton/orpheus-cpp.git
43+
pip install huggingface_hub[hf_xet] hf_xet
44+
45+
# Frontend setup
46+
cd ../frontend
47+
npm install
48+
```
49+
50+
## Configuration
51+
52+
Create `backend/.env`:
53+
```ini
54+
REDIS_URL=redis://your-redis-host:6379
55+
PERPLEXITY_API_KEY=your_key_here
56+
PODBEAN_CLIENT_ID=...
57+
PODBEAN_CLIENT_SECRET=...
58+
```
59+
60+
Create `frontend/.env`:
61+
```ini
62+
REACT_APP_API_URL=http://your-backend-host:5000
63+
```
64+
65+
## Usage
66+
67+
1. **Start Redis Server**:
68+
```bash
69+
redis-server --port 6380
70+
```
71+
72+
2. **Launch Backend**:
73+
```bash
74+
cd backend
75+
python app.py
76+
```
77+
78+
3. **Launch Frontend**:
79+
```bash
80+
cd frontend
81+
npm run dev
82+
```
83+
84+
4. **Optional: Podbean Integration**:
85+
```bash
86+
cd backend/integrations/podbean_mcp
87+
pip install -e .
88+
python server.py
89+
python client.py server.py
90+
```
91+
92+
5. **Generate Content**: Enter a topic in the homepage textbox and hit Enter. Switch to `ContentGenerationView` to see live script & audio progress.
93+
94+
## Code Explanation
95+
96+
* **Backend**: Python Flask with Redis pub/sub, llama.cpp, and Orpheus TTS for audio generation
97+
* **Frontend**: React with Vite, Tailwind CSS, and Server-Sent Events for real-time updates
98+
* **AI Integration**: Perplexity API for content generation and trending topics detection
99+
* **Audio Processing**: Multi-speaker TTS with distinct voice personalities
100+
* **Content Evaluation**: Built-in pipelines for factual accuracy and legal compliance
101+
* **Podcast Publishing**: Direct integration with Podbean via MCP server
102+
103+
## Demo Video
104+
105+
<iframe
106+
className="w-full aspect-video rounded-xl"
107+
src="https://www.youtube.com/embed/XUPsSuCBTFw"
108+
title="YouTube video player"
109+
frameBorder="0"
110+
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
111+
allowFullScreen
112+
></iframe>
113+
114+
## Links
115+
116+
- [GitHub Repository](https://github.com/dineshkannan010/Ellipsis)
117+
- [Devpost Submission](https://devpost.com/software/ellipsis)

0 commit comments

Comments
 (0)