forked from Portkey-AI/terraform-provider-portkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
2253 lines (1910 loc) · 79.2 KB
/
Copy pathclient.go
File metadata and controls
2253 lines (1910 loc) · 79.2 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// JSONNull is a pre-encoded JSON null value for clearing fields via the API.
// Use this with json.RawMessage fields to explicitly send "field": null.
var JSONNull = json.RawMessage("null")
// Client manages communication with the Portkey Admin API
type Client struct {
BaseURL string
APIKey string
HTTPClient *http.Client
}
// NewClient creates a new Portkey API client
func NewClient(baseURL, apiKey string) (*Client, error) {
if baseURL == "" {
return nil, fmt.Errorf("base URL cannot be empty")
}
if apiKey == "" {
return nil, fmt.Errorf("API key cannot be empty")
}
return &Client{
BaseURL: baseURL,
APIKey: apiKey,
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
}, nil
}
// doRequest performs an HTTP request
func (c *Client) doRequest(ctx context.Context, method, path string, body interface{}) ([]byte, error) {
var reqBody io.Reader
if body != nil {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("error marshaling request body: %w", err)
}
reqBody = bytes.NewBuffer(jsonBody)
}
url := c.BaseURL + path
req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-portkey-api-key", c.APIKey)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(respBody))
}
return respBody, nil
}
// WorkspaceDefaults represents the defaults configuration for a workspace
type WorkspaceDefaults struct {
Metadata map[string]string `json:"metadata,omitempty"`
}
// Workspace represents a Portkey workspace
type Workspace struct {
ID string `json:"id"`
Slug string `json:"slug,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Defaults *WorkspaceDefaults `json:"defaults,omitempty"`
RateLimits []IntegrationWorkspaceRateLimits `json:"rate_limits,omitempty"`
UsageLimits []IntegrationWorkspaceUsageLimits `json:"usage_limits,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"last_updated_at"`
}
// CreateWorkspaceRequest represents the request to create a workspace
type CreateWorkspaceRequest struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Defaults *WorkspaceDefaults `json:"defaults,omitempty"`
RateLimits []IntegrationWorkspaceRateLimits `json:"rate_limits,omitempty"`
UsageLimits []IntegrationWorkspaceUsageLimits `json:"usage_limits,omitempty"`
}
// UpdateWorkspaceRequest represents the request to update a workspace.
// UsageLimits and RateLimits use json.RawMessage for three-state semantics:
// - nil: field omitted from JSON (no change to existing limits)
// - client.JSONNull: sends "usage_limits": null (clears limits)
// - marshaled JSON: sends the new limits array
type UpdateWorkspaceRequest struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Defaults *WorkspaceDefaults `json:"defaults,omitempty"`
RateLimits json.RawMessage `json:"rate_limits,omitempty"`
UsageLimits json.RawMessage `json:"usage_limits,omitempty"`
}
// CreateWorkspace creates a new workspace
func (c *Client) CreateWorkspace(ctx context.Context, req CreateWorkspaceRequest) (*Workspace, error) {
respBody, err := c.doRequest(ctx, http.MethodPost, "/admin/workspaces", req)
if err != nil {
return nil, err
}
var workspace Workspace
if err := json.Unmarshal(respBody, &workspace); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &workspace, nil
}
// GetWorkspace retrieves a workspace by ID
func (c *Client) GetWorkspace(ctx context.Context, id string) (*Workspace, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/workspaces/"+id, nil)
if err != nil {
return nil, err
}
var workspace Workspace
if err := json.Unmarshal(respBody, &workspace); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &workspace, nil
}
// ListWorkspaces retrieves all workspaces
func (c *Client) ListWorkspaces(ctx context.Context) ([]Workspace, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/workspaces", nil)
if err != nil {
return nil, err
}
var response struct {
Data []Workspace `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// UpdateWorkspace updates a workspace
func (c *Client) UpdateWorkspace(ctx context.Context, id string, req UpdateWorkspaceRequest) (*Workspace, error) {
_, err := c.doRequest(ctx, http.MethodPut, "/admin/workspaces/"+id, req)
if err != nil {
return nil, err
}
// Fetch updated workspace details since update returns empty response
workspace, err := c.GetWorkspace(ctx, id)
if err != nil {
return nil, fmt.Errorf("workspace updated but failed to retrieve details: %w", err)
}
return workspace, nil
}
// DeleteWorkspaceRequest represents the request to delete a workspace
type DeleteWorkspaceRequest struct {
Name string `json:"name"`
ForceDelete bool `json:"force_delete,omitempty"`
}
// DeleteWorkspace deletes a workspace
func (c *Client) DeleteWorkspace(ctx context.Context, id string, name string) error {
req := DeleteWorkspaceRequest{
Name: name,
}
_, err := c.doRequest(ctx, http.MethodDelete, "/admin/workspaces/"+id, req)
return err
}
// User represents a Portkey user
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Role string `json:"role"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// GetUser retrieves a user by ID
func (c *Client) GetUser(ctx context.Context, id string) (*User, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/users/"+id, nil)
if err != nil {
return nil, err
}
var user User
if err := json.Unmarshal(respBody, &user); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &user, nil
}
// ListUsers retrieves all users
func (c *Client) ListUsers(ctx context.Context) ([]User, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/users", nil)
if err != nil {
return nil, err
}
var response struct {
Data []User `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// UpdateUserRequest represents the request to update a user
type UpdateUserRequest struct {
Role string `json:"role,omitempty"`
}
// UpdateUser updates a user
func (c *Client) UpdateUser(ctx context.Context, id string, req UpdateUserRequest) (*User, error) {
respBody, err := c.doRequest(ctx, http.MethodPut, "/admin/users/"+id, req)
if err != nil {
return nil, err
}
var user User
if err := json.Unmarshal(respBody, &user); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &user, nil
}
// DeleteUser removes a user
func (c *Client) DeleteUser(ctx context.Context, id string) error {
_, err := c.doRequest(ctx, http.MethodDelete, "/admin/users/"+id, nil)
return err
}
// WorkspaceMember represents a workspace member
type WorkspaceMember struct {
ID string `json:"id"`
UserID string `json:"user_id,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
Role string `json:"role"`
Email string `json:"email,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// normalizeWorkspaceMember ensures consistent field values
func normalizeWorkspaceMember(member *WorkspaceMember) {
// If ID is not set, use UserID
if member.ID == "" && member.UserID != "" {
member.ID = member.UserID
}
// Strip "ws-" prefix from role if present
member.Role = strings.TrimPrefix(member.Role, "ws-")
}
// workspaceUserItem represents a user in the add users request
type workspaceUserItem struct {
ID string `json:"id"`
Role string `json:"role"`
}
// addWorkspaceUsersRequest represents the request to add users to a workspace
type addWorkspaceUsersRequest struct {
Users []workspaceUserItem `json:"users"`
}
// AddWorkspaceMemberRequest represents the request to add a workspace member
type AddWorkspaceMemberRequest struct {
UserID string `json:"user_id"`
Role string `json:"role"`
}
// AddWorkspaceMember adds a member to a workspace
func (c *Client) AddWorkspaceMember(ctx context.Context, workspaceID string, req AddWorkspaceMemberRequest) (*WorkspaceMember, error) {
// The API expects { users: [{ id, role }] } format
addReq := addWorkspaceUsersRequest{
Users: []workspaceUserItem{
{
ID: req.UserID,
Role: req.Role,
},
},
}
path := fmt.Sprintf("/admin/workspaces/%s/users", workspaceID)
_, err := c.doRequest(ctx, http.MethodPost, path, addReq)
if err != nil {
return nil, err
}
// The add endpoint doesn't return member details, so we need to fetch them
member, err := c.GetWorkspaceMember(ctx, workspaceID, req.UserID)
if err != nil {
return nil, fmt.Errorf("user added but failed to retrieve details: %w", err)
}
return member, nil
}
// GetWorkspaceMember retrieves a workspace member
func (c *Client) GetWorkspaceMember(ctx context.Context, workspaceID, userID string) (*WorkspaceMember, error) {
path := fmt.Sprintf("/admin/workspaces/%s/users/%s", workspaceID, userID)
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
var member WorkspaceMember
if err := json.Unmarshal(respBody, &member); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
// API getMember endpoint doesn't return id field, use the queried userID
if member.ID == "" {
member.ID = userID
}
normalizeWorkspaceMember(&member)
return &member, nil
}
// ListWorkspaceMembers retrieves all members of a workspace
func (c *Client) ListWorkspaceMembers(ctx context.Context, workspaceID string) ([]WorkspaceMember, error) {
path := fmt.Sprintf("/admin/workspaces/%s/users", workspaceID)
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
var response struct {
Data []WorkspaceMember `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
// Normalize all members
for i := range response.Data {
normalizeWorkspaceMember(&response.Data[i])
}
return response.Data, nil
}
// UpdateWorkspaceMemberRequest represents the request to update a workspace member
type UpdateWorkspaceMemberRequest struct {
Role string `json:"role"`
}
// UpdateWorkspaceMember updates a workspace member's role
func (c *Client) UpdateWorkspaceMember(ctx context.Context, workspaceID, userID string, req UpdateWorkspaceMemberRequest) (*WorkspaceMember, error) {
path := fmt.Sprintf("/admin/workspaces/%s/users/%s", workspaceID, userID)
_, err := c.doRequest(ctx, http.MethodPut, path, req)
if err != nil {
return nil, err
}
// Fetch updated member details
member, err := c.GetWorkspaceMember(ctx, workspaceID, userID)
if err != nil {
return nil, fmt.Errorf("role updated but failed to retrieve details: %w", err)
}
return member, nil
}
// RemoveWorkspaceMember removes a member from a workspace
func (c *Client) RemoveWorkspaceMember(ctx context.Context, workspaceID, userID string) error {
path := fmt.Sprintf("/admin/workspaces/%s/users/%s", workspaceID, userID)
_, err := c.doRequest(ctx, http.MethodDelete, path, nil)
return err
}
// UserInvite represents a user invitation
type UserInvite struct {
ID string `json:"id"`
Email string `json:"email"`
Role string `json:"role"`
Status string `json:"status"`
Workspaces []WorkspaceInviteDetails `json:"workspaces,omitempty"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
// WorkspaceInviteDetails represents workspace details in an invitation
type WorkspaceInviteDetails struct {
ID string `json:"id"`
Role string `json:"role"`
}
// CreateUserInviteRequest represents the request to invite a user
type CreateUserInviteRequest struct {
Email string `json:"email"`
Role string `json:"role"`
Workspaces []WorkspaceInviteDetails `json:"workspaces,omitempty"`
WorkspaceAPIKeyDetails *APIKeyDetails `json:"workspace_api_key_details,omitempty"`
}
// APIKeyDetails represents API key configuration for user invites
type APIKeyDetails struct {
Scopes []string `json:"scopes"`
}
// InviteUser sends an invitation to a user
func (c *Client) InviteUser(ctx context.Context, req CreateUserInviteRequest) (*UserInvite, error) {
respBody, err := c.doRequest(ctx, http.MethodPost, "/admin/users/invites", req)
if err != nil {
return nil, err
}
var invite UserInvite
if err := json.Unmarshal(respBody, &invite); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &invite, nil
}
// GetUserInvite retrieves a user invitation by ID
func (c *Client) GetUserInvite(ctx context.Context, id string) (*UserInvite, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/users/invites/"+id, nil)
if err != nil {
return nil, err
}
var invite UserInvite
if err := json.Unmarshal(respBody, &invite); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &invite, nil
}
// ListUserInvites retrieves all user invitations
func (c *Client) ListUserInvites(ctx context.Context) ([]UserInvite, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/admin/users/invites", nil)
if err != nil {
return nil, err
}
var response struct {
Data []UserInvite `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// DeleteUserInvite deletes a user invitation
func (c *Client) DeleteUserInvite(ctx context.Context, id string) error {
_, err := c.doRequest(ctx, http.MethodDelete, "/admin/users/invites/"+id, nil)
return err
}
// Integration represents a Portkey integration (connection to an AI provider)
type Integration struct {
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
AIProviderID string `json:"ai_provider_id"`
Description string `json:"description,omitempty"`
Status string `json:"status"`
MaskedKey string `json:"masked_key,omitempty"`
Configurations map[string]interface{} `json:"configurations,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"last_updated_at"`
}
// CreateIntegrationRequest represents the request to create an integration
type CreateIntegrationRequest struct {
Name string `json:"name"`
Slug string `json:"slug,omitempty"`
AIProviderID string `json:"ai_provider_id"`
Key string `json:"key,omitempty"`
Description string `json:"description,omitempty"`
Configurations map[string]interface{} `json:"configurations,omitempty"`
}
// UpdateIntegrationRequest represents the request to update an integration
type UpdateIntegrationRequest struct {
Name string `json:"name,omitempty"`
Key string `json:"key,omitempty"`
Description string `json:"description,omitempty"`
Configurations map[string]interface{} `json:"configurations,omitempty"`
}
// CreateIntegrationResponse represents the response from creating an integration
type CreateIntegrationResponse struct {
ID string `json:"id"`
Slug string `json:"slug"`
}
// CreateIntegration creates a new integration
func (c *Client) CreateIntegration(ctx context.Context, req CreateIntegrationRequest) (*CreateIntegrationResponse, error) {
respBody, err := c.doRequest(ctx, http.MethodPost, "/integrations", req)
if err != nil {
return nil, err
}
var response CreateIntegrationResponse
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &response, nil
}
// GetIntegration retrieves an integration by slug
func (c *Client) GetIntegration(ctx context.Context, slug string) (*Integration, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/integrations/"+slug, nil)
if err != nil {
return nil, err
}
var integration Integration
if err := json.Unmarshal(respBody, &integration); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &integration, nil
}
// ListIntegrations retrieves all integrations
func (c *Client) ListIntegrations(ctx context.Context) ([]Integration, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/integrations", nil)
if err != nil {
return nil, err
}
var response struct {
Data []Integration `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// UpdateIntegration updates an integration
func (c *Client) UpdateIntegration(ctx context.Context, slug string, req UpdateIntegrationRequest) (*Integration, error) {
_, err := c.doRequest(ctx, http.MethodPut, "/integrations/"+slug, req)
if err != nil {
return nil, err
}
// Fetch updated integration details
return c.GetIntegration(ctx, slug)
}
// DeleteIntegration deletes an integration
func (c *Client) DeleteIntegration(ctx context.Context, slug string) error {
_, err := c.doRequest(ctx, http.MethodDelete, "/integrations/"+slug, nil)
return err
}
// APIKeyDefaults represents the defaults configuration for an API key
type APIKeyDefaults struct {
Metadata map[string]string `json:"metadata,omitempty"`
ConfigID string `json:"config_id,omitempty"`
AllowConfigOverride *bool `json:"allow_config_override,omitempty"`
}
// APIKey represents a Portkey API key
type APIKey struct {
ID string `json:"id"`
Key string `json:"key,omitempty"` // Only returned on creation
Name string `json:"name"`
Description string `json:"description,omitempty"`
Type string `json:"type"` // organisation-service, workspace-service, workspace-user
OrganisationID string `json:"organisation_id"`
WorkspaceID string `json:"workspace_id,omitempty"`
UserID string `json:"user_id,omitempty"`
Status string `json:"status"`
CreationMode string `json:"creation_mode,omitempty"`
RateLimits []RateLimit `json:"rate_limits,omitempty"`
UsageLimits *UsageLimits `json:"usage_limits,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Defaults *APIKeyDefaults `json:"defaults,omitempty"`
AlertEmails []string `json:"alert_emails,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"last_updated_at"`
}
// RateLimit represents a rate limit configuration
type RateLimit struct {
Type string `json:"type"` // requests
Unit string `json:"unit"` // rpm, rpd
Value int `json:"value"`
}
// UsageLimits represents usage limit configuration for API keys.
// Uses the same field names as workspace usage limits (credit_limit, periodic_reset, alert_threshold).
type UsageLimits struct {
CreditLimit *int `json:"credit_limit,omitempty"`
AlertThreshold *int `json:"alert_threshold,omitempty"`
PeriodicReset string `json:"periodic_reset,omitempty"` // monthly, weekly
}
// CreateAPIKeyRequest represents the request to create an API key
type CreateAPIKeyRequest struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
UserID string `json:"user_id,omitempty"` // Required for user sub-type
RateLimits []RateLimit `json:"rate_limits,omitempty"`
UsageLimits *UsageLimits `json:"usage_limits,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Defaults *APIKeyDefaults `json:"defaults,omitempty"`
AlertEmails []string `json:"alert_emails,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
}
// CreateAPIKeyResponse represents the response from creating an API key
type CreateAPIKeyResponse struct {
ID string `json:"id"`
Key string `json:"key"`
Object string `json:"object"`
}
// UpdateAPIKeyRequest represents the request to update an API key.
// UsageLimits and RateLimits use json.RawMessage for three-state semantics:
// - nil: field omitted from JSON (no change to existing limits)
// - client.JSONNull: sends "usage_limits": null (clears limits)
// - marshaled JSON: sends the new limits object/array
type UpdateAPIKeyRequest struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
RateLimits json.RawMessage `json:"rate_limits,omitempty"`
UsageLimits json.RawMessage `json:"usage_limits,omitempty"`
Scopes []string `json:"scopes,omitempty"`
Defaults *APIKeyDefaults `json:"defaults,omitempty"`
AlertEmails []string `json:"alert_emails,omitempty"`
}
// CreateAPIKey creates a new API key
// keyType: "organisation" or "workspace"
// subType: "service" or "user"
func (c *Client) CreateAPIKey(ctx context.Context, keyType, subType string, req CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) {
path := fmt.Sprintf("/api-keys/%s/%s", keyType, subType)
respBody, err := c.doRequest(ctx, http.MethodPost, path, req)
if err != nil {
return nil, err
}
var response CreateAPIKeyResponse
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &response, nil
}
// GetAPIKey retrieves an API key by ID
func (c *Client) GetAPIKey(ctx context.Context, id string) (*APIKey, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/api-keys/"+id, nil)
if err != nil {
return nil, err
}
var apiKey APIKey
if err := json.Unmarshal(respBody, &apiKey); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &apiKey, nil
}
// ListAPIKeys retrieves all API keys
func (c *Client) ListAPIKeys(ctx context.Context, workspaceID string) ([]APIKey, error) {
path := "/api-keys"
if workspaceID != "" {
path = fmt.Sprintf("/api-keys?workspace_id=%s", workspaceID)
}
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
var response struct {
Data []APIKey `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// UpdateAPIKey updates an API key
func (c *Client) UpdateAPIKey(ctx context.Context, id string, req UpdateAPIKeyRequest) (*APIKey, error) {
_, err := c.doRequest(ctx, http.MethodPut, "/api-keys/"+id, req)
if err != nil {
return nil, err
}
// Fetch updated API key details
return c.GetAPIKey(ctx, id)
}
// DeleteAPIKey deletes an API key
func (c *Client) DeleteAPIKey(ctx context.Context, id string) error {
_, err := c.doRequest(ctx, http.MethodDelete, "/api-keys/"+id, nil)
return err
}
// Provider represents a Portkey provider (virtual key)
type Provider struct {
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
AIProviderID string `json:"ai_provider_name,omitempty"`
IntegrationID string `json:"integration_id,omitempty"`
WorkspaceID string `json:"workspace_id,omitempty"`
Status string `json:"status"`
Note string `json:"note,omitempty"`
ModelConfig map[string]interface{} `json:"model_config,omitempty"`
RateLimits []RateLimit `json:"rate_limits,omitempty"`
UsageLimits *UsageLimits `json:"usage_limits,omitempty"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// CreateProviderRequest represents the request to create a provider
type CreateProviderRequest struct {
Name string `json:"name"`
Slug string `json:"slug,omitempty"`
WorkspaceID string `json:"workspace_id"`
IntegrationID string `json:"integration_id"`
Note string `json:"note,omitempty"`
ModelConfig map[string]interface{} `json:"model_config,omitempty"`
RateLimits []RateLimit `json:"rate_limits,omitempty"`
UsageLimits *UsageLimits `json:"usage_limits,omitempty"`
}
// CreateProviderResponse represents the response from creating a provider
type CreateProviderResponse struct {
ID string `json:"id"`
Slug string `json:"slug"`
Object string `json:"object"`
}
// UpdateProviderRequest represents the request to update a provider
type UpdateProviderRequest struct {
Name string `json:"name,omitempty"`
WorkspaceID string `json:"workspace_id"`
Note string `json:"note,omitempty"`
ModelConfig map[string]interface{} `json:"model_config,omitempty"`
RateLimits []RateLimit `json:"rate_limits,omitempty"`
UsageLimits *UsageLimits `json:"usage_limits,omitempty"`
}
// CreateProvider creates a new provider
func (c *Client) CreateProvider(ctx context.Context, req CreateProviderRequest) (*CreateProviderResponse, error) {
respBody, err := c.doRequest(ctx, http.MethodPost, "/providers", req)
if err != nil {
return nil, err
}
var response CreateProviderResponse
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &response, nil
}
// GetProvider retrieves a provider by ID
func (c *Client) GetProvider(ctx context.Context, id, workspaceID string) (*Provider, error) {
path := fmt.Sprintf("/providers/%s?workspace_id=%s", id, workspaceID)
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
var provider Provider
if err := json.Unmarshal(respBody, &provider); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &provider, nil
}
// ListProviders retrieves all providers for a workspace
func (c *Client) ListProviders(ctx context.Context, workspaceID string) ([]Provider, error) {
path := "/providers"
if workspaceID != "" {
path = fmt.Sprintf("/providers?workspace_id=%s", workspaceID)
}
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}
var response struct {
Data []Provider `json:"data"`
}
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return response.Data, nil
}
// UpdateProvider updates a provider
func (c *Client) UpdateProvider(ctx context.Context, id string, req UpdateProviderRequest) (*Provider, error) {
_, err := c.doRequest(ctx, http.MethodPut, "/providers/"+id, req)
if err != nil {
return nil, err
}
// Fetch updated provider details
return c.GetProvider(ctx, id, req.WorkspaceID)
}
// DeleteProvider deletes a provider
func (c *Client) DeleteProvider(ctx context.Context, id, workspaceID string) error {
path := fmt.Sprintf("/providers/%s?workspace_id=%s", id, workspaceID)
_, err := c.doRequest(ctx, http.MethodDelete, path, nil)
return err
}
// Config represents a Portkey config
type Config struct {
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Config map[string]interface{} `json:"-"` // Parsed config map
ConfigRaw string `json:"-"` // Raw config string
WorkspaceID string `json:"workspace_id"`
OrganisationID string `json:"organisation_id"`
IsDefault int `json:"is_default"`
Status string `json:"status"`
OwnerID string `json:"owner_id,omitempty"`
UpdatedBy string `json:"updated_by,omitempty"`
Format string `json:"format,omitempty"`
Type string `json:"type,omitempty"`
VersionID string `json:"version_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"last_updated_at"`
}
// CreateConfigRequest represents the request to create a config
type CreateConfigRequest struct {
Name string `json:"name"`
Config map[string]interface{} `json:"config"`
WorkspaceID string `json:"workspace_id,omitempty"`
IsDefault *int `json:"isDefault,omitempty"`
}
// CreateConfigResponse represents the response from creating a config
type CreateConfigResponse struct {
ID string `json:"id"`
Slug string `json:"slug"`
VersionID string `json:"version_id"`
}
// UpdateConfigRequest represents the request to update a config
type UpdateConfigRequest struct {
Name string `json:"name,omitempty"`
Config map[string]interface{} `json:"config,omitempty"`
Status string `json:"status,omitempty"`
}
// UpdateConfigResponse represents the response from updating a config
type UpdateConfigResponse struct {
VersionID string `json:"version_id"`
}
// CreateConfig creates a new config
func (c *Client) CreateConfig(ctx context.Context, req CreateConfigRequest) (*CreateConfigResponse, error) {
respBody, err := c.doRequest(ctx, http.MethodPost, "/configs", req)
if err != nil {
return nil, err
}
var response CreateConfigResponse
if err := json.Unmarshal(respBody, &response); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
return &response, nil
}
// configAPIResponse is used for unmarshaling API responses with flexible config field
type configAPIResponse struct {
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Config interface{} `json:"config"` // Can be string or object
WorkspaceID string `json:"workspace_id"`
OrganisationID string `json:"organisation_id"`
IsDefault int `json:"is_default"`
Status string `json:"status"`
OwnerID string `json:"owner_id,omitempty"`
UpdatedBy string `json:"updated_by,omitempty"`
Format string `json:"format,omitempty"`
Type string `json:"type,omitempty"`
VersionID string `json:"version_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"last_updated_at"`
}
// GetConfig retrieves a config by slug
func (c *Client) GetConfig(ctx context.Context, slug string) (*Config, error) {
respBody, err := c.doRequest(ctx, http.MethodGet, "/configs/"+slug, nil)
if err != nil {
return nil, err
}
var apiResp configAPIResponse
if err := json.Unmarshal(respBody, &apiResp); err != nil {
return nil, fmt.Errorf("error unmarshaling response: %w", err)
}
config := &Config{
ID: apiResp.ID,
Slug: apiResp.Slug,
Name: apiResp.Name,
WorkspaceID: apiResp.WorkspaceID,
OrganisationID: apiResp.OrganisationID,
IsDefault: apiResp.IsDefault,
Status: apiResp.Status,
OwnerID: apiResp.OwnerID,
UpdatedBy: apiResp.UpdatedBy,
Format: apiResp.Format,
Type: apiResp.Type,
VersionID: apiResp.VersionID,
CreatedAt: apiResp.CreatedAt,
UpdatedAt: apiResp.UpdatedAt,
}
// Handle config field which can be a string (JSON) or object
switch v := apiResp.Config.(type) {
case string:
config.ConfigRaw = v
// Parse string to map
var configMap map[string]interface{}
if err := json.Unmarshal([]byte(v), &configMap); err == nil {
config.Config = configMap
}
case map[string]interface{}:
config.Config = v
// Convert to string
if configBytes, err := json.Marshal(v); err == nil {
config.ConfigRaw = string(configBytes)
}
}
return config, nil
}
// ListConfigs retrieves all configs
func (c *Client) ListConfigs(ctx context.Context, workspaceID string) ([]Config, error) {
path := "/configs"
if workspaceID != "" {
path = fmt.Sprintf("/configs?workspace_id=%s", workspaceID)
}
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
if err != nil {
return nil, err
}