Spaces:
Sleeping
Sleeping
Download internal/memory/server/server.go from AmaniQuery/amaniquery-agent: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/spaces/AmaniQuery/amaniquery-agent/resolve/main/internal/memory/server/server.go
- Command line
-
hf download hf://spaces/AmaniQuery/amaniquery-agent/internal/memory/server/server.go
-
curl -L -o server.go https://huggingface.co/spaces/AmaniQuery/amaniquery-agent/resolve/main/internal/memory/server/server.go
14.3 kB
| // Package server provides a combined gRPC + HTTP memory service. | |
| // gRPC: ListSessions, GetContextWindow, ConsolidateMemory (from proto) | |
| // HTTP: Store, Retrieve, and other MemoryManager operations (JSON) | |
| package server | |
| import ( | |
| "context" | |
| "encoding/json" | |
| "fmt" | |
| "net" | |
| "net/http" | |
| "strconv" | |
| "time" | |
| "github.com/AmaniQuery/amaniquery/internal/memory" | |
| ragv1 "github.com/AmaniQuery/amaniquery/pkg/proto/gen/ragv1" | |
| "go.uber.org/zap" | |
| "google.golang.org/grpc" | |
| "google.golang.org/grpc/health" | |
| "google.golang.org/grpc/health/grpc_health_v1" | |
| "google.golang.org/grpc/reflection" | |
| ) | |
| type Config struct { | |
| GRPCPort int | |
| HTTPPort int | |
| MemoryConfig *memory.MemoryConfig | |
| RustServiceHost string | |
| RustServicePort int | |
| RustServiceAuthToken string | |
| EnableRust bool | |
| Logger *zap.Logger | |
| } | |
| type GRPCServer struct { | |
| ragv1.UnimplementedMemoryServiceServer | |
| backend memory.MemoryManager | |
| logger *zap.Logger | |
| } | |
| type HTTPServer struct { | |
| backend memory.MemoryManager | |
| logger *zap.Logger | |
| mux *http.ServeMux | |
| } | |
| type Server struct { | |
| cfg Config | |
| grpcSrv *grpc.Server | |
| httpSrv *http.Server | |
| backend memory.MemoryManager | |
| orchestrator *memory.MemoryOrchestrator | |
| consolidation *memory.ConsolidationWorker | |
| logger *zap.Logger | |
| } | |
| func New(cfg Config) (*Server, error) { | |
| logger := cfg.Logger | |
| if logger == nil { | |
| logger, _ = zap.NewProduction() | |
| } | |
| memCfg := cfg.MemoryConfig | |
| if memCfg == nil { | |
| memCfg = memory.DefaultMemoryConfig() | |
| } | |
| var backend memory.MemoryManager | |
| if cfg.EnableRust { | |
| localBackend := memory.NewLocalMemoryBackend(memCfg) | |
| rustClient := memory.NewRustMemoryClient(memory.RustClientConfig{ | |
| Host: cfg.RustServiceHost, | |
| Port: cfg.RustServicePort, | |
| AuthToken: cfg.RustServiceAuthToken, | |
| Compression: true, | |
| PoolSize: memCfg.ConnectionPoolSize, | |
| RequestTimeout: memCfg.RequestTimeout, | |
| Fallback: localBackend, | |
| }) | |
| backend = rustClient | |
| } else { | |
| backend = memory.NewLocalMemoryBackend(memCfg) | |
| } | |
| orch := memory.NewMemoryOrchestrator(backend, nil, nil, memCfg) | |
| consolidation := memory.NewConsolidationWorker(orch, memCfg.Consolidation) | |
| grpcSrv := grpc.NewServer( | |
| grpc.ChainUnaryInterceptor( | |
| loggerInterceptor(logger), | |
| ), | |
| ) | |
| grpcServer := &GRPCServer{ | |
| backend: backend, | |
| logger: logger, | |
| } | |
| ragv1.RegisterMemoryServiceServer(grpcSrv, grpcServer) | |
| healthServer := health.NewServer() | |
| grpc_health_v1.RegisterHealthServer(grpcSrv, healthServer) | |
| healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING) | |
| reflection.Register(grpcSrv) | |
| return &Server{ | |
| cfg: cfg, | |
| grpcSrv: grpcSrv, | |
| backend: backend, | |
| orchestrator: orch, | |
| consolidation: consolidation, | |
| logger: logger, | |
| }, nil | |
| } | |
| func (s *Server) Start() error { | |
| s.consolidation.Start() | |
| s.logger.Info("consolidation worker started") | |
| errChan := make(chan error, 2) | |
| grpcAddr := fmt.Sprintf(":%d", s.cfg.GRPCPort) | |
| grpcListener, err := net.Listen("tcp", grpcAddr) | |
| if err != nil { | |
| return fmt.Errorf("failed to listen gRPC: %w", err) | |
| } | |
| go func() { | |
| s.logger.Info("gRPC memory server starting", zap.String("addr", grpcAddr)) | |
| errChan <- s.grpcSrv.Serve(grpcListener) | |
| }() | |
| if s.cfg.HTTPPort > 0 { | |
| httpAddr := fmt.Sprintf(":%d", s.cfg.HTTPPort) | |
| httpMux := http.NewServeMux() | |
| httpSrv := &HTTPServer{ | |
| backend: s.backend, | |
| logger: s.logger, | |
| mux: httpMux, | |
| } | |
| httpSrv.registerRoutes() | |
| s.httpSrv = &http.Server{ | |
| Addr: httpAddr, | |
| Handler: httpMux, | |
| } | |
| go func() { | |
| s.logger.Info("HTTP memory server starting", zap.String("addr", httpAddr)) | |
| if err := s.httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed { | |
| errChan <- err | |
| } | |
| }() | |
| } | |
| return <-errChan | |
| } | |
| func (s *Server) Shutdown(ctx context.Context) error { | |
| s.consolidation.Stop() | |
| s.grpcSrv.GracefulStop() | |
| if s.httpSrv != nil { | |
| return s.httpSrv.Shutdown(ctx) | |
| } | |
| return nil | |
| } | |
| func (s *Server) Orchestrator() *memory.MemoryOrchestrator { | |
| return s.orchestrator | |
| } | |
| func (s *Server) ConsolidationWorker() *memory.ConsolidationWorker { | |
| return s.consolidation | |
| } | |
| func (s *GRPCServer) ListSessions(ctx context.Context, req *ragv1.ListSessionsRequest) (*ragv1.ListSessionsResponse, error) { | |
| sessions, err := s.backend.ListSessions(ctx, req.UserId) | |
| if err != nil { | |
| return nil, err | |
| } | |
| protoSessions := make([]*ragv1.SessionInfo, len(sessions)) | |
| for i, sess := range sessions { | |
| protoSessions[i] = &ragv1.SessionInfo{ | |
| Id: sess.ID, | |
| UserId: sess.UserID, | |
| Title: sess.Title, | |
| LastInteraction: sess.LastInteraction.UnixMilli(), | |
| MessageCount: int32(sess.MessageCount), | |
| } | |
| } | |
| return &ragv1.ListSessionsResponse{Sessions: protoSessions}, nil | |
| } | |
| func (s *GRPCServer) GetContextWindow(ctx context.Context, req *ragv1.ContextWindowRequest) (*ragv1.ContextWindowResponse, error) { | |
| entries, err := s.backend.GetContextWindowForUser(ctx, req.SessionId, req.UserId, int(req.MaxTurns)) | |
| if err != nil { | |
| return nil, err | |
| } | |
| protoEntries := make([]*ragv1.ContextEntry, len(entries)) | |
| for i, e := range entries { | |
| protoEntries[i] = &ragv1.ContextEntry{ | |
| Id: e.ID, | |
| Type: e.Type.String(), | |
| Content: e.Content, | |
| Timestamp: e.Timestamp.UnixMilli(), | |
| Score: e.Score, | |
| } | |
| } | |
| return &ragv1.ContextWindowResponse{Entries: protoEntries}, nil | |
| } | |
| func (s *GRPCServer) ConsolidateMemory(ctx context.Context, req *ragv1.ConsolidateRequest) (*ragv1.ConsolidateResponse, error) { | |
| err := s.backend.ConsolidateMemory(ctx, req.SessionId) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return &ragv1.ConsolidateResponse{Success: true}, nil | |
| } | |
| func (h *HTTPServer) registerRoutes() { | |
| h.mux.HandleFunc("/api/v1/memory/store", h.handleStore) | |
| h.mux.HandleFunc("/api/v1/memory/retrieve", h.handleRetrieve) | |
| h.mux.HandleFunc("/api/v1/memory/search", h.handleSearch) | |
| h.mux.HandleFunc("/api/v1/memory/delete", h.handleDelete) | |
| h.mux.HandleFunc("/api/v1/memory/anonymize", h.handleAnonymize) | |
| h.mux.HandleFunc("/api/v1/memory/list-sessions", h.handleListSessions) | |
| h.mux.HandleFunc("/api/v1/memory/consolidate", h.handleConsolidate) | |
| h.mux.HandleFunc("/api/v1/memory/apply-ttl", h.handleApplyTTL) | |
| h.mux.HandleFunc("/api/v1/memory/health", h.handleHealth) | |
| } | |
| type storeRequest struct { | |
| UserID string `json:"user_id"` | |
| SessionID string `json:"session_id"` | |
| Content string `json:"content"` | |
| MemoryType string `json:"memory_type"` | |
| Source string `json:"source"` | |
| Tags []string `json:"tags,omitempty"` | |
| Confidence float64 `json:"confidence"` | |
| } | |
| type storeResponse struct { | |
| ID string `json:"id"` | |
| Success bool `json:"success"` | |
| } | |
| type retrieveRequest struct { | |
| UserID string `json:"user_id"` | |
| SessionID string `json:"session_id"` | |
| Query string `json:"query"` | |
| MemoryType string `json:"memory_type"` | |
| TopK int `json:"top_k"` | |
| Tags []string `json:"tags,omitempty"` | |
| } | |
| type searchResult struct { | |
| ID string `json:"id"` | |
| Content string `json:"content"` | |
| Type string `json:"type"` | |
| Score float64 `json:"score"` | |
| Timestamp int64 `json:"timestamp"` | |
| Source string `json:"source"` | |
| SessionID string `json:"session_id"` | |
| } | |
| func (h *HTTPServer) respond(w http.ResponseWriter, status int, data any) { | |
| w.Header().Set("Content-Type", "application/json") | |
| w.WriteHeader(status) | |
| if data != nil { | |
| _ = json.NewEncoder(w).Encode(data) | |
| } | |
| } | |
| func (h *HTTPServer) respondError(w http.ResponseWriter, status int, msg string) { | |
| h.respond(w, status, map[string]string{"error": msg}) | |
| } | |
| func (h *HTTPServer) handleStore(w http.ResponseWriter, r *http.Request) { | |
| if r.Method != http.MethodPost { | |
| h.respondError(w, http.StatusMethodNotAllowed, "POST required") | |
| return | |
| } | |
| var req storeRequest | |
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | |
| h.respondError(w, http.StatusBadRequest, "invalid JSON") | |
| return | |
| } | |
| memType := memory.EpisodicMemory | |
| switch req.MemoryType { | |
| case "semantic": | |
| memType = memory.SemanticMemory | |
| case "procedural": | |
| memType = memory.ProceduralMemory | |
| case "temporal": | |
| memType = memory.TemporalMemory | |
| } | |
| entry := &memory.MemoryEntry{ | |
| ID: fmt.Sprintf("mem:%s:%d", req.UserID, time.Now().UnixNano()), | |
| Type: memType, | |
| Content: req.Content, | |
| Timestamp: time.Now(), | |
| Confidence: req.Confidence, | |
| UserID: req.UserID, | |
| SessionID: req.SessionID, | |
| Source: req.Source, | |
| Tags: req.Tags, | |
| } | |
| if entry.Confidence == 0 { | |
| entry.Confidence = 1.0 | |
| } | |
| if err := h.backend.Store(r.Context(), entry); err != nil { | |
| h.logger.Error("store failed", zap.Error(err)) | |
| h.respondError(w, http.StatusInternalServerError, "store failed") | |
| return | |
| } | |
| h.respond(w, http.StatusOK, storeResponse{ID: entry.ID, Success: true}) | |
| } | |
| func (h *HTTPServer) handleRetrieve(w http.ResponseWriter, r *http.Request) { | |
| if r.Method != http.MethodPost { | |
| h.respondError(w, http.StatusMethodNotAllowed, "POST required") | |
| return | |
| } | |
| var req retrieveRequest | |
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | |
| h.respondError(w, http.StatusBadRequest, "invalid JSON") | |
| return | |
| } | |
| if req.TopK <= 0 { | |
| req.TopK = 10 | |
| } | |
| memQuery := &memory.MemoryQuery{ | |
| UserID: req.UserID, | |
| SessionID: req.SessionID, | |
| Query: req.Query, | |
| TopK: req.TopK, | |
| Tags: req.Tags, | |
| } | |
| entries, err := h.backend.Retrieve(r.Context(), memQuery) | |
| if err != nil { | |
| h.logger.Error("retrieve failed", zap.Error(err)) | |
| h.respondError(w, http.StatusInternalServerError, "retrieve failed") | |
| return | |
| } | |
| results := make([]searchResult, len(entries)) | |
| for i, e := range entries { | |
| results[i] = searchResult{ | |
| ID: e.ID, | |
| Content: e.Content, | |
| Type: e.Type.String(), | |
| Score: e.Score, | |
| Timestamp: e.Timestamp.UnixMilli(), | |
| Source: e.Source, | |
| SessionID: e.SessionID, | |
| } | |
| } | |
| h.respond(w, http.StatusOK, map[string]any{"results": results, "count": len(results)}) | |
| } | |
| func (h *HTTPServer) handleSearch(w http.ResponseWriter, r *http.Request) { | |
| userID := r.URL.Query().Get("user_id") | |
| sessionID := r.URL.Query().Get("session_id") | |
| q := r.URL.Query().Get("q") | |
| topK, _ := strconv.Atoi(r.URL.Query().Get("top_k")) | |
| if topK <= 0 { | |
| topK = 10 | |
| } | |
| entries, err := h.backend.GetContextWindow(r.Context(), sessionID, topK) | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| query := &memory.MemoryQuery{ | |
| UserID: userID, | |
| SessionID: sessionID, | |
| Query: q, | |
| TopK: topK, | |
| } | |
| if q != "" { | |
| entries, err = h.backend.Retrieve(r.Context(), query) | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| } | |
| results := make([]searchResult, len(entries)) | |
| for i, e := range entries { | |
| results[i] = searchResult{ | |
| ID: e.ID, | |
| Content: e.Content, | |
| Type: e.Type.String(), | |
| Score: e.Score, | |
| Timestamp: e.Timestamp.UnixMilli(), | |
| Source: e.Source, | |
| SessionID: e.SessionID, | |
| } | |
| } | |
| h.respond(w, http.StatusOK, map[string]any{"results": results}) | |
| } | |
| func (h *HTTPServer) handleDelete(w http.ResponseWriter, r *http.Request) { | |
| if r.Method != http.MethodPost { | |
| h.respondError(w, http.StatusMethodNotAllowed, "POST required") | |
| return | |
| } | |
| var req struct { | |
| ID string `json:"id"` | |
| UserID string `json:"user_id"` | |
| } | |
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | |
| h.respondError(w, http.StatusBadRequest, "invalid JSON") | |
| return | |
| } | |
| var err error | |
| if req.ID != "" { | |
| err = h.backend.Delete(r.Context(), req.ID) | |
| } else if req.UserID != "" { | |
| err = h.backend.DeleteUserData(r.Context(), req.UserID) | |
| } | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| h.respond(w, http.StatusOK, map[string]bool{"success": true}) | |
| } | |
| func (h *HTTPServer) handleAnonymize(w http.ResponseWriter, r *http.Request) { | |
| if r.Method != http.MethodPost { | |
| h.respondError(w, http.StatusMethodNotAllowed, "POST required") | |
| return | |
| } | |
| var req struct { | |
| UserID string `json:"user_id"` | |
| } | |
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | |
| h.respondError(w, http.StatusBadRequest, "invalid JSON") | |
| return | |
| } | |
| if req.UserID == "" { | |
| h.respondError(w, http.StatusBadRequest, "user_id required") | |
| return | |
| } | |
| if err := h.backend.AnonymizeUserData(r.Context(), req.UserID); err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| h.respond(w, http.StatusOK, map[string]bool{"success": true, "anonymized": true}) | |
| } | |
| func (h *HTTPServer) handleListSessions(w http.ResponseWriter, r *http.Request) { | |
| userID := r.URL.Query().Get("user_id") | |
| if userID == "" { | |
| h.respondError(w, http.StatusBadRequest, "user_id required") | |
| return | |
| } | |
| sessions, err := h.backend.ListSessions(r.Context(), userID) | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| h.respond(w, http.StatusOK, map[string]any{"sessions": sessions}) | |
| } | |
| func (h *HTTPServer) handleConsolidate(w http.ResponseWriter, r *http.Request) { | |
| sessionID := r.URL.Query().Get("session_id") | |
| err := h.backend.ConsolidateMemory(r.Context(), sessionID) | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| h.respond(w, http.StatusOK, map[string]bool{"success": true}) | |
| } | |
| func (h *HTTPServer) handleApplyTTL(w http.ResponseWriter, r *http.Request) { | |
| count, err := h.backend.ApplyTTL(r.Context()) | |
| if err != nil { | |
| h.respondError(w, http.StatusInternalServerError, err.Error()) | |
| return | |
| } | |
| h.respond(w, http.StatusOK, map[string]any{"deleted": count}) | |
| } | |
| func (h *HTTPServer) handleHealth(w http.ResponseWriter, r *http.Request) { | |
| h.respond(w, http.StatusOK, map[string]string{"status": "healthy"}) | |
| } | |
| func loggerInterceptor(logger *zap.Logger) grpc.UnaryServerInterceptor { | |
| return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { | |
| start := time.Now() | |
| resp, err := handler(ctx, req) | |
| duration := time.Since(start) | |
| if err != nil { | |
| logger.Error("gRPC error", | |
| zap.String("method", info.FullMethod), | |
| zap.Duration("duration", duration), | |
| zap.Error(err), | |
| ) | |
| } else { | |
| logger.Debug("gRPC call", | |
| zap.String("method", info.FullMethod), | |
| zap.Duration("duration", duration), | |
| ) | |
| } | |
| return resp, err | |
| } | |
| } | |