-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
158 lines (134 loc) · 4.15 KB
/
main.go
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
package main
import (
"cmp"
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/tmc/langchaingo/embeddings"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/googleai"
"github.com/tmc/langchaingo/schema"
"github.com/tmc/langchaingo/vectorstores/weaviate"
)
const generativeModelName = "gemini-1.5-flash"
const embeddingModelName = "text-embedding-004"
func main() {
fmt.Println("Running RAG model", generativeModelName)
ctx := context.Background()
apiKey := os.Getenv("GEMINI_API_KEY")
geminiClient, err := googleai.New(ctx,
googleai.WithAPIKey(apiKey),
googleai.WithDefaultEmbeddingModel(embeddingModelName))
if err != nil {
log.Fatal(err)
}
emb, err := embeddings.NewEmbedder(geminiClient)
if err != nil {
log.Fatal(err)
}
wvStore, err := weaviate.New(
weaviate.WithEmbedder(emb),
weaviate.WithScheme("http"),
weaviate.WithHost("localhost:"+cmp.Or(os.Getenv("WVPORT"), "9035")),
weaviate.WithIndexName("Document"),
)
server := &ragServer{
ctx: ctx,
wvStore: wvStore,
geminiClient: geminiClient,
}
mux := http.NewServeMux()
mux.HandleFunc("POST /healthz/", server.HealthEndpoint)
mux.HandleFunc("POST /add/", server.addDocumentsHandler)
mux.HandleFunc("POST /query/", server.queryHandler)
port := cmp.Or(os.Getenv("SERVERPORT"), "8000")
address := "localhost:" + port
log.Println("listening on", address)
log.Fatal(http.ListenAndServe(address, mux))
}
type ragServer struct {
ctx context.Context
wvStore weaviate.Store
geminiClient *googleai.GoogleAI
}
// HealthEndpoint
func (h *ragServer) HealthEndpoint(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Service Healthy"))
}
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {
// Parse HTTP request from JSON.
type document struct {
Text string
}
type addRequest struct {
Documents []document
}
ar := &addRequest{}
err := readRequestJSON(req, ar)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Store documents and their embeddings in weaviate
var wvDocs []schema.Document
for _, doc := range ar.Documents {
wvDocs = append(wvDocs, schema.Document{PageContent: doc.Text})
}
_, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {
// Parse HTTP request from JSON.
type queryRequest struct {
Content string
}
qr := &queryRequest{}
err := readRequestJSON(req, qr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Find the most similar documents.
docs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3)
if err != nil {
http.Error(w, fmt.Errorf("similarity search: %w", err).Error(), http.StatusInternalServerError)
return
}
var docsContents []string
for _, doc := range docs {
docsContents = append(docsContents, doc.PageContent)
}
// Create a RAG query for the LLM with the most relevant documents as
// context.
ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n"))
respText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName))
if err != nil {
log.Printf("calling generative model: %v", err.Error())
http.Error(w, "generative model error", http.StatusInternalServerError)
return
}
renderJSON(w, respText)
}
const ragTemplateStr = `
I will ask you a question and will provide some additional context information.
Assume this context information is factual and correct, as part of internal
documentation.
If the question relates to the context, answer it using the context.
If the question does not relate to the context, answer it as normal.
For example, let's say the context has nothing in it about tropical flowers;
then if I ask you about tropical flowers, just answer what you know about them
without referring to the context.
For example, if the context does mention minerology and I ask you about that,
provide information from the context along with general knowledge.
Question:
%s
Context:
%s
`