OpenAi 채팅 완료 API (ChatGpt) DI 및 EF 코어 지원과 통합. .NET 응용 프로그램에서 API를 사용할 수 있습니다. 또한 클라이언트는 비동기 스트림을 통해 스트리밍 응답 (예 : ChatGpt)을 지원합니다.
AddChatGptEntityFrameworkIntegration now requires builder.Configuration as a mandatory parameter.StructuredResponse module allows you to get structured responses from the API as C# object. 참조 : 구조적 응답 섹션. 먼저 OpenAI 계정을 만들고 API 키 (또는 OpenRouter 또는 Azure OpenAI)를 가져와야합니다. https://platform.openai.com/account/api-keys에서이를 수행 할 수 있습니다.
Di and Persistence (EF Core) 지원 기능이있는 .NET 프로젝트에서 ChatGpt 서비스를 사용하는 가장 쉬운 방법은 Nuget 패키지 OpenAi.Chatgpt.EntityFrameworkCore를 설치하는 것입니다.
Install-Package OpenAI.ChatGPT.EntityFrameworkCore
If you don't want to use EF Core, you can install the package OpenAI.ChatGPT.AspNetCore and implement your own storage for chat history, using IChatHistoryStorage interface.
TL; DR : 참조 프로젝트의 예를 참조하십시오.
appsettings.json file (not safe): {
"AIProvider" : " openai " , // or openrouter or azure_openai
"OpenAICredentials" : { //optional
"ApiKey" : " your-api-key-from-openai " ,
"ApiHost" : " https://api.openai.com/v1/ "
},
"AzureOpenAICredentials" : { //optional
"ApiKey" : " your-api-key-from-azure-openai " ,
"ApiHost" : " https://{your-host}.openai.azure.com/ " ,
"DeploymentName" : " gpt-4-turbo-preview "
},
"OpenRouterCredentials" : { //optional
"ApiKey" : " your-api-key-from-openrouter " ,
"ApiHost" : " https://openrouter.ai/api/v1 "
}
} Also, you can specify OpenAI API key as environment variable ASPNETCORE_OpenAICredentials:ApiKey .
builder . Services . AddChatGptEntityFrameworkIntegration (
builder . Configuration ,
options => options . UseSqlite ( " Data Source=chats.db " ) ) ; Instead of options.UseSqlite("Data Source=chats.db") use your own db and connection string.
ChatGPTFactory to your service and use it to create ChatGPT instance: public class YourService
{
private readonly ChatGPTFactory _chatGptFactory ;
public YourService ( ChatGPTFactory chatGptFactory )
{
_chatGptFactory = chatGptFactory ;
}
public async Task < string > GetAnswer ( string text )
{
ChatGPT chatGpt = await _chatGptFactory . Create ( userId ) ;
var chatService = await chatGpt . ContinueOrStartNewTopic ( ) ;
response = await _chatService . GetNextMessageResponse ( _prompt ) ;
return response ;
}
}Blazor 예를 참조하십시오.
If you want to configure request parameters, you can do it in appsettings.json configuration or in ChatGPTFactory.Create or in ChatGPT.CreateChat methods.
{
"ChatGPTConfig" : {
"InitialSystemMessage" : " You are a helpful and kind assistant. " ,
"InitialUserMessage" : null ,
"MaxTokens" : null ,
"Model" : null ,
"Temperature" : null ,
"PassUserIdToOpenAiRequests" : true
}
}ChatgptConfig 내부의 매개 변수 설명을 참조하십시오.
서버 응답이 성공 상태 코드가 아닌 경우 클라이언트는 예상치 못한 반응성을 던지게됩니다. 예외에는 OpenAI API의 오류 메시지가 포함됩니다.
By default, requesting cancellation or ChatService.Stop() method calling will throw OperationCanceledException . If you don't want to throw it (relevant for streaming responses), you can set throwOnCancellation parameter to false :
await foreach ( string chunk in chatService . StreamNextMessageResponse ( text , throwOnCancellation : false ) )
{
//...
} ChatGPTFactory , ChatGPT classes thread-safety is depend on the IChatHistoryStorage implementation. If you use ChatGPTFactory with entity framework, it's NOT thread-safe. ChatService class is not thread-safe.
어쨌든,이 서비스는 DI와 안전하게 사용되도록 설계되었으므로 걱정할 필요가 없습니다.
All the methods from all the packages are designed to be used in async context and use ConfigureAwait(false) (thanks for the ConfigureAwait.Fody package).
Since ChatGPTFactory depends on IHttpClientFactory , you can easily use any of the available policies for it, like Polly .
이 모듈을 사용하면 API에서 C# 객체로 구조화 된 응답을 얻을 수 있습니다. 채팅 외에 API를 사용하려는 경우 유용합니다.
record City ( string Name , int YearOfFoundation , string Country ) ;
var message = Dialog
. StartAsSystem ( " Return requested data. " )
. ThenUser ( " I need info about Almaty city " ) ;
City almaty = await _client . GetStructuredResponse < City > ( message , model : ChatCompletionModels . Gpt4Turbo ) ;
Console . WriteLine ( almaty ) ; // Name: "Almaty", Country: "Kazakhstan", YearOfFoundation: 1854 Under the hood, it uses the new json mode of the API for GPT4Turbo and for the gpt-3.5-turbo-1106 . Regular GPT4 and GPT3.5Turbo models are also supported, but GPT3.5 responses may be unstable (for GPT3.5 it's strictly recommended to provide examples parameter).
어레이, 중첩 객체 및 열거가있는보다 복잡한 예는 테스트에서 사용할 수 있습니다.
chatgpt_api_dotnet/tests/openai.chatgpt.integrationtests/openaiclienttests/openaiclient_getStructuredResponse.cs
F50D386의 1 행
nuget : https://www.nuget.org/packages.chatgpt.modules.structuredresponse
이 모듈을 사용하면 한 언어에서 다른 언어로 메시지를 변환 할 수 있습니다.
string textToTranslate = " Hello, world! " ;
string translatedText = await _client . TranslateText ( textToTranslate , " English " , " Russian " ) ;
Console . WriteLine ( translatedText ) ; // "Привет, мир!" Also, it's possible to translate entire object in pair with StructuredResponse module:
var objectToTranslate = new Order (
new List < Order . Item >
{
new ( 1 , " Book " , 5 ) ,
new ( 2 , " Pen " , 10 ) ,
new ( 3 , " Notebook " , 3 )
}
) ;
Order translatedObject = await _client . TranslateObject ( objectToTranslate , " English " , " Russian " ) ;테스트의 전체 예를 참조하십시오.
chatgpt_api_dotnet/tests/openai.chatgpt.integrationTests/chatGptTranslatorServicetests.cs
11658b7의 36 행
Nuget : https://www.nuget.org/packages.chatgpt.modules.translator
다음은 ChatCompletions (ChatGpt) API 요청 (OpenAi.ChatGpt/Models/ChatCompletion/ChatCompletionRequest.cs)에서 사용할 수있는 주요 매개 변수 목록입니다. 그 중 일부는이 기사에서 가져온 것입니다 : https://towardsdatascience.com/gpt-3-parameters-and-prompt-design-1a595dc5b405
아래에서 ChatCompletions API에 대한 나열된 매개 변수.
예측 생성 AI 모델은 엔진 매개 변수에 의해 지정됩니다. 사용 가능한 모델은 다음과 같습니다. https://platform.openai.com/docs/models
| C# 모델 | API 모델 |
|---|---|
| ChatCompletionModels.gpt4turbo | GPT-4-1106-- 검색 |
| ChatCompletionModels.gpt4 | GPT-4 |
| ChatCompletionModels.gpt4_0613 | GPT-4-0613 |
| ChatCompletionModels.gpt4_32k | GPT-4-32K |
| ChatCompletionModels.gpt4_32k_0613 | GPT-4-32K-0613 |
| ChatCompletionModels.gpt3_5_turbo | GPT-3.5 터보 |
| chatCompletionModels.gpt3_5_turbo_1106 | GPT-3.5-Turbo-1106 |
| ChatCompletionModels.gpt3_5_turbo_16k | GPT-3.5- 터보 -16K |
| ChatCompletionModels.gpt3_5_turbo_0613 | GPT-3.5-Turbo-0613 |
| ChatCompletionModels.gpt3_5_turbo_16k_0613 | GPT-3.5-TURBO-16K-0613 |
| ChatCompletionModels.gpt4_0314 | GPT-4-0314 |
| ChatCompletionModels.gpt4_32k_0314 | GPT-4-32K-0314 |
| ChatCompletionModels.gpt3_5_turbo_0301 | GPT-3.5-Turbo-0301 |
최대 토큰 수는 생성 된 답변을 허용했습니다. Defaults to ChatCompletionRequest.MaxTokensDefault (64).
ChatCompletionModels.GetMaxTokensLimitForModel method.ChatCompletionMessage.CalculateApproxTotalTokenCount methodChatCompletionResponse.Usage.TotalTokens . 영어의 규칙으로, 1 개의 토큰은 약 4 자입니다 (따라서 100 개의 토큰 ≈ 75 단어). Openai : https://platform.openai.com/tokenizer에서 Tokenizer를 참조하십시오0과 2 사이의 샘플링 온도.
ChatCompletionTemperatures .ChatCompletionTemperatures.Balanced (0.5).설명 : 확률에 매핑되기 전에 모델은 정규화되지 않은 값 (로이트)을 출력합니다. 로그는 일반적으로 SoftMax와 같은 함수와 함께 사용하여 확률로 변환됩니다.
그러나 SoftMax 함수를 적용하기 전에 열역학에서 영감을 얻은 트릭을 사용하고 온도 매개 변수 (즉, Logits/Onder)로 로그를 확장 할 수 있습니다.
1에 가까운 온도 매개 변수는 로그가 수정없이 SoftMax 함수를 통과 함을 의미합니다. 온도가 0에 가까워지면 가장 높은 토큰이 다른 토큰에 비해 매우 가능성이 높아질 것입니다. 즉, 모델은 더 결정적이되고 주어진 일련의 단어 후에 항상 동일한 토큰 세트를 출력합니다.
더 많은 매개 변수 설명은 여기에서 찾을 수 있습니다 : 일부는이 기사에서 가져옵니다 : https://towardsdatascience.com/gpt-3-parameters-and-prompt-design-1a595dc5b405
DI 및 채팅 기록이 필요하지 않은 경우 Nuget 패키지 Openai.chatgpt 만 사용할 수 있습니다.
Install-Package OpenAI.ChatGPT
Then create an instance of OpenAIClient :
_client = new OpenAiClient ( " {YOUR_OPENAI_API_KEY} " ) ; string text = " Who are you? " ;
string response = await _client . GetChatCompletions ( new UserMessage ( text ) , maxTokens : 80 ) ;
Console . WriteLine ( response ) ; var text = " Write the world top 3 songs of Soul genre " ;
await foreach ( string chunk in _client . StreamChatCompletions ( new UserMessage ( text ) , maxTokens : 80 ) )
{
Console . Write ( chunk ) ;
} Use ThenAssistant and ThenUser methods to create a dialog:
var dialog = Dialog . StartAsUser ( " How many meters are in a kilometer? Write just the number. " ) //the message from user
. ThenAssistant ( " 1000 " ) // response from the assistant
. ThenUser ( " Convert it to hex. Write just the number. " ) ; // the next message from user
await foreach ( var chunk in _client . StreamChatCompletions ( dialog , maxTokens : 80 ) )
{
Console . Write ( chunk ) ;
}또는 메시지 기록을 컬렉션으로 보내십시오.