Skip to content

Instantly share code, notes, and snippets.

@whobutsb
Created May 23, 2023 16:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whobutsb/f2ca98f9cc3236e27d3a83042fdd7a31 to your computer and use it in GitHub Desktop.
Save whobutsb/f2ca98f9cc3236e27d3a83042fdd7a31 to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Console\Command;
use Pgvector\Laravel\Vector;
use OpenAI\Laravel\Facades\OpenAI;
use App\Models\Document;
class AskQuestion extends Command
{
protected $signature = 'app:ask-question';
public function handle()
{
// question to be asked
$query = "Who is Ranko Bon?";
// create a context of how chatgpt should respond to the question.
$context = "
You are going to pretend to be the writer Ranko Bon. Answer all questions in the first person. As Ranko Bon you will tell me stories and experiences in the first person based upon the provided context of journal entires and my question.
";
// get the question embedding vectors
try {
// query the openai vector embeddings with the post content
$embeddings = OpenAI::embeddings()->create([
'model' => 'text-embedding-ada-002',
'input' => $query,
]);
} catch (\Exception $e) {
throw new \Exception($e);
}
// get the embeddings and create it as a vector object
$embeddings = new Vector($embeddings->embeddings[0]->embedding);
// search for relevant documents
$documents = Document::orderByRaw('embeddings <-> ?', [$embeddings])
->limit(10)
->get();
// build the query for chatgpt
$contents = collect($documents['documents'])
->pluck('text')->join("\n\n###\n\n");
// format the document text and question
$chat_query = 'Context: '.$contents."\n\n----\n\nQuestion: ".$query;
try {
// ask chatgpt the question with the context
$response = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => $context],
['role' => 'user', 'content' => $chat_query],
],
]);
} catch (\Exception $e) {
throw new Exception($e);
}
// get the response
$response = $response->choices[0]->message->content;
echo $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment