diff --git a/README.md b/README.md index 4c5b251..370f9f5 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,26 @@ $classification = $open_ai->classification([ ]); ``` +## Chat + +Given a chat conversation, the model will return a chat completion response. + + ```php +$complete = $open_ai->chat([ + 'model' => 'gpt-3.5-turbo', + 'messages' => [ + [ + "role" => "user", + "content" => "Hello!" + ] + ], + 'temperature' => 1.0, + 'max_tokens' => 4096, + 'frequency_penalty' => 0, + 'presence_penalty' => 0, +]); +``` + ## Content Moderations Given a input text, outputs if the model classifies it as violating OpenAI's content policy. diff --git a/src/OpenAi.php b/src/OpenAi.php index 6ed4664..fa7f17a 100644 --- a/src/OpenAi.php +++ b/src/OpenAi.php @@ -8,6 +8,7 @@ class OpenAi { private string $engine = "davinci"; private string $model = "text-davinci-002"; + private string $chatModel = "gpt-3.5-turbo"; private array $headers; private array $contentTypes; private int $timeout = 0; @@ -200,6 +201,32 @@ public function moderation($opts) return $this->sendRequest($url, 'POST', $opts); } + + /** + * @param $opts + * @param null $stream + * @return bool|string + * @throws Exception + */ + public function chat($opts, $stream = null) + { + if ($stream != null && array_key_exists('stream', $opts)) { + if (! $opts['stream']) { + throw new Exception( + 'Please provide a stream function. Check https://github.com/orhanerday/open-ai#stream-example for an example.' + ); + } + + $this->stream_method = $stream; + } + + $opts['model'] = $opts['model'] ?? $this->chatModel; + $url = Url::chatUrl(); + $this->baseUrl($url); + + return $this->sendRequest($url, 'POST', $opts); + } + /** * @param $opts * @return bool|string diff --git a/src/Url.php b/src/Url.php index aa86c8d..903971b 100644 --- a/src/Url.php +++ b/src/Url.php @@ -133,4 +133,13 @@ public static function embeddings(): string { return self::OPEN_AI_URL . "/embeddings"; } + + /** + * @param + * @return string + */ + public static function chatUrl(): string + { + return self::OPEN_AI_URL . "/chat/completions"; + } } diff --git a/tests/OpenAiTest.php b/tests/OpenAiTest.php index 22b83b8..2e8db54 100644 --- a/tests/OpenAiTest.php +++ b/tests/OpenAiTest.php @@ -227,3 +227,22 @@ $this->assertStringContainsString('data', $result); })->group('working'); + + +it('should handle simple chat completion using the new endpoint', function () use ($open_ai) { + $result = $open_ai->chat([ + 'model' => 'gpt-3.5-turbo', + 'messages' => [ + [ + "role" => "user", + "content" => "Hello!" + ] + ], + 'temperature' => 0.9, + "max_tokens" => 150, + "frequency_penalty" => 0, + "presence_penalty" => 0, + ]); + + $this->assertStringContainsString('text', $result); +})->group('working');