feat(openai): 新增 v2 版机器人对话相关接口

This commit is contained in:
Fu Diwei
2024-06-05 19:39:23 +08:00
parent ea25c0bf24
commit 1aed793b08
10 changed files with 289 additions and 134 deletions

View File

@@ -9,6 +9,7 @@ using Flurl.Http;
namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Interceptors
{
using SKIT.FlurlHttpClient.Internal;
using SKIT.FlurlHttpClient.Primitives;
internal class WechatOpenAIRequestEncryptionInterceptor : HttpInterceptor
{
@@ -90,19 +91,19 @@ namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Interceptors
if (context.FlurlCall.HttpResponseMessage.StatusCode != HttpStatusCode.OK)
return;
byte[] respBytes = Array.Empty<byte>();
string respBody = string.Empty;
if (context.FlurlCall.HttpResponseMessage.Content is not null)
{
HttpContent httpContent = context.FlurlCall.HttpResponseMessage.Content;
respBytes = await
respBody = await
#if NET5_0_OR_GREATER
httpContent.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
httpContent.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
_AsyncEx.RunTaskWithCancellationTokenAsync(httpContent.ReadAsByteArrayAsync(), cancellationToken).ConfigureAwait(false);
_AsyncEx.RunTaskWithCancellationTokenAsync(httpContent.ReadAsStringAsync(), cancellationToken).ConfigureAwait(false);
#endif
}
byte[] respBytesDecrypted;
string respBodyDecrypted;
try
{
const int AES_BLOCK_SIZE = 16;
@@ -110,10 +111,10 @@ namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Interceptors
byte[] ivBytes = new byte[AES_BLOCK_SIZE]; // iv 是 key 的前 16 个字节
Buffer.BlockCopy(keyBytes, 0, ivBytes, 0, ivBytes.Length);
respBytesDecrypted = Utilities.AESUtility.DecryptWithCBC(
keyBytes: keyBytes,
ivBytes: ivBytes,
cipherBytes: respBytes
respBodyDecrypted = Utilities.AESUtility.DecryptWithCBC(
encodingKey: EncodedString.ToBase64String(keyBytes),
encodingIV: EncodedString.ToBase64String(ivBytes),
encodingCipher: new EncodedString(respBody, EncodingKinds.Base64)
)!;
}
catch (Exception ex)
@@ -122,7 +123,7 @@ namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Interceptors
}
context.FlurlCall.HttpResponseMessage!.Content?.Dispose();
context.FlurlCall.HttpResponseMessage!.Content = new ByteArrayContent(respBytesDecrypted);
context.FlurlCall.HttpResponseMessage!.Content = new StringContent(respBodyDecrypted);
}
private string GetRequestUrlPath(Uri uri)
@@ -144,7 +145,7 @@ namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Interceptors
return false;
}
return false;
return true;
}
}
}