Skip to content

Instantly share code, notes, and snippets.

@agilous
Created January 23, 2025 05:00
Show Gist options
  • Save agilous/d004d08655a4bf2e2cdf5b2dd4080fb4 to your computer and use it in GitHub Desktop.
Save agilous/d004d08655a4bf2e2cdf5b2dd4080fb4 to your computer and use it in GitHub Desktop.
Perplexity Sonar Play
#! /usr/bin/env ruby
require 'httparty'
require 'json'
require 'pry'
class PerplexityClient
include HTTParty
base_uri 'https://api.perplexity.ai'
API_KEY = "YOULL_HAVE_TO_GET_ONE_OF_YOUR_OWN"
headers 'Authorization' => "Bearer #{API_KEY}"
def chat_completion(messages)
options = {
body: {
model: "sonar-pro",
messages: messages,
stream: false
}.to_json,
headers: { 'Content-Type' => 'application/json' }
}
self.class.post('/chat/completions', options)
end
end
client = PerplexityClient.new
messages = [
{
role: "system",
content: <<~SYSTEM_PROMPT
You are an astrophysicist.
SYSTEM_PROMPT
},
{
role: "user",
content: <<~USER_PROMPT
How many stars are in our galaxy?
USER_PROMPT
}
]
response = client.chat_completion(messages)
response["choices"].each { |choice| puts choice["message"]["content"] }
puts "\n\n"
response["citations"].each_with_index { |citation, index| puts "[#{index + 1}] #{citation}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment