AIClientFactory.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. class AIClientFactory
  3. {
  4. public static function create($model, $config, $systemPrompt, $message, $history = [])
  5. {
  6. $instance = new self(); // 或 new MyClass();
  7. if ($model == 'claude') {
  8. return $instance->Claude37ClientSendMessage($config, $systemPrompt, $message, $history);
  9. } elseif ($model == 'deepseek') {
  10. return $instance->DeepSeekClientSendMessage($config, $systemPrompt, $message, $history);
  11. }
  12. return ['success' => false, 'error' => 'Invalid model'];
  13. }
  14. /**
  15. * Send a message to the Claude API
  16. *
  17. * @param string $message The user message
  18. * @param array $history Previous conversation history
  19. * @return array The API response
  20. */
  21. private function Claude37ClientSendMessage($config, $systemPrompt, $message, $history = [])
  22. {
  23. // Format conversation history for Claude API
  24. //$messages = AIClientFactory::formatHistory($history);
  25. // Add the current user message
  26. $messages[] = [
  27. 'role' => 'user',
  28. 'content' => $message
  29. ];
  30. // Prepare request data
  31. $data = [
  32. 'model' => $config['model'],
  33. 'messages' => $messages,
  34. 'system' => $systemPrompt,
  35. 'max_tokens' => $config['maxTokens'],
  36. 'temperature' => $config['temperature'],
  37. 'top_p' => $config['topP']
  38. ];
  39. // Prepare headers
  40. $headers = [
  41. 'Content-Type: application/json',
  42. 'x-api-key: ' . $config['apiKey'],
  43. 'anthropic-version: 2023-06-01'
  44. ];
  45. try {
  46. // Make the request
  47. $response = $this->makeRequest($config['apiUrl'], $data, $headers);
  48. // Extract the assistant's message
  49. if (isset($response['content']) && !empty($response['content'])) {
  50. $content = '';
  51. foreach ($response['content'] as $part) {
  52. if ($part['type'] === 'text') {
  53. $content .= $part['text'];
  54. }
  55. }
  56. // Return formatted response
  57. return [
  58. 'success' => true,
  59. 'message' => $content,
  60. 'model' => 'claude',
  61. 'full_response' => $response
  62. ];
  63. } else {
  64. throw new Exception('Invalid response format from Claude API');
  65. }
  66. } catch (Exception $e) {
  67. // Log and return error
  68. error_log('Claude 3.7', $e->getMessage());
  69. return [
  70. 'success' => false,
  71. 'error' => $e->getMessage(),
  72. 'model' => 'claude'
  73. ];
  74. }
  75. }
  76. /**
  77. * Send a message to the DeepSeek API
  78. *
  79. * @param string $message The user message
  80. * @param array $history Previous conversation history
  81. * @return array The API response
  82. */
  83. private function DeepSeekClientSendMessage($config, $systemPrompt, $message, $history = [])
  84. {
  85. // Format conversation history for DeepSeek API
  86. //$messages = $this->formatHistory($history);
  87. $messages = [];
  88. // Add system message at the beginning
  89. $messages = array_merge([
  90. ['role' => 'system', 'content' => $systemPrompt]
  91. ], $messages);
  92. // Add the current user message
  93. $messages[] = [
  94. 'role' => 'user',
  95. 'content' => $message
  96. ];
  97. // Prepare request data
  98. $data = [
  99. 'model' => $config['model'],
  100. 'messages' => $messages,
  101. 'max_tokens' => $config['maxTokens'],
  102. 'temperature' => $config['temperature'],
  103. 'top_p' => $config['topP']
  104. ];
  105. // Prepare headers
  106. $headers = [
  107. 'Content-Type: application/json',
  108. 'Authorization: Bearer ' . $config['apiKey']
  109. ];
  110. try {
  111. // Make the request
  112. $response = $this->makeRequest($config['apiUrl'], $data, $headers);
  113. // Extract the assistant's message
  114. if (isset($response['choices'][0]['message']['content'])) {
  115. $content = $response['choices'][0]['message']['content'];
  116. // Return formatted response
  117. return [
  118. 'success' => true,
  119. 'message' => $content,
  120. 'model' => 'deepseek',
  121. 'full_response' => $response
  122. ];
  123. } else {
  124. throw new Exception('Invalid response format from DeepSeek API');
  125. }
  126. } catch (Exception $e) {
  127. // Log and return error
  128. error_log('DeepSeek', $e->getMessage());
  129. return [
  130. 'success' => false,
  131. 'error' => $e->getMessage(),
  132. 'model' => 'deepseek'
  133. ];
  134. }
  135. }
  136. private function makeRequest($url, $data, $headers = [])
  137. {
  138. $ch = curl_init($url);
  139. // Set common cURL options
  140. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  141. curl_setopt($ch, CURLOPT_POST, true);
  142. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  143. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  144. // Send the request
  145. $response = curl_exec($ch);
  146. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  147. $error = curl_error($ch);
  148. curl_close($ch);
  149. // Handle errors
  150. if ($error) {
  151. error_log("cURL error: $url, $error");
  152. throw new Exception("API request failed: $error");
  153. }
  154. // Decode response
  155. $responseData = json_decode($response, true);
  156. if ($httpCode >= 400) {
  157. $errorMsg = isset($responseData['error']['message'])
  158. ? $responseData['error']['message']
  159. : "HTTP error code: $httpCode";
  160. error_log($url, $errorMsg, $responseData);
  161. throw new Exception("API error: $errorMsg");
  162. }
  163. return $responseData;
  164. }
  165. /* Format conversation history for Claude API
  166. *
  167. * @param array $history Conversation history
  168. * @return array Formatted history
  169. */
  170. private function formatHistory($history)
  171. {
  172. $messages = [];
  173. foreach ($history as $item) {
  174. if ($item['role'] === 'user') {
  175. $messages[] = [
  176. 'role' => 'user',
  177. 'content' => $item['content']
  178. ];
  179. } elseif ($item['role'] === 'assistant') {
  180. $messages[] = [
  181. 'role' => 'assistant',
  182. 'content' => $item['content']
  183. ];
  184. }
  185. }
  186. return $messages;
  187. }
  188. }