Commit 6086a5f8 authored by 吴春's avatar 吴春

1

parent 42b2f5ef
......@@ -35,7 +35,7 @@ namespace Edu.Model.Entity.AI
public string Charging { get; set; }
/// <summary>
/// token数量
/// token数量(回答)
/// </summary>
public string TokenNum { get; set; }
/// <summary>
......
......@@ -27,6 +27,7 @@ using System.IO.Compression;
using SharpCompress.Common;
using System.Collections;
using System.Reflection;
using System.Text;
namespace Edu.WebApi.Controllers.AI
{
......@@ -36,7 +37,9 @@ namespace Edu.WebApi.Controllers.AI
[EnableCors("AllowCors")]
public class AIStudentController : AppletBaseController
{
private static readonly string postUrl = "https://api.zhizengzeng.com/v1/chat/completions";
private const string user = "user";
private const string messages = "messages";
/// <summary>
/// AI供应商处理类
/// </summary>
......@@ -236,19 +239,6 @@ namespace Edu.WebApi.Controllers.AI
}
else if (supplierModel.SupplierType == Common.Enum.AI.SupplierTypeEnum.OpenAI)
{
string answer = string.Empty;
// 初始化客户端
var api = new OpenAIAPI(basicConfigureModel.ApiKey);
// // 调用GPT-3模型完成一段文本
var completionRequest = new CompletionRequest
{
Model = "gpt-4o-mini",
Prompt = keyWord,
MaxTokens = 4000,
};
int addId = aiModule.SetAIUseLogModule(userLogModel);
if (addId > 0)
......@@ -263,33 +253,101 @@ namespace Edu.WebApi.Controllers.AI
CompletionResultModel = "",
};
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, resultModel, Common.Config.JwtExpirTime);
var result = api.Completions.CreateCompletionAsync(completionRequest);
if (result != null)
PostAsync("sk-zk2ad4c7483a167ffcbb7246c4b551b02e967777cb2744fc", keyWord, addId);
return ApiResult.Success(data: new { result = resultModel, Id = addId });
}
}
return ApiResult.Failed("解析失败!");
}
static string ExtractContent(string jsonResponse)
{
try
string returnStr = "";
JObject json = JObject.Parse(jsonResponse);
returnStr = json["choices"][0]["message"]["content"].ToString();
return returnStr;
}
/// <summary>
/// 根据内容以及供应商获取ai内容
/// </summary>
/// <returns></returns>
[HttpPost]
public ApiResult GettestAIContentByKeyWord()
{
// PostAsync();
return ApiResult.Success();
}
public async Task PostAsync(string apiSecretKey, string keyWord, int addId)
{
var data = new JObject();
data[user] = "测试者";
// messages
var messageDatas = new JArray();
// 单个 message
var messageData = new JObject
{
["role"] = "user",
["content"] = keyWord
};
// 存入 message
messageDatas.Add(messageData);
// 配置内容
data[messages] = messageDatas;
// 编码 JSON
var jsonData = data.ToString();
var dataBytes = Encoding.UTF8.GetBytes(jsonData);
var returnModel = Cache.User.UserReidsCache.OpenAIGet(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId);
if (returnModel != null)
{
string completionResult = "";
if (result.Result != null)
using (HttpClient client = new HttpClient())
{
var requestContent = new ByteArrayContent(dataBytes);
requestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiSecretKey);
HttpResponseMessage response = await client.PostAsync(postUrl, requestContent);
if (response.IsSuccessStatusCode)
{
string receiveContent = await response.Content.ReadAsStringAsync();
returnModel.Status = 1;
completionResult = JsonHelper.Serialize(result.Result);
returnModel.CompletionResultModel = completionResult;
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, resultModel, Common.Config.JwtExpirTime);
}
}
returnModel.CompletionResultModel = receiveContent;
//更新数据库信息
var oldModel = aiModule.GetAIUseLogEntity(addId);
if ((oldModel?.ID ?? 0) > 0)
{
oldModel.ResultInfo = receiveContent;
try
{
JObject json = JObject.Parse(receiveContent);
string prompt_tokens = json["usage"]["prompt_tokens"].ToString();
string completion_tokens = json["usage"]["completion_tokens"].ToString();
var tokenNum = new
{
prompt_tokens,
completion_tokens,
};
oldModel.TokenNum = JsonHelper.Serialize(tokenNum);
}
catch (Exception ex)
{
Common.Plugin.LogHelper.Write(ex, "GetUserLoginInfo");
}
aiModule.SetAIUseLogModule(oldModel);
}
return ApiResult.Success(data: new { result = resultModel, Id = addId });
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, returnModel, Common.Config.JwtExpirTime);
}
else
{
returnModel.Status = 3;//失败了
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, returnModel, Common.Config.JwtExpirTime);
LogHelper.WriteInfo($"Error: {response.StatusCode}, {response.ReasonPhrase}");
}
}
return ApiResult.Failed("解析失败!");
}
}
/// <summary>
......@@ -310,12 +368,6 @@ namespace Edu.WebApi.Controllers.AI
{
return ApiResult.Failed("获取失败请重新调用");
}
else if (returnModel.Status == 1)
{
var model = aiModule.GetAIUseLogEntity(Id);
model.ResultInfo = returnModel.CompletionResultModel;
aiModule.SetAIUseLogModule(model);
}
return ApiResult.Success(data: returnModel);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment