AIClientFactory.php 7.3 KB

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