Ask Your Question
4

How can I use PHP to retrieve data stream from the OpenAI GPT-3 API?

asked 2022-06-19 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-07-19 19:00:00 +0000

ladyg gravatar image

To retrieve data stream from the OpenAI GPT-3 API using PHP, you can use the following steps:

  1. Sign up for an OpenAI account, create an API key and add it to your account.

  2. Install the Guzzle HTTP client library for PHP.

  3. Use the following code to initialize a Guzzle client and send a request to the GPT-3 API endpoint:

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://api.openai.com/v1/',
    'headers' => [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer <your-api-key>'
    ]
]);

$response = $client->request('POST', 'engines/davinci-codex/completions', [
    'json' => [
        'prompt' => 'Code a function that returns the sum of two numbers:',
        'max_tokens' => 2048,
        'temperature' => 0.5
    ]
]);

$dataStream = $response->getBody()->getContents();
  1. In this example, we are using the GPT-3 Codex model to generate code based on a prompt. We send a POST request to the engines/davinci-codex/completions endpoint with a JSON payload that includes the prompt, max_tokens and temperature parameters.

  2. The response from the API is a JSON object that includes the generated code. We use the getBody() method to retrieve the response body as a stream of data and the getContents() method to convert the stream to a string.

  3. You can then use the generated code for further processing, such as saving it to a file or executing it within your application.

Note: The OpenAI API is a paid service and requires a valid API key to access. Also, make sure to read the documentation to understand the limitations and usage guidelines for the API.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-19 11:00:00 +0000

Seen: 14 times

Last updated: Jul 19 '22