Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ChatApi/ChatApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

</Project>
163 changes: 163 additions & 0 deletions ChatApi/ChatApiHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace ChatApi {
public class ChatApiHelper {
public class ApowersoftTaskData {
public string task_id { get; set; }
}

public class ApowersoftTask {
public int status { get; set; }
public string message { get; set; }
public ApowersoftTaskData data { get; set; }
}
public class ApowersoftResult {
public int status { get; set; }
public ApowersoftResultData data { get; set; }
}

public class ApowersoftResultData {
public string text { get; set; }
public string conversation_id { get; set; }
public string msg_id { get; set; }
public int state { get; set; }
public string task_id { get; set; }
}


public ChatApiHelper(ChatApiService chatApiService) {
this.chatApiService = chatApiService;
if (string.IsNullOrEmpty(chatApiService.Option.ApiKey)){
throw new Exception("Please set apiKey first!");
}
url = chatApiService.Option.ApiUrl;

client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-KEY", chatApiService.Option.ApiKey);
//client.DefaultRequestHeaders.Add("UserAgent", "");
}


private string url = "";
private HttpClient client;
private ChatApiService chatApiService;

/// <summary>
/// 发送第一条人设 promote
/// </summary>
/// <returns></returns>
public async Task<ApowersoftResultData> SetFirstPromote() {
if (!string.IsNullOrEmpty(chatApiService?.BehaviorOption?.FirstPromote)) {
return await GetResults(chatApiService?.BehaviorOption?.FirstPromote);
}
else {
return null;
}
}

public async Task<ApowersoftResultData> GetResults(string inputText, ApowersoftResultData lastData = null) {
var result = new ApowersoftResultData();

var taskId = await CreateTask(inputText, false, lastData);
if (string.IsNullOrEmpty(taskId)) {
result.text = chatApiService.BehaviorOption.DefultErrorResponse;
}
var data = await QueryTask(taskId);
result = JsonConvert.DeserializeObject<ApowersoftResult>(data).data;
var count = 1;
while (result.state != 1 && count < 100) {
data = await QueryTask(taskId);
result = JsonConvert.DeserializeObject<ApowersoftResult>(data).data;
await Task.Delay(100);
count++;
}


return result;
}

public async Task<ApowersoftResultData> GetStreamResult(string inputText, Action<string> append, ApowersoftResultData lastData = null) {
var result = new ApowersoftResultData();

var taskId = await CreateTask(inputText, true, lastData);
if (string.IsNullOrEmpty(taskId)) {
result.text = chatApiService.BehaviorOption.DefultConnectErrorResponse;
}
var streamReader = await QueryTaskBySteam(taskId);

while (true && streamReader != null) {
var line = await streamReader.ReadLineAsync();
if (line == null) break;

// 解析 SSE 消息内容
if (line.StartsWith("data: ")) {
var data = line.Substring("data: ".Length).Trim();
if (data.EndsWith("}")) {
result = JsonConvert.DeserializeObject<ApowersoftResultData>(data);
}
else {
append?.Invoke(data);
}
}
await Task.Delay(10);
}
return result;
}

private async Task<string> CreateTask(string inputText, bool isStream, ApowersoftResultData lastData = null) {
var form = new MultipartFormDataContent();
form.Add(new StringContent(inputText), "prompt");

if (isStream) {
form.Add(new StringContent("1"), "response_type");
}
if (lastData != null) {
form.Add(new StringContent(lastData.conversation_id), "conversation_id");
form.Add(new StringContent(lastData.msg_id), "prev_msg_id");
}
try {
var response = await client.PostAsync(url, form);
var result = JsonConvert.DeserializeObject<ApowersoftTask>(await response.Content.ReadAsStringAsync());
return result.data.task_id;
}
catch (System.Exception ex) {
Debug.WriteLine(ex);
return string.Empty;
}
}

private async Task<StreamReader> QueryTaskBySteam(string id) {
var request = new HttpRequestMessage(HttpMethod.Get, url + id) {
Headers = {
{"Accept", "text/event-stream" }
}
};
try {
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();
var reader = new StreamReader(stream);
return reader;
}
catch (Exception ex) {
Debug.WriteLine(ex);
return null;
}
}

private async Task<string> QueryTask(string id) {

try {
return await client.GetStringAsync(url + id);
}
catch (Exception ex) {
Debug.WriteLine(ex);
return null;
}
}
}
}
63 changes: 63 additions & 0 deletions ChatApi/ChatApiService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ChatApi {
public class ChatApiService {
public ChatApiService(string jsonPath) {
SetOption(jsonPath);
}
public ChatApiService(ChatApiOption option, ChatBehaviorOption behaviorOption) {
this.Option = option;
this.BehaviorOption = behaviorOption;
}
public void SetOption(ChatApiOption option, ChatBehaviorOption behaviorOption ) {
this.Option = option;
this.BehaviorOption = behaviorOption;
}

public void SetOption(string jsonPath) {
if (File.Exists(jsonPath)) {
var jsonStr = File.ReadAllText(jsonPath);
var jsonObject = JObject.Parse(jsonStr);
if(jsonObject["chat_api_option"] != null) {
Option = JsonConvert.DeserializeObject<ChatApiOption>(jsonObject["chat_api_option"].ToString());
}
if (jsonObject["chat_behavior_option"] != null) {
BehaviorOption = JsonConvert.DeserializeObject<ChatBehaviorOption>(jsonObject["chat_behavior_option"].ToString());
}
}

}

internal ChatApiOption Option { get; private set; }
internal ChatBehaviorOption BehaviorOption { get; private set; }

}

public class ChatApiOption {
public ChatApiOption(string apiKey = "", string apiUrl = "") {
ApiKey = apiKey;
ApiUrl = apiUrl;
}
[JsonProperty("api_key")]
public string ApiKey { get; set; }
[JsonProperty("api_url")]
public string ApiUrl { get; set; }

}

public class ChatBehaviorOption {
[JsonProperty("first_promote")]
public string FirstPromote { get; set; }
[JsonProperty("defult_error_response")]
public string DefultErrorResponse { get; set; } = @"暂时没有思绪呢~ ε=ε=ε=ε=ε=ε=┌(; ̄◇ ̄)┘ (。→‿←。) (๑→‿ฺ←๑)(=ˇωˇ=)(⺻▽⺻ )<( ̄︶ ̄)>(•‾̑⌣‾̑•)✧˖° (๑˘ ˘๑) ♥(。→v←。)♥";
[JsonProperty("defult_connect_error_response")]
public string DefultConnectErrorResponse { get; set; } = @"啊!我的脑子离开了我的身体,容我缓缓 (┬┬﹏┬┬) ಥ_ಥ (‾◡◝) /_ \ <(_ _)>";

}

}
28 changes: 27 additions & 1 deletion ChatWindow.sln
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32929.385
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatWindow", "ChatWindow\ChatWindow.csproj", "{096634AB-330E-46B3-B530-42469611763F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatWindow", "ChatWindow\ChatWindow.csproj", "{096634AB-330E-46B3-B530-42469611763F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatApi", "ChatApi\ChatApi.csproj", "{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{096634AB-330E-46B3-B530-42469611763F}.Debug|Any CPU.ActiveCfg = Debug|x64
{096634AB-330E-46B3-B530-42469611763F}.Debug|Any CPU.Build.0 = Debug|x64
{096634AB-330E-46B3-B530-42469611763F}.Debug|Any CPU.Deploy.0 = Debug|x64
{096634AB-330E-46B3-B530-42469611763F}.Debug|ARM64.ActiveCfg = Debug|ARM64
{096634AB-330E-46B3-B530-42469611763F}.Debug|ARM64.Build.0 = Debug|ARM64
{096634AB-330E-46B3-B530-42469611763F}.Debug|ARM64.Deploy.0 = Debug|ARM64
Expand All @@ -24,6 +31,9 @@ Global
{096634AB-330E-46B3-B530-42469611763F}.Debug|x86.ActiveCfg = Debug|x86
{096634AB-330E-46B3-B530-42469611763F}.Debug|x86.Build.0 = Debug|x86
{096634AB-330E-46B3-B530-42469611763F}.Debug|x86.Deploy.0 = Debug|x86
{096634AB-330E-46B3-B530-42469611763F}.Release|Any CPU.ActiveCfg = Release|x64
{096634AB-330E-46B3-B530-42469611763F}.Release|Any CPU.Build.0 = Release|x64
{096634AB-330E-46B3-B530-42469611763F}.Release|Any CPU.Deploy.0 = Release|x64
{096634AB-330E-46B3-B530-42469611763F}.Release|ARM64.ActiveCfg = Release|ARM64
{096634AB-330E-46B3-B530-42469611763F}.Release|ARM64.Build.0 = Release|ARM64
{096634AB-330E-46B3-B530-42469611763F}.Release|ARM64.Deploy.0 = Release|ARM64
Expand All @@ -33,6 +43,22 @@ Global
{096634AB-330E-46B3-B530-42469611763F}.Release|x86.ActiveCfg = Release|x86
{096634AB-330E-46B3-B530-42469611763F}.Release|x86.Build.0 = Release|x86
{096634AB-330E-46B3-B530-42469611763F}.Release|x86.Deploy.0 = Release|x86
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|ARM64.Build.0 = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|x64.ActiveCfg = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|x64.Build.0 = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|x86.ActiveCfg = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Debug|x86.Build.0 = Debug|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|Any CPU.Build.0 = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|ARM64.ActiveCfg = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|ARM64.Build.0 = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|x64.ActiveCfg = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|x64.Build.0 = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|x86.ActiveCfg = Release|Any CPU
{FAFAB75B-FD00-4895-AB5C-3E6EB553FBB5}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
21 changes: 18 additions & 3 deletions ChatWindow/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
using Windows.Storage;
using System.Configuration;
using ChatWindow.AppClasses;
using ChatApi;
using Microsoft.Extensions.DependencyInjection;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
Expand All @@ -38,21 +40,34 @@ public partial class App : Application {
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App() {
this.InitializeComponent();
this.InitializeComponent();
}
private Window m_window;

/// <summary>
/// Invoked when the application is launched.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override async void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args) {
await AppSettings.Init();
Services = ConfigureServices();
m_window = new MainWindow();
m_window.Activate();

}

private Window m_window;


internal static IServiceProvider Services { get; private set; }
private static IServiceProvider ConfigureServices() {
var services = new ServiceCollection();

services.AddTransient<ChatApiOption>();
services.AddTransient<ChatBehaviorOption>();
services.AddTransient<ChatApiService>(sp => new ChatApiService(new ChatApiOption(AppSettings.Key, AppSettings.URL), new ChatBehaviorOption()));
services.AddSingleton<ChatApiHelper>();

return services.BuildServiceProvider();
}

}
}
4 changes: 4 additions & 0 deletions ChatWindow/ChatWindow.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<PackageReference Include="CommunityToolkit.WinUI.UI" Version="7.1.2" />
<PackageReference Include="CommunityToolkit.WinUI.UI.Behaviors" Version="7.1.2" />
<PackageReference Include="CommunityToolkit.WinUI.UI.Controls.Markdown" Version="7.1.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.3.230331000" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.25336-preview" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
Expand Down Expand Up @@ -70,6 +71,9 @@
<ItemGroup>
<Content Include="Images\yuyin.png" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ChatApi\ChatApi.csproj" />
</ItemGroup>
<ItemGroup>
<Page Update="Pages\TranslationPage.xaml">
<Generator>MSBuild:Compile</Generator>
Expand Down
5 changes: 3 additions & 2 deletions ChatWindow/Helper/ApiHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using static ChatWindow.App;

namespace ChatWindow.Helper {
[Obsolete]
public class ApiHelper {
public class ApowersoftTaskData {
public string task_id { get; set; }
Expand Down Expand Up @@ -125,7 +126,7 @@ private async Task<StreamReader> QueryTaskBySteam(string id) {
var stream = response.Content.ReadAsStream();
var reader = new StreamReader(stream);
return reader;
} catch (System.Exception ex) {
} catch (System.Exception) {
return null;
}
}
Expand All @@ -134,7 +135,7 @@ private async Task<string> QueryTask(string id) {

try {
return await client.GetStringAsync(url + id);
} catch (System.Exception ex) {
} catch (System.Exception) {
return null;
}
}
Expand Down
Loading