File size: 6,096 Bytes
ebab9b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
/**
 * MemoryOS β€” Frontend API Client
 *
 * Typed fetch wrapper for all backend endpoints.
 */

const API_BASE = import.meta.env.VITE_API_URL || '/api/v1';

// ── Types ────────────────────────────────────────────────────────────────

export interface User {
  id: string;
  external_id: string;
  created_at: string;
}

export interface Session {
  id: string;
  user_id: string;
  started_at: string;
  ended_at: string | null;
  metadata: Record<string, unknown>;
}

export interface MemoryItem {
  id: string;
  user_id: string;
  session_id: string | null;
  memory_type: 'episodic' | 'semantic' | 'procedural';
  content: string;
  summary: string | null;
  metadata: Record<string, unknown>;
  importance: number;
  recency_score: number;
  access_count: number;
  created_at: string;
  last_accessed: string | null;
}

export interface ScoredMemory {
  memory: MemoryItem;
  score: number;
  cosine_similarity: number;
}

export interface IngestResponse {
  memory_id: string;
  message: string;
}

export interface ChatResponse {
  assistant_message: string;
  retrieved_memories: {
    id: string;
    type: string;
    content: string;
    score: number;
  }[];
}

export interface ContradictionItem {
  id: string;
  memory_a: string;
  memory_b: string;
  detected_at: string;
  resolved: boolean;
  memory_a_content: string | null;
  memory_b_content: string | null;
}

export interface StatsOverview {
  total_memories: number;
  type_counts: {
    episodic: number;
    semantic: number;
    procedural: number;
  };
  avg_importance: number;
  avg_recency_score: number;
  total_users: number;
  total_sessions: number;
  recent_contradictions: ContradictionItem[];
}

export interface GraphNode {
  id: string;
  memory_type: 'episodic' | 'semantic' | 'procedural';
  content: string;
  importance: number;
  created_at: string;
}

export interface GraphEdge {
  source: string;
  target: string;
  similarity: number;
}

export interface GraphData {
  nodes: GraphNode[];
  edges: GraphEdge[];
}

export interface SessionWithMemories extends Session {
  memories: MemoryItem[];
}

// ── Fetch helper ─────────────────────────────────────────────────────────

async function apiFetch<T>(
  path: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE}${path}`;
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(options.headers as Record<string, string> || {}),
  };

  const response = await fetch(url, { ...options, headers });

  if (!response.ok) {
    const body = await response.json().catch(() => ({ detail: response.statusText }));
    throw new Error(body.detail || `API error: ${response.status}`);
  }

  return response.json();
}

// ── API functions ────────────────────────────────────────────────────────

export async function createUser(externalId: string): Promise<User> {
  return apiFetch<User>('/users', {
    method: 'POST',
    body: JSON.stringify({ external_id: externalId }),
  });
}

export async function getUser(userId: string): Promise<User> {
  return apiFetch<User>(`/users/${userId}`);
}

export async function getUserContext(
  userId: string,
  query: string,
  topK: number = 10
): Promise<ScoredMemory[]> {
  const params = new URLSearchParams({ query, top_k: String(topK) });
  return apiFetch<ScoredMemory[]>(`/users/${userId}/context?${params}`);
}

export async function createSession(
  userId: string,
  metadata: Record<string, unknown> = {}
): Promise<Session> {
  return apiFetch<Session>('/sessions', {
    method: 'POST',
    body: JSON.stringify({ user_id: userId, metadata }),
  });
}

export async function getSession(sessionId: string): Promise<SessionWithMemories> {
  return apiFetch<SessionWithMemories>(`/sessions/${sessionId}`);
}

export async function endSession(sessionId: string): Promise<Session> {
  return apiFetch<Session>(`/sessions/${sessionId}`, { method: 'DELETE' });
}

export async function sendChatMessage(
  sessionId: string,
  userMessage: string
): Promise<ChatResponse> {
  return apiFetch<ChatResponse>(`/sessions/${sessionId}/chat`, {
    method: 'POST',
    body: JSON.stringify({ user_message: userMessage }),
  });
}

export async function ingestMemory(
  userId: string,
  sessionId: string,
  userMessage: string,
  assistantMessage: string
): Promise<IngestResponse> {
  return apiFetch<IngestResponse>('/memories/ingest', {
    method: 'POST',
    body: JSON.stringify({
      user_id: userId,
      session_id: sessionId,
      user_message: userMessage,
      assistant_message: assistantMessage,
    }),
  });
}

export async function searchMemories(
  userId: string,
  query: string,
  memoryType?: string,
  topK: number = 10
): Promise<ScoredMemory[]> {
  const params = new URLSearchParams({
    user_id: userId,
    query,
    top_k: String(topK),
  });
  if (memoryType) params.append('memory_type', memoryType);
  return apiFetch<ScoredMemory[]>(`/memories/search?${params}`);
}

export async function getMemory(memoryId: string): Promise<MemoryItem> {
  return apiFetch<MemoryItem>(`/memories/${memoryId}`);
}

export async function deleteMemory(memoryId: string): Promise<MemoryItem> {
  return apiFetch<MemoryItem>(`/memories/${memoryId}`, { method: 'DELETE' });
}

export async function getContradictions(memoryId: string): Promise<ContradictionItem[]> {
  return apiFetch<ContradictionItem[]>(`/memories/${memoryId}/contradictions`);
}

export async function getStatsOverview(): Promise<StatsOverview> {
  return apiFetch<StatsOverview>('/stats/overview');
}

export async function getGraphData(userId?: string): Promise<GraphData> {
  const params = userId ? `?user_id=${userId}` : '';
  return apiFetch<GraphData>(`/stats/graph${params}`);
}