c5_labsci/web/admin/demo/dyn/openai.php

68 lines
2.1 KiB
PHP

<?php
namespace web\admin\demo\dyn;
class openai {
public static function sse_llm($senddata, $sendevent) {
global $db;
$rsuser = verifyfast();
$post = new \ciy\post();
$messages = $post->get('messages');
$csql = new \ciy\sql('zc_ai_key');
$csql->where('id', 1);
$aikeyrow = $db->getone($csql);
if(!is_array($aikeyrow))
return $senddata('AI密钥不存在');
$openai = new \ciy\openai($aikeyrow);
$openai->debug();
$retai = $openai->chat($messages, function($data) {
echo $data;
ob_flush();
flush();
});
if(is_string($retai))
$senddata($retai);
}
public static function sse_llmori($senddata, $sendevent) {
$rsuser = verifyfast();
$post = new \ciy\post();
$prompt = $post->get('prompt');
if (!$prompt)
return errjson('请输入提示词');
$apiKey = 'sk-f73708'; // 替换为你的API密钥
$model = "deepseek-chat";
$url = 'https://api.deepseek.com/chat/completions';
// 构建请求体
$data = [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
'stream' => true,
'temperature' => 0.7,
];
// 初始化cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) {
echo $data;
ob_flush();
flush();
return strlen($data);
});
curl_exec($ch);
if (curl_errno($ch))
$senddata('错误: ' . curl_error($ch));
curl_close($ch);
}
}