Skip to content

Instantly share code, notes, and snippets.

@whoisthisstud
Created January 11, 2023 17:28
Show Gist options
  • Select an option

  • Save whoisthisstud/3f1d226f125cc33dbe2804e433a8ba85 to your computer and use it in GitHub Desktop.

Select an option

Save whoisthisstud/3f1d226f125cc33dbe2804e433a8ba85 to your computer and use it in GitHub Desktop.
ChatGPT written Laravel Service class for interacting with ChatGPT's API.
You will need to add your API key and the base URL of the API to the configuration file of your application (config/services.php) in order to use this service class.
You can use this service class to generate text by calling the generateText method and passing in a prompt as an argument.
You can also modify the model, token, stop and temperature and other parameters based on your requirements.
Note that this is an example, that you should adapt and test to your specific case and use case.
This code was written by ChatGPT!
<?php
namespace App\Services;
use GuzzleHttp\Client;
class ChatGPTService
{
private $apiKey;
private $baseUrl;
public function __construct()
{
$this->apiKey = config('services.chatgpt.api_key');
$this->baseUrl = config('services.chatgpt.base_url');
}
public function generateText($prompt)
{
$client = new Client([
'base_uri' => $this->baseUrl,
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->apiKey,
],
]);
$response = $client->post('/v1/models/davinci-codex/completions', [
'json' => [
'prompt' => $prompt,
'max_tokens' => 100,
'stop' => '\n',
'temperature' => 0.5,
],
]);
$result = json_decode($response->getBody(), true);
return $result['choices'][0]['text'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment