MCPcopy Index your code
hub / github.com/golang/example / addDocumentsHandler

Method addDocumentsHandler

ragserver/ragserver/main.go:70–122  ·  view source on GitHub ↗
(w http.ResponseWriter, req *http.Request)

Source from the content-addressed store, hash-verified

68}
69
70func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) {
71 // Parse HTTP request from JSON.
72 type document struct {
73 Text string
74 }
75 type addRequest struct {
76 Documents []document
77 }
78 ar := &addRequest{}
79
80 err := readRequestJSON(req, ar)
81 if err != nil {
82 http.Error(w, err.Error(), http.StatusBadRequest)
83 return
84 }
85
86 // Use the batch embedding API to embed all documents at once.
87 batch := rs.embModel.NewBatch()
88 for _, doc := range ar.Documents {
89 batch.AddContent(genai.Text(doc.Text))
90 }
91 log.Printf("invoking embedding model with %v documents", len(ar.Documents))
92 rsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch)
93 if err != nil {
94 http.Error(w, err.Error(), http.StatusInternalServerError)
95 return
96 }
97 if len(rsp.Embeddings) != len(ar.Documents) {
98 http.Error(w, "embedded batch size mismatch", http.StatusInternalServerError)
99 return
100 }
101
102 // Convert our documents - along with their embedding vectors - into types
103 // used by the Weaviate client library.
104 objects := make([]*models.Object, len(ar.Documents))
105 for i, doc := range ar.Documents {
106 objects[i] = &models.Object{
107 Class: "Document",
108 Properties: map[string]any{
109 "text": doc.Text,
110 },
111 Vector: rsp.Embeddings[i].Values,
112 }
113 }
114
115 // Store documents with embeddings in the Weaviate DB.
116 log.Printf("storing %v objects in weaviate", len(objects))
117 _, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx)
118 if err != nil {
119 http.Error(w, err.Error(), http.StatusInternalServerError)
120 return
121 }
122}
123
124func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) {
125 // Parse HTTP request from JSON.

Callers

nothing calls this directly

Calls 1

readRequestJSONFunction · 0.70

Tested by

no test coverage detected