Repository navigation
Expand file tree
/
Copy pathOpenAI.GigaChat.pas
More file actions
83 lines (71 loc) · 2.28 KB
/
Copy pathOpenAI.GigaChat.pas
File metadata and controls
83 lines (71 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
unit OpenAI.GigaChat;
interface
uses
System.SysUtils, System.Classes, OpenAI.API;
type
TApiPrepareGigaChat = class(TInterfacedObject, IAPIPrepare)
const
SBER_GIGACHAT_OAUTH = 'https://ngw.devices.sberbank.ru:9443/api/v2/oauth';
SBER_GIGACHAT_OAUTH_SCOPE = 'GIGACHAT_API_PERS';
private
FClientID: string;
FAuthorizationKey: string;
FAccessToken: string;
FExpiresAt: TDateTime;
function IsValidToken: Boolean;
procedure UpdateToken(API: TOpenAIAPI);
public
procedure PrepareQuery(API: TOpenAIAPI);
constructor Create(const ClientID, AuthorizationKey: string); reintroduce;
end;
implementation
uses
System.Net.URLClient, System.JSON, System.DateUtils, System.NetConsts,
System.Net.HttpClient;
{ TApiPrepareGigaChat }
constructor TApiPrepareGigaChat.Create(const ClientID, AuthorizationKey: string);
begin
inherited Create;
FClientID := ClientID;
FAuthorizationKey := AuthorizationKey;
end;
function TApiPrepareGigaChat.IsValidToken: Boolean;
begin
Result := (not FAccessToken.IsEmpty) and (FExpiresAt > Now);
end;
procedure TApiPrepareGigaChat.PrepareQuery(API: TOpenAIAPI);
begin
if not IsValidToken then
UpdateToken(API);
API.Token := FAccessToken;
end;
procedure TApiPrepareGigaChat.UpdateToken(API: TOpenAIAPI);
begin
var Client := API.GetClient;
try
Client.Accept := 'application/json';
Client.CustomHeaders['RqUID'] := FClientID;
Client.CustomHeaders['Authorization'] := 'Basic ' + FAuthorizationKey;
var Content := TStringList.Create;
try
Content.AddPair('scope', SBER_GIGACHAT_OAUTH_SCOPE);
var Response := Client.Post(SBER_GIGACHAT_OAUTH, Content);
if Response.StatusCode <> 200 then
raise OpenAIPrepareException.Create(Response.StatusText, '', '', Response.StatusCode);
var JSON := TJSONObject.ParseJSONValue(Response.ContentAsString);
try
FAccessToken := JSON.GetValue<string>('access_token', '');
FExpiresAt := UnixToDateTime(JSON.GetValue<Int64>('expires_at', 0) div MSecsPerSec, False);
if not IsValidToken then
raise OpenAIPrepareException.Create('Token receipt error', '', '', Response.StatusCode);
finally
JSON.Free;
end;
finally
Content.Free;
end;
finally
Client.Free;
end;
end;
end.