| Conditions | 3 |
| Paths | 7 |
| Total Lines | 54 |
| Code Lines | 37 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 69 | public function chat( |
||
| 70 | array $messages, |
||
| 71 | ?string $model = null, |
||
| 72 | ?array $options = null |
||
| 73 | ): array { |
||
| 74 | if (!$this->isEnabled()) { |
||
| 75 | return ['success' => false, 'error' => 'Gemini adapter not enabled']; |
||
| 76 | } |
||
| 77 | |||
| 78 | $model ??= $this->getDefaultModel(); |
||
| 79 | $options ??= []; |
||
| 80 | |||
| 81 | // Compress messages |
||
| 82 | $compressedMessages = array_map(fn ($msg) => [ |
||
| 83 | 'role' => $msg['role'], |
||
| 84 | 'parts' => [['text' => $this->compressMessage($msg['content'])]], |
||
| 85 | ], $messages); |
||
| 86 | |||
| 87 | $payload = array_merge([ |
||
| 88 | 'contents' => $compressedMessages, |
||
| 89 | ], $options); |
||
| 90 | |||
| 91 | try { |
||
| 92 | $apiKey = config('laravel-toon.adapters.gemini.api_key'); |
||
| 93 | $response = Http::baseUrl('https://generativelanguage.googleapis.com/v1beta/models') |
||
| 94 | ->withQueryParameters(['key' => $apiKey]) |
||
| 95 | ->post("/{$model}:generateContent", $payload) |
||
| 96 | ->throw() |
||
| 97 | ->json(); |
||
| 98 | |||
| 99 | $originalTokens = array_sum(array_map( |
||
| 100 | fn ($msg) => $this->tokenAnalyzer->estimate($msg['content']), |
||
| 101 | $messages |
||
| 102 | )); |
||
| 103 | |||
| 104 | $compressedTokens = array_sum(array_map( |
||
| 105 | fn ($msg) => $this->tokenAnalyzer->estimate($msg['content']), |
||
| 106 | $messages |
||
| 107 | )); |
||
| 108 | |||
| 109 | return [ |
||
| 110 | 'success' => true, |
||
| 111 | 'adapter' => 'gemini', |
||
| 112 | 'model' => $model, |
||
| 113 | 'messages_count' => count($messages), |
||
| 114 | 'original_tokens' => $originalTokens, |
||
| 115 | 'compressed_tokens' => $compressedTokens, |
||
| 116 | 'tokens_saved' => $originalTokens - $compressedTokens, |
||
| 117 | 'response' => $response, |
||
| 118 | ]; |
||
| 119 | } catch (\Exception $e) { |
||
| 120 | return [ |
||
| 121 | 'success' => false, |
||
| 122 | 'error' => $e->getMessage(), |
||
| 123 | ]; |
||
| 141 |