Skip to content

Instantly share code, notes, and snippets.

Created May 23, 2023 16:13
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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])
// build the query for chatgpt
$contents = collect($documents['documents'])
// 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