-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
222 lines (188 loc) · 5.35 KB
/
client.go
File metadata and controls
222 lines (188 loc) · 5.35 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
package basegrid
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// BaseURL is the default API endpoint
const BaseURL = "https://basegrid-production.up.railway.app"
// MemoryMode controls how the SDK handles memory operations
type MemoryMode string
const (
MemoryModeAuto MemoryMode = "auto"
MemoryModeManual MemoryMode = "manual"
MemoryModeOff MemoryMode = "off"
)
// Client is the BaseGrid API client
type Client struct {
APIKey string
BaseURL string
HTTPClient *http.Client
MemoryMode MemoryMode
DefaultAgent string
sessionEvents []string
}
// Memory represents a stored memory
type Memory struct {
ID string `json:"id,omitempty"`
AgentID string `json:"agentId"`
Content string `json:"content"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Importance float64 `json:"importance,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
}
// SearchParams represents search query parameters
type SearchParams struct {
AgentID string `json:"agentId"`
Query string `json:"query"`
Limit int `json:"limit,omitempty"`
Threshold float64 `json:"threshold,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
// SearchResult represents a single search result
type SearchResult struct {
ID string `json:"id"`
Content string `json:"content"`
Similarity float64 `json:"similarity"`
Metadata map[string]interface{} `json:"metadata"`
CreatedAt time.Time `json:"createdAt"`
}
// searchResponse is the internal API response structure
type searchResponse struct {
Success bool `json:"success"`
Results []SearchResult `json:"results"`
}
// ClientOptions holds optional configuration for NewWithOptions
type ClientOptions struct {
BaseURL string
MemoryMode MemoryMode
DefaultAgent string
}
// New creates a new BaseGrid client with manual memory mode
func New(apiKey string) *Client {
return &Client{
APIKey: apiKey,
BaseURL: BaseURL,
HTTPClient: &http.Client{Timeout: 10 * time.Second},
MemoryMode: MemoryModeManual,
DefaultAgent: "default",
}
}
// NewWithOptions creates a new BaseGrid client with full configuration
func NewWithOptions(apiKey string, opts ClientOptions) *Client {
c := New(apiKey)
if opts.BaseURL != "" {
c.BaseURL = opts.BaseURL
}
if opts.MemoryMode != "" {
c.MemoryMode = opts.MemoryMode
}
if opts.DefaultAgent != "" {
c.DefaultAgent = opts.DefaultAgent
}
return c
}
// Add stores a new memory
func (c *Client) Add(mem Memory) (*Memory, error) {
if c.MemoryMode == MemoryModeOff {
return nil, nil
}
if c.MemoryMode == MemoryModeAuto {
preview := mem.Content
if len(preview) > 80 {
preview = preview[:80]
}
c.sessionEvents = append(c.sessionEvents, fmt.Sprintf(`Stored: "%s"`, preview))
}
body, err := json.Marshal(mem)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.BaseURL+"/v1/memories", bytes.NewBuffer(body))
if err != nil {
return nil, err
}
c.addHeaders(req)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("API error: %s", resp.Status)
}
var result struct {
Success bool `json:"success"`
Data Memory `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return &result.Data, nil
}
// Search retrieves relevant memories
func (c *Client) Search(params SearchParams) ([]SearchResult, error) {
if c.MemoryMode == MemoryModeOff {
return []SearchResult{}, nil
}
body, err := json.Marshal(params)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.BaseURL+"/v1/memories/search", bytes.NewBuffer(body))
if err != nil {
return nil, err
}
c.addHeaders(req)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("API error: %s", resp.Status)
}
var result searchResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
return result.Results, nil
}
// Recall surfaces relevant memories for a given context
func (c *Client) Recall(query string, agentId string) ([]SearchResult, error) {
if c.MemoryMode == MemoryModeOff {
return []SearchResult{}, nil
}
if agentId == "" {
agentId = c.DefaultAgent
}
return c.Search(SearchParams{AgentID: agentId, Query: query, Limit: 5})
}
// FlushSession stores a session summary and clears the event log (auto mode only)
func (c *Client) FlushSession() error {
if c.MemoryMode != MemoryModeAuto {
return nil
}
if len(c.sessionEvents) == 0 {
return nil
}
summary := "Session summary: " + strings.Join(c.sessionEvents, " | ")
_, err := c.Add(Memory{
AgentID: c.DefaultAgent,
Content: summary,
Importance: 0.8,
Metadata: map[string]interface{}{"type": "session_summary", "auto": true},
})
if err == nil {
c.sessionEvents = []string{}
}
return err
}
func (c *Client) addHeaders(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "basegrid-go/1.0.0")
}