Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移除多余的第三方依赖,采用IKernelBuilder 实现对接讯飞api的聊天接口 #111

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ appsettings.Development.json
/src/.idea/.idea.Senparc.AI/.idea
/Samples/Senparc.AI.Samples.Consoles/Properties/PublishProfiles
/Samples/Senparc.AI.Samples.Consoles/Senparc.AI.Samples.Consoles.csproj.user
/Samples/Senparc.AI.Samples.Consoles/appsettings.json
/src/ConsoleApp1/ConsoleApp1.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@

<ItemGroup>

<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
Expand Down
29 changes: 25 additions & 4 deletions Samples/Senaprc.AI.Samples.Agents/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
//Senparc.AI 设置
"SenparcAiSetting": {
"IsDebug": true,
"AiPlatform": "AzureOpenAI", //注意修改为自己平台对应的枚举值
"AiPlatform": "SparkAI", //注意修改为自己平台对应的枚举值
"NeuCharAIKeys": {
"ApiKey": "<Your ApiKey>", //在 https://www.neuchar.com/Developer/AiApp 申请
"NeuCharEndpoint": "https://www.neuchar.com/<DeveloperId>", //查看 ApiKey 时可看到 DeveloperId
"ApiKey": "5b0b30df3fd44811bdbfed8fe07be3eb", //在 https://www.neuchar.com/Developer/AiApp 申请
"NeuCharEndpoint": "https://www.neuchar.com/18673", //查看 ApiKey 时可看到 DeveloperId
"ModelName": {
"Chat": "gpt-35-turbo"
"Chat": "gpt-4-32k"
}
},
"AzureOpenAIKeys": {
Expand All @@ -46,6 +46,15 @@
"TextCompletion": "chatglm2"
}
},
"SparkAIKeys": {
"ApiKey": "40a519641152f3c7caecbcc416065ae1", //TODO:加密
"AppId": "a891b281",
"ApiSecret": "ODdhYjEzZTY3OGE4OWJkYTI0M2ZlNGIz",
"SparkAiEndpoint": "",
"ModelName": {
"Chat": "gpt-35-turbo"
}
},
"Items": {
"AzureDalle3": {
"AiPlatform": "AzureOpenAI",
Expand All @@ -68,6 +77,18 @@
}
}
},
"SparkAIKeys": {
"AiPlatform": "SparkAI",
"SparkAIKeys": {
"ApiKey": "40a519641152f3c7caecbcc416065ae1", //TODO:加密
"AppId": "a891b281",
"ApiSecret": "ODdhYjEzZTY3OGE4OWJkYTI0M2ZlNGIz",
"SparkAiEndpoint": "https://www.neuchar.com/<DeveloperId>/",
"ModelName": {
"Chat": "gpt-35-turbo"
}
}
},
"OtherModels": {
"AiPlatform": "<AiPlatform>"
//任意数量的 *Keys 配置
Expand Down
30 changes: 16 additions & 14 deletions Samples/Senparc.AI.Samples.Consoles/Samples/ChatSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,31 +95,33 @@ 输入 exit 退出。
var useMultiLine = false;
//开始对话
var talkingRounds = 0;
while (true)
{
talkingRounds++;
//bool useMultiLine = false; // 确保变量被正确初始化
//StringBuilder multiLineContent = new StringBuilder(); // 初始化多行内容存储

while (true) {
talkingRounds++;
await Console.Out.WriteLineAsync($"[{talkingRounds}] 人类:");
var input = Console.ReadLine() ?? "";

if (input.ToUpper() == "[ML]")
{
// 修剪输入并转换为大写
if (input.Trim().ToUpper() == "[ML]") {
await Console.Out.WriteLineAsync("识别到多行模式,请继续输入");
await Console.Out.FlushAsync(); // 强制刷新缓冲区,确保输出顺序一致
useMultiLine = true;
}

while (useMultiLine)
{
if (input.ToUpper() == "[END]")
{
while (useMultiLine) {
input = Console.ReadLine();

// 检查是否结束多行模式
if (input.Trim().ToUpper() == "[END]") {
useMultiLine = false;
input = multiLineContent.ToString();
}
else
{
multiLineContent.Clear(); // 清空多行内容缓存
} else {
await Console.Out.WriteLineAsync("请继续输入,直到输入 [END] 停止...");
input = Console.ReadLine();
multiLineContent.Append(input);
await Console.Out.FlushAsync(); // 强制刷新缓冲区,确保输出顺序一致
multiLineContent.AppendLine(input); // 添加多行内容到 StringBuilder 中
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,6 @@

</PropertyGroup>

<ItemGroup>
<None Remove="appsettings.Development.json" />
</ItemGroup>

<ItemGroup>
<Content Include="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
Expand All @@ -34,4 +21,10 @@
<ProjectReference Include="..\..\src\Senparc.AI\Senparc.AI.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
85 changes: 0 additions & 85 deletions Samples/Senparc.AI.Samples.Consoles/appsettings.json

This file was deleted.

10 changes: 10 additions & 0 deletions src/ConsoleApp1/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
62 changes: 62 additions & 0 deletions src/Senparc.AI.Kernel/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.TextGeneration;
using Microsoft.SemanticKernel;
using Senparc.AI.Kernel.SparkAI;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http;
using static Humanizer.On;
using System.IO;
using System.Threading;

namespace Senparc.AI.Kernel
{
Expand Down Expand Up @@ -36,7 +43,21 @@ public static IKernelBuilder AddFastAPIChatCompletion(this IKernelBuilder builde
builder.Services.AddKeyedSingleton((object?)serviceId, (Func<IServiceProvider, object?, ITextGenerationService>)implementationFactory);
return builder;
}
//public static IKernelBuilder AddFOllamaChatCompletion(this IKernelBuilder builder, string modelId, string endpoint, string serviceId = null)
//{
// string modelId2 = modelId;


// Func<IServiceProvider, object, OpenAIChatCompletionService> implementationFactory =
// (IServiceProvider serviceProvider, object? _) =>
// new OpenAIChatCompletionService(modelId, new OpenAIClient(new Uri(endpoint), new Azure.AzureKeyCredential(apiKey)), serviceProvider.GetService<ILoggerFactory>());

// OllamaApiClientExtensions.

// builder.Services.AddKeyedSingleton((object?)serviceId, (Func<IServiceProvider, object?, IChatCompletionService>)implementationFactory);
// builder.Services.AddKeyedSingleton((object?)serviceId, (Func<IServiceProvider, object?, ITextGenerationService>)implementationFactory);
// return builder;
//}
#region Ollama

public static IKernelBuilder AddFOllamaChatCompletion(this IKernelBuilder builder, string modelId, string endpoint, string serviceId = null)
Expand Down Expand Up @@ -65,5 +86,46 @@ public static IKernelBuilder AddFOllamaTextCompletion(this IKernelBuilder builde
}

#endregion
/// <summary>
/// 添加讯飞聊天服务
/// </summary>
/// <param name="builder"></param>
/// <param name="modelId"></param>
/// <param name="apiKey"></param>
/// <param name="endpoint"></param>
/// <param name="orgId"></param>
/// <param name="serviceId"></param>
/// <returns></returns>
public static IKernelBuilder AddSparkAPIChatCompletion(this IKernelBuilder builder, string modelId, string apiKey, string endpoint, string? orgId = null, string? serviceId = null)
{
// 创建 HttpClient,用于与讯飞星火 API 交互
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(endpoint);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
Func<IServiceProvider, object, OpenAIChatCompletionService> implementationFactory =
(IServiceProvider serviceProvider, object? _) =>
new OpenAIChatCompletionService(modelId, new Uri(endpoint), apiKey, null, httpClient);
builder.Services.AddKeyedSingleton((object?)serviceId, (Func<IServiceProvider, object?, IChatCompletionService>)implementationFactory);
builder.Services.AddKeyedSingleton((object?)serviceId, (Func<IServiceProvider, object?, ITextGenerationService>)implementationFactory);
return builder;
}

///// <summary>
///// 添加 SparkAI 聊天服务 现在只有简单聊天 过时
///// </summary>
///// <param name="builder"></param>
///// <param name="modelId"></param>
///// <param name="apiKey"></param>
///// <param name="endpoint"></param>
///// <param name="orgId"></param>
///// <param name="serviceId"></param>
///// <returns></returns>
//public static IKernelBuilder AddSparkAIChatCompletion(this IKernelBuilder builder, string appId, string apiKey, string apiSecret,string modelVersion)
//{
// // Register SparkAIService as a singleton in the dependency injection container SparkApiClient
// // builder.Services.AddSingleton<ITextGenerationService>(new SparkAIChatService(appId, apiKey, apiSecret,modelVersion));
// builder.Services.AddSingleton<ITextGenerationService>(new SparkApiClient(apiKey, modelVersion));
// return builder;
//}
}
}
33 changes: 33 additions & 0 deletions src/Senparc.AI.Kernel/Helpers/ExtensionHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Microsoft.SemanticKernel;

Expand All @@ -17,5 +18,37 @@ public static void Set(this KernelArguments kernelArguments, string key, object
{
kernelArguments[key] = value;
}

public static string GenerateApiPassword(string key, string secret)
{
// 拼接 key 和 secret
string combined = $"{key}:{secret}";

// 将拼接后的字符串进行 Base64 编码
byte[] byteArray = Encoding.UTF8.GetBytes(combined);
string base64Encoded = Convert.ToBase64String(byteArray);

return base64Encoded;
}

public static string GetAuthorizationUrl(string apiKey, string apiSecret, string hostUrl)
{
var url = new Uri(hostUrl);

string dateString = DateTime.UtcNow.ToString("r");

byte[] signatureBytes = Encoding.ASCII.GetBytes($"host: {url.Host}\ndate: {dateString}\nGET {url.AbsolutePath} HTTP/1.1");

using HMACSHA256 hmacsha256 = new(Encoding.ASCII.GetBytes(apiSecret));
byte[] computedHash = hmacsha256.ComputeHash(signatureBytes);
string signature = Convert.ToBase64String(computedHash);

string authorizationString = $"api_key=\"{apiKey}\",algorithm=\"hmac-sha256\",headers=\"host date request-line\",signature=\"{signature}\"";
string authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(authorizationString));

string query = $"authorization={authorization}&date={dateString}&host={url.Host}";

return new UriBuilder(url) { Scheme = url.Scheme, Query = query }.ToString();
}
}
}
Loading
Loading