| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222 |
- <?php
- class AIClientFactory
- {
- public static function create($model, $config, $systemPrompt, $message, $history = [])
- {
- $instance = new self(); // 或 new MyClass();
- if ($model == 'claude') {
- return $instance->Claude37ClientSendMessage($config, $systemPrompt, $message, $history);
- } elseif ($model == 'deepseek') {
- return $instance->DeepSeekClientSendMessage($config, $systemPrompt, $message, $history);
- }
- return ['success' => false, 'error' => 'Invalid model'];
- }
- /**
- * Send a message to the Claude API
- *
- * @param string $message The user message
- * @param array $history Previous conversation history
- * @return array The API response
- */
- private function Claude37ClientSendMessage($config, $systemPrompt, $message, $history = [])
- {
- // Format conversation history for Claude API
- //$messages = AIClientFactory::formatHistory($history);
- // Add the current user message
- $messages[] = [
- 'role' => 'user',
- 'content' => $message
- ];
- // Prepare request data
- $data = [
- 'model' => $config['model'],
- 'messages' => $messages,
- 'system' => $systemPrompt,
- 'max_tokens' => $config['max_tokens'],
- 'temperature' => $config['temperature'],
- 'top_p' => $config['top_p']
- ];
- // Prepare headers
- $headers = [
- 'Content-Type: application/json',
- 'x-api-key: ' . $config['api_key'],
- 'anthropic-version: 2023-06-01'
- ];
- try {
- // Make the request
- $response = $this->makeRequest($config['api_url'], $data, $headers);
- // Extract the assistant's message
- if (isset($response['content']) && !empty($response['content'])) {
- $content = '';
- foreach ($response['content'] as $part) {
- if ($part['type'] === 'text') {
- $content .= $part['text'];
- }
- }
- // Return formatted response
- return [
- 'success' => true,
- 'message' => $content,
- 'model' => 'claude',
- 'full_response' => $response,
- 'data'=>$data
- ];
- } else {
- throw new Exception('Invalid response format from Claude API');
- }
- } catch (Exception $e) {
- // Log and return error
- error_log('Claude 3.7', $e->getMessage());
- return [
- 'success' => false,
- 'error' => $e->getMessage(),
- 'model' => 'claude'
- ];
- }
- }
- /**
- * Send a message to the DeepSeek API
- *
- * @param string $message The user message
- * @param array $history Previous conversation history
- * @return array The API response
- */
- private function DeepSeekClientSendMessage($config, $systemPrompt, $message, $history = [])
- {
- // Format conversation history for DeepSeek API
- //$messages = $this->formatHistory($history);
- $messages = [];
- // Add system message at the beginning
- $messages = array_merge([
- ['role' => 'system', 'content' => $systemPrompt]
- ], $messages);
- // Add the current user message
- $messages[] = [
- 'role' => 'user',
- 'content' => $message
- ];
- // Prepare request data
- $data = [
- 'model' => $config['model'],
- 'messages' => $messages,
- 'max_tokens' => $config['max_tokens'],
- 'temperature' => $config['temperature'],
- 'top_p' => $config['top_p']
- ];
- // Prepare headers
- $headers = [
- 'Content-Type: application/json',
- 'Authorization: Bearer ' . $config['api_key']
- ];
- try {
- // Make the request
- $response = $this->makeRequest($config['api_url'], $data, $headers);
- // Extract the assistant's message
- if (isset($response['choices'][0]['message']['content'])) {
- $content = $response['choices'][0]['message']['content'];
- // Return formatted response
- return [
- 'success' => true,
- 'message' => $content,
- 'model' => 'deepseek',
- 'full_response' => $response,
- 'data'=>$data
- ];
- } else {
- throw new Exception('Invalid response format from DeepSeek API');
- }
- } catch (Exception $e) {
- // Log and return error
- error_log('DeepSeek:'.$e->getMessage());
- return [
- 'success' => false,
- 'error' => $e->getMessage(),
- 'model' => 'deepseek'
- ];
- }
- }
- private function makeRequest($url, $data, $headers = [])
- {
- $ch = curl_init($url);
- // Set common cURL options
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- // Send the request
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- // Handle errors
- if ($error) {
- error_log("cURL error: $url, $error");
- throw new Exception("API request failed: $error");
- }
- // Decode response
- $responseData = json_decode($response, true);
- if ($httpCode >= 400) {
- $errorMsg = isset($responseData['error']['message'])
- ? $responseData['error']['message']
- : "HTTP error code: $httpCode";
- error_log($url, $errorMsg, $responseData);
- throw new Exception("API error: $errorMsg");
- }
- return $responseData;
- }
- /* Format conversation history for Claude API
- *
- * @param array $history Conversation history
- * @return array Formatted history
- */
- private function formatHistory($history)
- {
- $messages = [];
- foreach ($history as $item) {
- if ($item['role'] === 'user') {
- $messages[] = [
- 'role' => 'user',
- 'content' => $item['content']
- ];
- } elseif ($item['role'] === 'assistant') {
- $messages[] = [
- 'role' => 'assistant',
- 'content' => $item['content']
- ];
- }
- }
- return $messages;
- }
- }
|