Skip to content

brightdigit/Mem0Swift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mem0Swift

A Swift SDK for Mem0 - the memory layer for LLM applications.

Generated from the official Mem0 OpenAPI specification using Swift OpenAPI Generator.

Requirements

  • Swift 5.9+
  • macOS 13+ / iOS 16+ / tvOS 16+ / watchOS 9+ / visionOS 1+

Installation

Swift Package Manager

Add to your Package.swift:

dependencies: [
    .package(url: "https://github.com/YourUsername/Mem0Swift", from: "1.0.0")
]

Or in Xcode: File → Add Package Dependencies → paste the repository URL.

Quick Start

Using the Hosted Platform (api.mem0.ai)

import Mem0Client

// Initialize with your API key
let mem0 = Mem0(apiKey: "your-api-key")

// Add memories from a conversation
let messages = [
    ["role": "user", "content": "I'm a Swift developer working on iOS apps"],
    ["role": "assistant", "content": "Great! I'll remember you're a Swift developer."]
]
try await mem0.add(messages: messages, userId: "user-123")

// Search memories
let results = try await mem0.search(
    query: "What programming languages do I use?",
    userId: "user-123"
)

// Get all memories for a user
let memories = try await mem0.getAll(userId: "user-123")

// Delete a specific memory
try await mem0.delete(memoryId: "mem-abc-123")

Using a Self-Hosted Instance

import Mem0Client

// Connect to your local Mem0 server
let mem0 = Mem0(serverURL: URL(string: "http://localhost:8000")!)

// Or with authentication
let mem0 = Mem0(
    serverURL: URL(string: "http://localhost:8000")!,
    apiKey: "optional-key"
)

Using the Raw Generated Client

For advanced use cases, access the generated client directly:

import Mem0Client

let mem0 = Mem0(apiKey: "your-api-key")

// Use v2 search with advanced filters
let response = try await mem0.rawClient.memories_search_v2(.init(
    body: .json(.init(
        query: "dietary preferences",
        filters: .init(
            AND: [
                .init(user_id: "alice"),
                .init(created_at: .init(gte: "2024-01-01"))
            ]
        )
    ))
))

API Coverage

This SDK covers the full Mem0 Platform API:

Memory Operations

  • add(messages:userId:agentId:metadata:) - Store memories from conversations
  • search(query:userId:agentId:limit:) - Semantic search
  • getAll(userId:agentId:page:pageSize:) - List memories
  • get(memoryId:) - Get single memory
  • update(memoryId:text:) - Update memory content
  • delete(memoryId:) - Delete single memory
  • deleteAll(userId:agentId:) - Bulk delete
  • history(memoryId:) - Memory change history

Entity Operations

  • listEntities(orgId:projectId:) - List users/agents/apps/runs
  • deleteEntity(entityType:entityId:) - Delete entity and memories

Raw Client Access

The rawClient property exposes all generated operations including:

  • v2 filter APIs with AND/OR/NOT logic
  • Memory exports
  • Events tracking
  • Webhooks (Platform only)
  • Organizations & Projects (Platform only)

Integration Examples

With SwiftUI

import SwiftUI
import Mem0Client

@MainActor
class ChatViewModel: ObservableObject {
    private let mem0 = Mem0(apiKey: ProcessInfo.processInfo.environment["MEM0_API_KEY"]!)
    private let userId = "current-user"
    
    @Published var memories: [String] = []
    
    func loadContext(for query: String) async {
        do {
            let response = try await mem0.search(query: query, userId: userId, limit: 5)
            // Extract memories from response...
        } catch {
            print("Failed to load context: \(error)")
        }
    }
    
    func saveConversation(_ messages: [[String: String]]) async {
        do {
            try await mem0.add(messages: messages, userId: userId)
        } catch {
            print("Failed to save: \(error)")
        }
    }
}

With Vapor (Server-Side Swift)

import Vapor
import Mem0Client

func routes(_ app: Application) throws {
    let mem0 = Mem0(apiKey: Environment.get("MEM0_API_KEY")!)
    
    app.post("chat") { req async throws -> String in
        let input = try req.content.decode(ChatRequest.self)
        
        // Get relevant context
        let context = try await mem0.search(
            query: input.message,
            userId: input.userId,
            limit: 5
        )
        
        // ... use context with your LLM ...
        
        // Save the conversation
        try await mem0.add(
            messages: [
                ["role": "user", "content": input.message],
                ["role": "assistant", "content": response]
            ],
            userId: input.userId
        )
        
        return response
    }
}

Error Handling

do {
    let memories = try await mem0.getAll(userId: "user-123")
} catch let error as ClientError {
    // Handle OpenAPI client errors
    print("Client error: \(error)")
} catch {
    // Handle other errors (network, etc.)
    print("Error: \(error)")
}

License

Apache 2.0 - Same as Mem0.

Links

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages