Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
231 lines (193 loc) · 6.14 KB
/
Copy pathmain.go
File metadata and controls
231 lines (193 loc) · 6.14 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
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/streamcoreai/streamcore-cli/internal/chunker"
"github.com/streamcoreai/streamcore-cli/internal/embed"
"github.com/streamcoreai/streamcore-cli/internal/parser"
"github.com/streamcoreai/streamcore-cli/internal/schema"
"github.com/streamcoreai/streamcore-cli/internal/setup"
"github.com/streamcoreai/streamcore-cli/internal/store"
)
// version is stamped by goreleaser at build time; a `go build` from source
// leaves it as-is.
var version = "dev"
// Config matches the structure written by `streamcore-cli setup`.
type Config struct {
OpenAI OpenAIConfig `toml:"openai"`
RAG RAGConfig `toml:"rag"`
Pgvector PgvectorConfig `toml:"pgvector"`
Supabase SupabaseConfig `toml:"supabase"`
}
type OpenAIConfig struct {
APIKey string `toml:"api_key"`
}
type RAGConfig struct {
Provider string `toml:"provider"`
TopK int `toml:"top_k"`
EmbeddingModel string `toml:"embedding_model"`
}
type PgvectorConfig struct {
ConnectionString string `toml:"connection_string"`
Table string `toml:"table"`
}
type SupabaseConfig struct {
URL string `toml:"url"`
APIKey string `toml:"api_key"`
Table string `toml:"table"`
}
func main() {
log.SetFlags(0)
if len(os.Args) < 2 {
printUsage()
os.Exit(1)
}
switch os.Args[1] {
case "setup":
if err := setup.Run(); err != nil {
log.Fatalf("Setup failed: %v", err)
}
case "ingest":
runIngest(os.Args[2:])
case "version", "--version", "-v":
fmt.Printf("streamcore-cli %s\n", version)
default:
log.Fatalf("Unknown command: %s\n\nRun 'streamcore-cli' for usage.", os.Args[1])
}
}
func runIngest(args []string) {
ingestCmd := flag.NewFlagSet("ingest", flag.ExitOnError)
configPath := ingestCmd.String("config", "", "Path to config.toml (default: ~/.streamcore/config.toml)")
providerFlag := ingestCmd.String("provider", "", "Override RAG provider (pgvector, supabase)")
chunkSize := ingestCmd.Int("chunk-size", 512, "Target chunk size in words (approximate)")
chunkOverlap := ingestCmd.Int("chunk-overlap", 64, "Overlap between chunks in words (approximate)")
ingestCmd.Parse(args)
files := ingestCmd.Args()
if len(files) == 0 {
log.Fatal("No files specified.\n\nUsage: streamcore-cli ingest [flags] <file1> [file2] ...")
}
cfg := loadConfig(*configPath)
provider := *providerFlag
if provider == "" {
provider = cfg.RAG.Provider
}
if provider == "" {
log.Fatal("No RAG provider configured. Run 'streamcore-cli setup' or use --provider flag.")
}
apiKey := cfg.OpenAI.APIKey
if apiKey == "" {
apiKey = os.Getenv("OPENAI_API_KEY")
}
if apiKey == "" {
log.Fatal("OpenAI API key required for embeddings. Run 'streamcore-cli setup' or set OPENAI_API_KEY.")
}
embeddingModel := schema.Normalize(cfg.RAG.EmbeddingModel)
embedder := embed.NewClient(apiKey, embeddingModel)
st, err := store.New(provider, store.Config{
PgvectorConnStr: cfg.Pgvector.ConnectionString,
PgvectorTable: cfg.Pgvector.Table,
SupabaseURL: cfg.Supabase.URL,
SupabaseAPIKey: cfg.Supabase.APIKey,
SupabaseTable: cfg.Supabase.Table,
})
if err != nil {
log.Fatalf("Failed to create store: %v", err)
}
defer st.Close()
ctx := context.Background()
// Everything below this line writes to the store, so the store gets checked
// against the model first. A mismatch caught here costs one query; caught at
// query time it costs a rebuild of the whole table, and nothing reports it.
if err := st.Verify(ctx, embeddingModel); err != nil {
log.Fatalf("Store check failed: %v", err)
}
ch := chunker.New(*chunkSize, *chunkOverlap)
var totalChunks int
for _, file := range files {
log.Printf("Processing %s ...", file)
text, err := parser.Parse(file)
if err != nil {
log.Printf(" ERROR: %v (skipping)", err)
continue
}
chunks := ch.Chunk(text)
if len(chunks) == 0 {
log.Printf(" No content extracted (skipping)")
continue
}
log.Printf(" Extracted %d chunks", len(chunks))
source := filepath.Base(file)
for i, chunk := range chunks {
embedding, err := embedder.Embed(ctx, chunk)
if err != nil {
log.Printf(" ERROR embedding chunk %d: %v (skipping)", i+1, err)
continue
}
err = st.Insert(ctx, chunk, embedding, source, embeddingModel)
if err != nil {
log.Printf(" ERROR storing chunk %d: %v (skipping)", i+1, err)
continue
}
totalChunks++
fmt.Printf("\r Uploaded %d/%d chunks", i+1, len(chunks))
}
fmt.Println()
}
log.Printf("Done. %d chunks uploaded to %s (%s).", totalChunks, provider, embeddingModel)
}
// loadConfig reads the CLI's own config file. Priority:
// 1. Explicit --config path
// 2. ~/.streamcore/config.toml
// 3. ./config.toml (local override)
// 4. ../server/config.toml (fallback to server config if in monorepo)
func loadConfig(path string) Config {
if path == "" {
candidates := []string{
setup.ConfigPath(),
"config.toml",
"../server/config.toml",
"server/config.toml",
}
for _, c := range candidates {
if _, err := os.Stat(c); err == nil {
path = c
break
}
}
}
var cfg Config
if path != "" {
if _, err := toml.DecodeFile(path, &cfg); err != nil {
log.Printf("Warning: could not read %s: %v", path, err)
} else {
log.Printf("Using config: %s", path)
}
} else {
log.Println("No config found. Run 'streamcore-cli setup' to configure.")
}
return cfg
}
func printUsage() {
fmt.Println(`streamcore-cli — StreamCoreAI command-line tool
Usage:
streamcore-cli <command> [flags] [args]
Commands:
setup Interactive setup wizard — configure credentials and create the vector store
ingest Upload documents to your RAG vector store
version Print the version
Examples:
streamcore-cli setup
streamcore-cli ingest docs/faq.pdf data.csv
streamcore-cli ingest --chunk-size 256 manual.docx
Ingest flags:
--config string Path to config.toml (default: ~/.streamcore/config.toml)
--provider string Override RAG provider (pgvector, supabase)
--chunk-size int Target chunk size in words (default 512)
--chunk-overlap int Overlap between chunks in words (default 64)
Run 'streamcore-cli setup' to get started.`)
}