Search handles POST /api/memories/search
(w ErrorResponseWriter, r *http.Request)
| 188 | |
| 189 | // Search handles POST /api/memories/search |
| 190 | func (h *MemoryHandler) Search(w ErrorResponseWriter, r *http.Request) { |
| 191 | var req SearchSessionMemoryRequest |
| 192 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 193 | RespondWithError(w, http.StatusBadRequest, "Invalid request body") |
| 194 | return |
| 195 | } |
| 196 | |
| 197 | if req.AgentName == "" || req.UserID == "" || len(req.Vector) == 0 { |
| 198 | RespondWithError(w, http.StatusBadRequest, "Missing required fields (agent_name, user_id, vector)") |
| 199 | return |
| 200 | } |
| 201 | |
| 202 | if len(req.Vector) != memoryVectorDimension { |
| 203 | RespondWithError(w, http.StatusBadRequest, fmt.Sprintf("vector must have exactly %d dimensions, got %d", memoryVectorDimension, len(req.Vector))) |
| 204 | return |
| 205 | } |
| 206 | |
| 207 | if req.Limit <= 0 { |
| 208 | req.Limit = 5 |
| 209 | } |
| 210 | |
| 211 | // Format vector using pgvector.NewVector |
| 212 | vector := pgvector.NewVector(req.Vector) |
| 213 | |
| 214 | // Update DB client call to pass pgvector.Vector |
| 215 | results, err := h.DatabaseService.SearchAgentMemory(r.Context(), req.AgentName, req.UserID, vector, req.Limit) |
| 216 | if err != nil { |
| 217 | RespondWithError(w, http.StatusInternalServerError, fmt.Sprintf("search failed: %v", err)) |
| 218 | return |
| 219 | } |
| 220 | |
| 221 | response := make([]SearchSessionMemoryResponse, 0, len(results)) |
| 222 | for _, res := range results { |
| 223 | // Filter by MinScore if provided |
| 224 | if req.MinScore > 0 && res.Score < req.MinScore { |
| 225 | continue |
| 226 | } |
| 227 | |
| 228 | // Handle empty or invalid metadata |
| 229 | metadata := json.RawMessage(res.Metadata) |
| 230 | if len(metadata) == 0 { |
| 231 | metadata = json.RawMessage("{}") |
| 232 | } |
| 233 | |
| 234 | response = append(response, SearchSessionMemoryResponse{ |
| 235 | ID: res.ID, |
| 236 | Content: res.Content, |
| 237 | Score: res.Score, |
| 238 | Metadata: metadata, |
| 239 | CreatedAt: res.CreatedAt, |
| 240 | }) |
| 241 | } |
| 242 | |
| 243 | RespondWithJSON(w, http.StatusOK, response) |
| 244 | } |
| 245 | |
| 246 | // List handles GET /api/memories and returns all memories for an agent+user, ranked by access frequency |
| 247 | func (h *MemoryHandler) List(w ErrorResponseWriter, r *http.Request) { |