Giter Club home page Giter Club logo

gigachatadapter's Introduction

GigaChatAdapter .net core

Capabilities

➕ Easy to start to use GigaChat API. Only main classes and methods in root namespace. All helpers stored in child namespaces if you need set more details

➕ You can set all settings according official documentation https://developers.sber.ru/docs/ru/gigachat/api/reference

➕ The history can be saved (in file for example) and can be used in other sessions. Just load history before request prompt

Completion completion = new Completion();
completion.History = {Your deserialized history}

➕ All errors wrapped in one request field 'ErrorTextIfFailed'. It includes HttpErrors and GigaChat errors

➕ Dont worry about access token expiring. Just use method 'UpdateToken()' before sending request prompt


Example

The code example you can find below or in application "TestGigaChatAdapter"

Step 1: //Set auth / Укажите аутентификационные данные из личного кабинета

Below after code description how to get this authData in Important! tips

string authData = "authData=="; // base64
Authorization auth = new Authorization(authData, GigaChatAdapter.Auth.RateScope.GIGACHAT_API_PERS);
var authResult = await auth.SendRequest();

Step 2: //Send Prompts to get answer from AI / отправляйте вопросы чату, чтобы получить ответ от ИИ

if (authResult.AuthorizationSuccess)
{
    Completion completion = new Completion();
    Console.WriteLine("EN: Type prompt or close console to end application");
    Console.WriteLine("РУ: Напишите запрос к модели. В ином случае закройте окно, если дальнейшую работу с чатботом необходимо прекратить.");
    
    while (true)
    {
        //read prompt / Чтение промпта с консоли
        var prompt = Console.ReadLine();

        //update access token if expired / Обновление токена, если он просрочился
        await auth.UpdateToken();

        //request / отправка промпта. Чтобы исключить историю переписки - необходимо в методе указать false для аргумента UseHistory (по умолчанию UseHistory = true)
        var result = await completion.SendRequest(auth.LastResponse.GigaChatAuthorizationResponse?.AccessToken, prompt);

        if (result.RequestSuccessed)
        {
            Console.WriteLine(result.GigaChatCompletionResponse.Choices.LastOrDefault().Message.Content);
        }
        else
        {
            Console.WriteLine(result.ErrorTextIfFailed);
        }
    }
}
else
{
    Console.WriteLine(authResult.ErrorTextIfFailed);
}

Important!

Before using you should execute 3 steps:

  1. Registred in https://developers.sber.ru/ to get authenticated key that used for authorization. Generate auth code in personal account using button "Generate new Secret Code"

    image

  2. Install certificates in OS. Information here: https://developers.sber.ru/docs/ru/gigachat/certificates

  3. Access token lives only 30 mins. So use method UpdateToken() before sending request prompt

   auth.UpdateToken();

UPDATES

V 1.0.5 - Now you can set reserveTime parameter when call Authorization.Update() method. It allows to update token before it expired. For example Authorization.Update() method can be called a millisecond before token ends. So just set reserveTime = 1 minute to update token if it expires less then 1 minute.

await auth.UpdateToken(reserveTime: new TimeSpan(0, 1, 0));

V 1.0.7 - Add parameter maxTokens to completions settings (thanks to Amr0x64)

CompletionSettings settings = new CompletionSettings("GigaChat:latest", 2, null, 4, 1024);

It is the first version of dll that i create for self using. Then it will be updated as needed. Welcome if you can help to upgrade this library :)

gigachatadapter's People

Contributors

rennn avatar amr0x64 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.