AIClientFactory.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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['max_tokens'],
  36. 'temperature' => $config['temperature'],
  37. 'top_p' => $config['top_p']
  38. ];
  39. // Prepare headers
  40. $headers = [
  41. 'Content-Type: application/json',
  42. 'x-api-key: ' . $config['api_key'],
  43. 'anthropic-version: 2023-06-01'
  44. ];
  45. try {
  46. // Make the request
  47. $response = $this->makeRequest($config['api_url'], $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. 'data'=>$data
  63. ];
  64. } else {
  65. throw new Exception('Invalid response format from Claude API');
  66. }
  67. } catch (Exception $e) {
  68. // Log and return error
  69. error_log('Claude 3.7', $e->getMessage());
  70. return [
  71. 'success' => false,
  72. 'error' => $e->getMessage(),
  73. 'model' => 'claude'
  74. ];
  75. }
  76. }
  77. /**
  78. * Send a message to the DeepSeek API
  79. *
  80. * @param string $message The user message
  81. * @param array $history Previous conversation history
  82. * @return array The API response
  83. */
  84. private function DeepSeekClientSendMessage($config, $systemPrompt, $message, $history = [])
  85. {
  86. // Format conversation history for DeepSeek API
  87. //$messages = $this->formatHistory($history);
  88. $messages = [];
  89. // Add system message at the beginning
  90. $messages = array_merge([
  91. ['role' => 'system', 'content' => $systemPrompt]
  92. ], $messages);
  93. // Add the current user message
  94. $messages[] = [
  95. 'role' => 'user',
  96. 'content' => $message
  97. ];
  98. // Prepare request data
  99. $data = [
  100. 'model' => $config['model'],
  101. 'messages' => $messages,
  102. 'max_tokens' => $config['max_tokens'],
  103. 'temperature' => $config['temperature'],
  104. 'top_p' => $config['top_p']
  105. ];
  106. // Prepare headers
  107. $headers = [
  108. 'Content-Type: application/json',
  109. 'Authorization: Bearer ' . $config['api_key']
  110. ];
  111. try {
  112. // Make the request
  113. $response = $this->makeRequest($config['api_url'], $data, $headers);
  114. // Extract the assistant's message
  115. if (isset($response['choices'][0]['message']['content'])) {
  116. $content = $response['choices'][0]['message']['content'];
  117. // Return formatted response
  118. return [
  119. 'success' => true,
  120. 'message' => $content,
  121. 'model' => 'deepseek',
  122. 'full_response' => $response,
  123. 'data'=>$data
  124. ];
  125. } else {
  126. throw new Exception('Invalid response format from DeepSeek API');
  127. }
  128. } catch (Exception $e) {
  129. // Log and return error
  130. error_log('DeepSeek', $e->getMessage());
  131. return [
  132. 'success' => false,
  133. 'error' => $e->getMessage(),
  134. 'model' => 'deepseek'
  135. ];
  136. }
  137. }
  138. private function makeRequest($url, $data, $headers = [])
  139. {
  140. $ch = curl_init($url);
  141. // Set common cURL options
  142. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  143. curl_setopt($ch, CURLOPT_POST, true);
  144. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  145. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  146. // Send the request
  147. $response = curl_exec($ch);
  148. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  149. $error = curl_error($ch);
  150. curl_close($ch);
  151. // Handle errors
  152. if ($error) {
  153. error_log("cURL error: $url, $error");
  154. throw new Exception("API request failed: $error");
  155. }
  156. // Decode response
  157. $responseData = json_decode($response, true);
  158. if ($httpCode >= 400) {
  159. $errorMsg = isset($responseData['error']['message'])
  160. ? $responseData['error']['message']
  161. : "HTTP error code: $httpCode";
  162. error_log($url, $errorMsg, $responseData);
  163. throw new Exception("API error: $errorMsg");
  164. }
  165. return $responseData;
  166. }
  167. /* Format conversation history for Claude API
  168. *
  169. * @param array $history Conversation history
  170. * @return array Formatted history
  171. */
  172. private function formatHistory($history)
  173. {
  174. $messages = [];
  175. foreach ($history as $item) {
  176. if ($item['role'] === 'user') {
  177. $messages[] = [
  178. 'role' => 'user',
  179. 'content' => $item['content']
  180. ];
  181. } elseif ($item['role'] === 'assistant') {
  182. $messages[] = [
  183. 'role' => 'assistant',
  184. 'content' => $item['content']
  185. ];
  186. }
  187. }
  188. return $messages;
  189. }
  190. }