Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

Answers

Greg Priday edited this page Jul 7, 2021 · 2 revisions

Answers API

Given a question, a set of documents, and some examples, the API generates an answer to the question based on the information in the set of documents. This is useful for question-answering applications on sources of truth, like company documentation or a knowledge base.

https://beta.openai.com/docs/api-reference/answers

The answers API lets us guide GPT-3 with some data, and it gives us answers.

Using a Data Array

use SiteOrigin\OpenAI\Client;
use SiteOrigin\OpenAI\Engines;

$client = new Client($_ENV['OPENAI_API_KEY']);

$documents = [
    "Puppy named Bailey is happy.",
    "Puppy named Bella is sad.",
    "Puppy named Molly is hungry.",
];

$result = $client->answers(Engines::CURIE)->create(
    'Which puppy is happy?',
    $documents,
    'In 2017, U.S. life expectancy was 78.6 years.',
    [["What is human life expectancy in the United States?","78 years."]],
    ["max_tokens" => 5, "stop" => ["\n", "<|endoftext|>"] ]
);

This gives us the result:

(object) array(
   'answers' => 
  array (
    0 => 'Bailey.',
  ),
   'completion' => 'cmpl-3J04Z7fG2x5DYSnoPvKAHfVbhrZ1B',
   'model' => 'curie:2020-05-03',
   'object' => 'answer',
   'search_model' => 'ada',
   'selected_documents' => 
  array (
    0 => 
    (object) array(
       'document' => 0,
       'text' => 'Puppy named Bailey is happy. ',
    ),
    1 => 
    (object) array(
       'document' => 2,
       'text' => 'Puppy named Molly is hungry. ',
    ),
    2 => 
    (object) array(
       'document' => 1,
       'text' => 'Puppy named Bella is sad. ',
    ),
  ),
);

You can also tweak values like temperature in the input to come up with more creative results. Setting n will increase the number of answers.

Using a File ID

You can also provide a file ID instead of a data array. This allows you to use a much larger data set of up to 150mb, based on the current OpenAI limitations.

use SiteOrigin\OpenAI\Client;
use SiteOrigin\OpenAI\Engines;

$client = new Client($_ENV['OPENAI_API_KEY']);
$documents = [
    ["text" => "Puppy named Bailey is happy."],
    ["text" => "Puppy named Bella is sad."],
    ["text" => "Puppy named Molly is hungry."],
];

$file = $client->files()->create('data.json', $documents, 'answers');

// Wait for the file to process
$result = $client->answers(Engines::CURIE)->create(
    'Which puppy is happy?',
    $file->id,
    'In 2017, U.S. life expectancy was 78.6 years.',
    [["What is human life expectancy in the United States?","78 years."]],
    ["max_tokens" => 5, "stop" => ["\n", "<|endoftext|>"] ]
);
Clone this wiki locally