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

1

parent 42b2f5ef
...@@ -35,7 +35,7 @@ namespace Edu.Model.Entity.AI ...@@ -35,7 +35,7 @@ namespace Edu.Model.Entity.AI
public string Charging { get; set; } public string Charging { get; set; }
/// <summary> /// <summary>
/// token数量 /// token数量(回答)
/// </summary> /// </summary>
public string TokenNum { get; set; } public string TokenNum { get; set; }
/// <summary> /// <summary>
......
...@@ -27,6 +27,7 @@ using System.IO.Compression; ...@@ -27,6 +27,7 @@ using System.IO.Compression;
using SharpCompress.Common; using SharpCompress.Common;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Text;
namespace Edu.WebApi.Controllers.AI namespace Edu.WebApi.Controllers.AI
{ {
...@@ -36,7 +37,9 @@ namespace Edu.WebApi.Controllers.AI ...@@ -36,7 +37,9 @@ namespace Edu.WebApi.Controllers.AI
[EnableCors("AllowCors")] [EnableCors("AllowCors")]
public class AIStudentController : AppletBaseController 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> /// <summary>
/// AI供应商处理类 /// AI供应商处理类
/// </summary> /// </summary>
...@@ -236,20 +239,7 @@ namespace Edu.WebApi.Controllers.AI ...@@ -236,20 +239,7 @@ namespace Edu.WebApi.Controllers.AI
} }
else if (supplierModel.SupplierType == Common.Enum.AI.SupplierTypeEnum.OpenAI) 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); int addId = aiModule.SetAIUseLogModule(userLogModel);
if (addId > 0) if (addId > 0)
{ {
...@@ -263,33 +253,101 @@ namespace Edu.WebApi.Controllers.AI ...@@ -263,33 +253,101 @@ namespace Edu.WebApi.Controllers.AI
CompletionResultModel = "", CompletionResultModel = "",
}; };
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, resultModel, Common.Config.JwtExpirTime); Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, resultModel, Common.Config.JwtExpirTime);
var result = api.Completions.CreateCompletionAsync(completionRequest); PostAsync("sk-zk2ad4c7483a167ffcbb7246c4b551b02e967777cb2744fc", keyWord, addId);
if (result != null) return ApiResult.Success(data: new { result = resultModel, Id = addId });
}
}
return ApiResult.Failed("解析失败!");
}
static string ExtractContent(string jsonResponse)
{
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)
{
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)
{ {
try string receiveContent = await response.Content.ReadAsStringAsync();
returnModel.Status = 1;
returnModel.CompletionResultModel = receiveContent;
//更新数据库信息
var oldModel = aiModule.GetAIUseLogEntity(addId);
if ((oldModel?.ID ?? 0) > 0)
{ {
var returnModel = Cache.User.UserReidsCache.OpenAIGet(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId); oldModel.ResultInfo = receiveContent;
if (returnModel != null)
try
{ {
string completionResult = ""; JObject json = JObject.Parse(receiveContent);
if (result.Result != null) string prompt_tokens = json["usage"]["prompt_tokens"].ToString();
string completion_tokens = json["usage"]["completion_tokens"].ToString();
var tokenNum = new
{ {
returnModel.Status = 1; prompt_tokens,
completionResult = JsonHelper.Serialize(result.Result); completion_tokens,
returnModel.CompletionResultModel = completionResult; };
Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, resultModel, Common.Config.JwtExpirTime); oldModel.TokenNum = JsonHelper.Serialize(tokenNum);
}
} }
catch (Exception ex)
{
}
aiModule.SetAIUseLogModule(oldModel);
} }
catch (Exception ex) Cache.User.UserReidsCache.Set(this.AppletUserInfo.AccountId + "_" + "LogId_" + addId, returnModel, Common.Config.JwtExpirTime);
{ }
Common.Plugin.LogHelper.Write(ex, "GetUserLoginInfo"); 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.Success(data: new { result = resultModel, Id = addId });
} }
} }
return ApiResult.Failed("解析失败!");
} }
/// <summary> /// <summary>
...@@ -310,12 +368,6 @@ namespace Edu.WebApi.Controllers.AI ...@@ -310,12 +368,6 @@ namespace Edu.WebApi.Controllers.AI
{ {
return ApiResult.Failed("获取失败请重新调用"); 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); return ApiResult.Success(data: returnModel);
} }
...@@ -342,7 +394,7 @@ namespace Edu.WebApi.Controllers.AI ...@@ -342,7 +394,7 @@ namespace Edu.WebApi.Controllers.AI
model.TokenNum, model.TokenNum,
model.KeyWordType, model.KeyWordType,
model.KeyWord, model.KeyWord,
model.ResultInfo, model.ResultInfo,
SupplierType = model?.SupplierType ?? 0, SupplierType = model?.SupplierType ?? 0,
PresetsApplicationName = model?.ApplicationName ?? "", PresetsApplicationName = model?.ApplicationName ?? "",
SupplierName = model?.SupplierName ?? "", SupplierName = model?.SupplierName ?? "",
......
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