I love me some Laravel (if you couldn’t tell) and recently I was messing around with ChatGPT. The future of programming looks like this.
ChatGPT Prompt
Generate a Laravel Service class for interfacing with ChatGPT
ChatGPT’s Response
Here’s an example of a Laravel service class for interfacing with ChatGPT:
<?php namespace App\Services; use OpenAI\OpenAI; use OpenAI\ApiException; class ChatGPTService { private $openai; public function __construct() { $this->openai = new OpenAI(env('OPENAI_API_KEY')); } public function generateResponse($prompt, $model, $temperature, $maxTokens) { try { $response = $this->openai->completions([ 'engine' => $model, 'prompt' => $prompt, 'temperature' => $floatval($temperature), 'max_tokens' => intval($maxTokens) ]); return $response['choices'][0]['text']; } catch (ApiException $e) { return "Error: " . $e->getMessage(); } } }
This service class uses the OpenAI PHP client library to communicate with the ChatGPT API. The generateResponse
method takes in the prompt, model, temperature, and maxTokens as parameters and returns the generated response. If an error occurs during the API request, the method will return an error message.
To use this service class in your Laravel application, you can add it to the app/Services
directory and then inject it into your controllers or other services as needed.
ChatGPT Prompt
Generate a controller that uses this service
ChatGPT’s Response
Sure! Here’s an example of a Laravel controller that uses the ChatGPTService to generate responses:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\ChatGPTService; class ChatController extends Controller { private $chatGPTService; public function __construct(ChatGPTService $chatGPTService) { $this->chatGPTService = $chatGPTService; } public function generateResponse(Request $request) { $validatedData = $request->validate([ 'prompt' => 'required|string', 'model' => 'required|string', 'temperature' => 'required|numeric', 'max_tokens' => 'required|integer', ]); $prompt = $validatedData['prompt']; $model = $validatedData['model']; $temperature = $validatedData['temperature']; $maxTokens = $validatedData['max_tokens']; $response = $this->chatGPTService->generateResponse($prompt, $model, $temperature, $maxTokens); return response()->json([ 'response' => $response, ]); } }
This controller has a single action, generateResponse
, that accepts a POST request with a JSON payload containing the prompt
, model
, temperature
, and max_tokens
parameters. The controller uses the ChatGPTService
to generate a response based on the provided parameters and returns the response as a JSON object.
To use this controller in your Laravel application, you can add it to the app/Http/Controllers
directory and define a route that points to the generateResponse
action. For example:
Route::post('/chat', [\App\Http\Controllers\ChatController::class, 'generateResponse']);
This route would handle POST requests to /chat
and pass them to the generateResponse
action in the ChatController
.
ChatGPT Prompt
Create Laravel PHP unit tests for this service and controller
ChatGPT’s Response
Certainly! Here are some examples of Laravel PHP unit tests for the ChatGPTService
and ChatController
:
<?php namespace Tests\Unit; use Tests\TestCase; use App\Services\ChatGPTService; class ChatGPTServiceTest extends TestCase { private $chatGPTService; public function setUp(): void { parent::setUp(); $this->chatGPTService = new ChatGPTService(); } public function testGenerateResponse() { $prompt = "Hello, ChatGPT!"; $model = "text-davinci-002"; $temperature = 0.7; $maxTokens = 50; $response = $this->chatGPTService->generateResponse($prompt, $model, $temperature, $maxTokens); $this->assertIsString($response); $this->assertNotEmpty($response); } }
This unit test for the ChatGPTService
tests the generateResponse
method with a set of input parameters and asserts that the output is a non-empty string.
<?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; use App\Services\ChatGPTService; class ChatControllerTest extends TestCase { private $chatGPTService; public function setUp(): void { parent::setUp(); $this->chatGPTService = $this->mock(ChatGPTService::class); } public function testGenerateResponse() { $responseText = "Hello, world!"; $this->chatGPTService->shouldReceive('generateResponse')->once()->andReturn($responseText); $response = $this->postJson('/chat', [ 'prompt' => 'Hello, ChatGPT!', 'model' => 'text-davinci-002', 'temperature' => 0.7, 'max_tokens' => 50, ]); $response->assertStatus(200); $response->assertJson(['response' => $responseText]); } }
This unit test for the ChatController
tests the generateResponse
action by mocking the ChatGPTService
and asserting that the response status is 200 and that the response JSON contains the expected response
value.
Note that you may need to update the test data to match your specific use case. Also, make sure to run these tests using a testing environment and not your production environment.
Discover more from AJB Blog
Subscribe to get the latest posts sent to your email.