PHP code example of shanginn / mem0

1. Go to this page and download the library: Download shanginn/mem0 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shanginn / mem0 example snippets




em0\Mem0;
use Mem0\DTO\Message;
use Mem0\Enum\Role;

// Retrieve your API key from environment variables or secure storage
$apiKey = getenv('MEM0_API_KEY'); 
if (!$apiKey) {
    die("MEM0_API_KEY environment variable not set.\n");
}

// Initialize the client
$mem0 = new Mem0($apiKey);

// Add a simple memory
$response = $mem0->add(
    messages: "Hi, my name is Alice and I love hiking",
    userId: 'user-123'
);

echo "Memory added successfully!\n";
dump($response);

// Simple text memory
$mem0->add(
    messages: "I prefer vegetarian restaurants",
    userId: 'user-123'
);

// Rich conversational memory
$messages = [
    new Message(Role::USER, "What's the weather like?"),
    new Message(Role::ASSISTANT, "It's sunny and 75°F today."),
    new Message(Role::USER, "Perfect for a bike ride!")
];

$response = $mem0->add(
    messages: $messages,
    userId: 'user-123',
    metadata: ['location' => 'San Francisco', 'activity' => 'cycling']
);

// Memory with expiration and custom instructions
$mem0->add(
    messages: "Temporary project preferences",
    userId: 'user-123',
    expirationDate: new DateTime('2024-12-31'),
    customInstructions: "Focus on project-related preferences only",
    immutable: false
);

use Mem0\DTO\Filter;
use Mem0\DTO\FilterOperator;

// Simple retrieval
$memories = $mem0->listMemories();

// Filtered retrieval with complex conditions
$filter = new Filter(
    and: [
        ['user_id' => 'alice'],
        ['created_at' => new FilterOperator(
            gte: '2024-07-01',
            lte: '2024-07-31'
        )]
    ],
    or: [
        ['agent_id' => new FilterOperator(
            in: ['travel-agent', 'food-agent']
        )],
        ['categories' => 'preferences']
    ]
);

$memories = $mem0->listMemories(
    filters: $filter,
    fields: ['id', 'memory', 'created_at', 'metadata'],
    page: 1,
    pageSize: 50
);

foreach ($memories as $memory) {
    echo "Memory: {$memory->memory}\n";
    echo "Created: {$memory->createdAt}\n";
    if ($memory->metadata) {
        echo "Metadata: " . json_encode($memory->metadata) . "\n";
    }
    echo "---\n";
}

use Mem0\Contract\ClientInterface;

class CustomClient implements ClientInterface
{
    public function sendRequest(string $method, string $endpoint, string $body = '', array $queryParams = []): string
    {
        // Your custom HTTP implementation
        // Return JSON response as string
    }
}

$mem0 = new Mem0(
    apiKey: 'your-api-key',
    client: new CustomClient()
);

use Mem0\Contract\SerializerInterface;

class CustomSerializer implements SerializerInterface
{
    public function serialize(object $data): string
    {
        // Your custom serialization logic
        return json_encode($data);
    }

    public function deserialize(string $json, string $className, bool $isArray = false): mixed
    {
        // Your custom deserialization logic
        $data = json_decode($json, true);
        // ... transform to $className instances
        return $data;
    }
}

$mem0 = new Mem0(
    apiKey: 'your-api-key',
    serializer: new CustomSerializer()
);

$mem0 = new Mem0(
    apiKey: 'your-api-key',
    defaultOrgId: 'org-123',
    defaultProjectId: 'project-456'
);

// These will automatically use the default org/project
$mem0->addMemory(
    messages: "Default scoped memory",
    userId: 'user-123'
);

use Mem0\DTO\Message;
use Mem0\Enum\Role;

$message = new Message(
    role: Role::USER, // or Role::ASSISTANT, Role::SYSTEM
    content: "Hello, world!"
);

use Mem0\DTO\Filter;
use Mem0\DTO\FilterOperator;

$filter = new Filter(
    and: [
        ['status' => 'active'],
        ['priority' => new FilterOperator(gte: 5)]
    ],
    or: [
        ['user_id' => new FilterOperator(in: ['user1', 'user2'])],
        ['agent_id' => 'special-agent']
    ]
);

// Returned from listMemories()
foreach ($memories as $memory) {
    echo "ID: {$memory->id}\n";
    echo "Content: {$memory->memory}\n";
    echo "Created: {$memory->createdAt}\n";
    echo "User ID: {$memory->userId}\n";
    echo "Categories: " . implode(', ', $memory->categories ?? []) . "\n";
    if ($memory->metadata) {
        echo "Metadata: " . json_encode($memory->metadata) . "\n";
    }
}

use Mem0\Exception\Mem0ApiException;
use Mem0\Exception\HttpClientException;
use Mem0\Exception\DeserializationException;
use Mem0\Exception\InvalidArgumentException;

try {
    $memories = $mem0->listMemories();
} catch (Mem0ApiException $e) {
    echo "API Error: " . $e->getMessage() . "\n";
    echo "Status Code: " . $e->getStatusCode() . "\n";
    echo "Response Body: " . $e->getResponseBody() . "\n";
} catch (HttpClientException $e) {
    echo "HTTP Client Error: " . $e->getMessage() . "\n";
} catch (DeserializationException $e) {
    echo "Serialization Error: " . $e->getMessage() . "\n";
} catch (InvalidArgumentException $e) {
    echo "Invalid Argument: " . $e->getMessage() . "\n";
}