aboutsummaryrefslogtreecommitdiff
path: root/packages/tools/src/conversations-client.ts
blob: c147265e7981de7eb0720c520ebb00add0759d96 (plain) (blame)
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
/**
 * Client for the Supermemory Conversations API
 *
 * This module provides a helper function to ingest conversations using the
 * /v4/conversations endpoint, which supports structured messages with smart
 * diffing and append detection on the backend.
 */

export interface ConversationMessage {
	role: "user" | "assistant" | "system" | "tool"
	content: string | ContentPart[]
	name?: string
	tool_calls?: ToolCall[]
	tool_call_id?: string
}

export interface ContentPart {
	type: "text" | "image_url"
	text?: string
	image_url?: { url: string }
}

export interface ToolCall {
	id: string
	type: "function"
	function: {
		name: string
		arguments: string
	}
}

export interface AddConversationParams {
	conversationId: string
	messages: ConversationMessage[]
	containerTags?: string[]
	metadata?: Record<string, string | number | boolean>
	apiKey: string
	baseUrl?: string
}

export interface AddConversationResponse {
	id: string
	conversationId: string
	status: string
}

/**
 * Adds a conversation to Supermemory using the /v4/conversations endpoint
 *
 * This endpoint supports:
 * - Structured messages with roles (user, assistant, system, tool)
 * - Multi-modal content (text, images)
 * - Tool calls and responses
 *
 * @param params - Configuration for adding the conversation
 * @returns Promise resolving to the conversation response
 * @throws Error if the API request fails
 *
 * @example
 * ```typescript
 * const response = await addConversation({
 *   conversationId: "conv-123",
 *   messages: [
 *     { role: "user", content: "Hello!" },
 *     { role: "assistant", content: "Hi there!" }
 *   ],
 *   containerTags: ["user-456"],
 *   apiKey: process.env.SUPERMEMORY_API_KEY,
 * })
 * ```
 */
export async function addConversation(
	params: AddConversationParams,
): Promise<AddConversationResponse> {
	const baseUrl = params.baseUrl || "https://api.supermemory.ai"
	const url = `${baseUrl}/v4/conversations`

	const response = await fetch(url, {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
			Authorization: `Bearer ${params.apiKey}`,
		},
		body: JSON.stringify({
			conversationId: params.conversationId,
			messages: params.messages,
			containerTags: params.containerTags,
			metadata: params.metadata,
		}),
	})

	if (!response.ok) {
		const errorText = await response.text().catch(() => "Unknown error")
		throw new Error(
			`Failed to add conversation: ${response.status} ${response.statusText}. ${errorText}`,
		)
	}

	return await response.json()
}