-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkb.go
More file actions
358 lines (325 loc) · 10.6 KB
/
Copy pathkb.go
File metadata and controls
358 lines (325 loc) · 10.6 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
package connector
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
)
// The kb/* connectors are thin pgvector helpers over a Postgres database (the
// step's `credential` is a postgres credential). They compose with ai/embed:
// take the pgvector literal from ai/embed's `output.vector` / `output.vectors`
// and store or query it, hiding the ::vector casts, distance operators, and
// multi-row unnest inserts. They do not manage schema — create the table
// yourself (see the RAG guide / rag-kb-schema.sql).
// kbIdentRe matches a safe SQL identifier, optionally schema-qualified. Table
// and column names are interpolated into SQL (they cannot be bound as
// parameters), so every identifier is validated against this before use.
var kbIdentRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$`)
const (
kbDefaultContentColumn = "content"
kbDefaultEmbeddingColumn = "embedding"
kbDefaultMetadataColumn = "metadata"
kbDefaultTopK = 5
kbMaxTopK = 1000
// kbConnectTimeout bounds the Postgres connection handshake so a stalled
// server can't hang a step that has no timeout of its own. It only shortens
// an existing deadline, never extends one.
kbConnectTimeout = 15 * time.Second
)
// kbIdentParam reads an identifier param, applies a default when absent, and
// validates it to prevent SQL injection through table/column names.
func kbIdentParam(params map[string]any, key, def string) (string, error) {
v, ok := params[key].(string)
if !ok || v == "" {
v = def
}
if v == "" {
return "", fmt.Errorf("%s is required", key)
}
if !kbIdentRe.MatchString(v) {
return "", fmt.Errorf("%s %q is not a valid SQL identifier", key, v)
}
return v, nil
}
// kbStrings normalizes a "single or many" text param: `singleKey` (a string) or
// `manyKey` (an array of strings). Exactly one must be present.
func kbStrings(params map[string]any, singleKey, manyKey string) ([]string, error) {
single, hasSingle := params[singleKey]
many, hasMany := params[manyKey]
if hasSingle == hasMany { // both or neither
return nil, fmt.Errorf("exactly one of %s or %s is required", singleKey, manyKey)
}
if hasSingle {
s, ok := single.(string)
if !ok || s == "" {
return nil, fmt.Errorf("%s must be a non-empty string", singleKey)
}
return []string{s}, nil
}
switch v := many.(type) {
case []string:
if len(v) == 0 {
return nil, fmt.Errorf("%s must not be empty", manyKey)
}
return v, nil
case []any:
out := make([]string, 0, len(v))
for i, item := range v {
s, ok := item.(string)
if !ok {
return nil, fmt.Errorf("%s[%d] must be a string, got %T", manyKey, i, item)
}
out = append(out, s)
}
if len(out) == 0 {
return nil, fmt.Errorf("%s must not be empty", manyKey)
}
return out, nil
default:
return nil, fmt.Errorf("%s must be an array of strings, got %T", manyKey, many)
}
}
// kbMetadata normalizes the optional metadata param into JSON strings aligned
// with the rows. A single `metadata` object is broadcast to every row (handy
// for chunked ingest that shares a title/source); `metadatas` must match the
// row count one-to-one. Returns present=false when no metadata param is set.
func kbMetadata(params map[string]any, rows int) (jsons []string, present bool, err error) {
single, hasSingle := params["metadata"]
many, hasMany := params["metadatas"]
if !hasSingle && !hasMany {
return nil, false, nil
}
if hasSingle && hasMany {
return nil, false, fmt.Errorf("set only one of metadata or metadatas")
}
if hasSingle {
b, mErr := json.Marshal(single)
if mErr != nil {
return nil, false, fmt.Errorf("marshaling metadata: %w", mErr)
}
out := make([]string, rows)
for i := range out {
out[i] = string(b)
}
return out, true, nil
}
arr, ok := many.([]any)
if !ok {
return nil, false, fmt.Errorf("metadatas must be an array of objects, got %T", many)
}
if len(arr) != rows {
return nil, false, fmt.Errorf("metadatas count %d does not match content count %d", len(arr), rows)
}
out := make([]string, len(arr))
for i, o := range arr {
b, mErr := json.Marshal(o)
if mErr != nil {
return nil, false, fmt.Errorf("marshaling metadatas[%d]: %w", i, mErr)
}
out[i] = string(b)
}
return out, true, nil
}
// prepareUpsert validates params and builds the INSERT ... SELECT unnest(...)
// statement plus its args. Pure (no DB) so it is fully unit-testable.
func prepareUpsert(params map[string]any) (string, []any, error) {
table, err := kbIdentParam(params, "table", "")
if err != nil {
return "", nil, err
}
contentCol, err := kbIdentParam(params, "content_column", kbDefaultContentColumn)
if err != nil {
return "", nil, err
}
embCol, err := kbIdentParam(params, "embedding_column", kbDefaultEmbeddingColumn)
if err != nil {
return "", nil, err
}
metaCol, err := kbIdentParam(params, "metadata_column", kbDefaultMetadataColumn)
if err != nil {
return "", nil, err
}
contents, err := kbStrings(params, "content", "contents")
if err != nil {
return "", nil, err
}
vectors, err := kbStrings(params, "vector", "vectors")
if err != nil {
return "", nil, err
}
if len(vectors) != len(contents) {
return "", nil, fmt.Errorf("vector count %d does not match content count %d", len(vectors), len(contents))
}
metas, hasMeta, err := kbMetadata(params, len(contents))
if err != nil {
return "", nil, err
}
var conflict string
if ct, ok := params["conflict_target"].(string); ok && ct != "" {
// Accept a single column or a comma-separated list (composite key),
// validating each part as an identifier.
parts := strings.Split(ct, ",")
for i, p := range parts {
p = strings.TrimSpace(p)
if !kbIdentRe.MatchString(p) {
return "", nil, fmt.Errorf("conflict_target %q is not a valid SQL identifier", ct)
}
parts[i] = p
}
conflict = fmt.Sprintf(" ON CONFLICT (%s) DO NOTHING", strings.Join(parts, ", "))
}
var sb strings.Builder
args := []any{contents, vectors}
if hasMeta {
fmt.Fprintf(&sb,
"INSERT INTO %s (%s, %s, %s) SELECT c, e::vector, m::jsonb FROM unnest($1::text[], $2::text[], $3::text[]) AS u(c, e, m)%s",
table, contentCol, embCol, metaCol, conflict)
args = append(args, metas)
} else {
fmt.Fprintf(&sb,
"INSERT INTO %s (%s, %s) SELECT c, e::vector FROM unnest($1::text[], $2::text[]) AS u(c, e)%s",
table, contentCol, embCol, conflict)
}
return sb.String(), args, nil
}
// kbDistanceOperator maps a metric name to its pgvector operator.
func kbDistanceOperator(metric string) (string, error) {
switch metric {
case "", "cosine":
return "<=>", nil
case "l2", "euclidean":
return "<->", nil
case "inner_product", "ip":
return "<#>", nil
default:
return "", fmt.Errorf("unknown metric %q (use cosine, l2/euclidean, or inner_product/ip)", metric)
}
}
// prepareQuery validates params and builds the nearest-neighbour SELECT plus
// its args ($1 = query vector). Pure (no DB) so it is fully unit-testable.
func prepareQuery(params map[string]any) (string, []any, error) {
table, err := kbIdentParam(params, "table", "")
if err != nil {
return "", nil, err
}
embCol, err := kbIdentParam(params, "embedding_column", kbDefaultEmbeddingColumn)
if err != nil {
return "", nil, err
}
vector, ok := params["vector"].(string)
if !ok || vector == "" {
return "", nil, fmt.Errorf("vector is required (a pgvector literal, e.g. from ai/embed output.vector)")
}
metric, _ := params["metric"].(string)
op, err := kbDistanceOperator(metric)
if err != nil {
return "", nil, err
}
topK := kbDefaultTopK
if v, ok := extractInt(params["top_k"]); ok {
if v <= 0 {
return "", nil, fmt.Errorf("top_k must be positive, got %d", v)
}
topK = v
}
if topK > kbMaxTopK {
topK = kbMaxTopK
}
// Columns to return: default to the content column; callers may request more.
var cols []string
if raw, ok := params["columns"]; ok {
list, lErr := kbStringList(raw)
if lErr != nil {
return "", nil, fmt.Errorf("columns: %w", lErr)
}
for _, c := range list {
if !kbIdentRe.MatchString(c) {
return "", nil, fmt.Errorf("column %q is not a valid SQL identifier", c)
}
}
cols = list
} else {
contentCol, cErr := kbIdentParam(params, "content_column", kbDefaultContentColumn)
if cErr != nil {
return "", nil, cErr
}
cols = []string{contentCol}
}
selectList := strings.Join(cols, ", ")
sql := fmt.Sprintf(
"SELECT %s, (%s %s $1::vector) AS distance FROM %s ORDER BY %s %s $1::vector LIMIT %s",
selectList, embCol, op, table, embCol, op, strconv.Itoa(topK))
return sql, []any{vector}, nil
}
func kbStringList(raw any) ([]string, error) {
switch v := raw.(type) {
case []string:
return v, nil
case []any:
out := make([]string, 0, len(v))
for i, item := range v {
s, ok := item.(string)
if !ok {
return nil, fmt.Errorf("[%d] must be a string, got %T", i, item)
}
out = append(out, s)
}
return out, nil
default:
return nil, fmt.Errorf("must be an array of strings, got %T", raw)
}
}
// KBUpsertConnector implements kb/upsert: store document text + embedding
// (and optional JSONB metadata) into a pgvector table, one or many rows.
type KBUpsertConnector struct{}
func (c *KBUpsertConnector) Execute(ctx context.Context, params map[string]any) (map[string]any, error) {
connURL, err := extractPostgresURL(params)
if err != nil {
return nil, fmt.Errorf("kb/upsert: %w", err)
}
query, args, err := prepareUpsert(params)
if err != nil {
return nil, fmt.Errorf("kb/upsert: %w", err)
}
connectCtx, cancel := context.WithTimeout(ctx, kbConnectTimeout)
conn, err := pgx.Connect(connectCtx, connURL)
cancel()
if err != nil {
return nil, fmt.Errorf("kb/upsert: connecting: %w", err)
}
defer conn.Close(ctx)
out, err := executeExec(ctx, conn, query, args)
if err != nil {
return nil, fmt.Errorf("kb/upsert: %w", err)
}
return out, nil
}
// KBQueryConnector implements kb/query: nearest-neighbour search over a
// pgvector table for a query embedding, returning the closest rows.
type KBQueryConnector struct{}
func (c *KBQueryConnector) Execute(ctx context.Context, params map[string]any) (map[string]any, error) {
connURL, err := extractPostgresURL(params)
if err != nil {
return nil, fmt.Errorf("kb/query: %w", err)
}
query, args, err := prepareQuery(params)
if err != nil {
return nil, fmt.Errorf("kb/query: %w", err)
}
connectCtx, cancel := context.WithTimeout(ctx, kbConnectTimeout)
conn, err := pgx.Connect(connectCtx, connURL)
cancel()
if err != nil {
return nil, fmt.Errorf("kb/query: connecting: %w", err)
}
defer conn.Close(ctx)
out, err := executeSelect(ctx, conn, query, args)
if err != nil {
return nil, fmt.Errorf("kb/query: %w", err)
}
return out, nil
}