Skip to content

MemNet AI Python SDK

The MemNet AI Python SDK provides a Python interface for interacting with the MemNet AI API, including basic request clients and enhanced features.

Features

  • Basic API request client
  • Memory management functionality
  • Thinking functionality
  • Dream functionality
  • Common sense functionality
  • Enhanced client (with LLM integration)

Get API Key

Obtain API Key from MemNetAI dashboardapi-key.png

Installation

bash
pip install memnetai-python-sdk

Quick Start

Basic Client Usage

python
from memnetai import MemNetAIClient
from memnetai import Message

# Initialize client
client = MemNetAIClient(
    base_url="https://api.memnetai.com",
    api_key="your_api_key"
)

messages = [
    Message(role="user", content="What is artificial intelligence?", character="default")
]

# 1. Memory
response = client.memories(
    memory_agent_name="default",
    namespace="default",
    messages=messages
)
print("Memory result:", response)

# 2. Recall
response = client.recall(
    memory_agent_name="default",
    namespace="default",
    query="What is artificial intelligence?",
)
print("Recall result:", response)

# 3. Thinking functionality
response = client.think(
    memory_agent_name="default",
    namespace="default",
)
print("Thinking result:", response)

# 4. Dream functionality
response = client.dream(
    memory_agent_name="default",
    namespace="default",
)
print("Dream result:", response)

# 5. Common sense functionality
response = client.common_sense(
    common_sense_database_id="default",
    common_sense_text="Science",
)
print("Common sense result:", response)

Enhanced Client Usage

python
from memnetai import MemNetAIClientPlus
from memnetai import OpenAIConfig


def test_memnetaiclientplus():
    # Configure OpenAI parameters
    openai_config = OpenAIConfig(
        memnetai_api_key="your_memnet_api_key",
        memory_agent_name="default",
        base_url="https://api.openai.com/v1",
        api_key="your_openai_api_key",
        model_name="gpt-3.5-turbo",
    )

    # Initialize enhanced client
    client_plus = MemNetAIClientPlus(config=openai_config)

    # Intelligent conversation (automatic memory and recall)
    try:
        while True:
            if not client_plus.input():  # User entered exit command
                break
            response = client_plus.chat()
            print(f"AI response: {response}")
    except KeyboardInterrupt:
        print("\nClosing program...")
    finally:
        client_plus.close()


if __name__ == "__main__":
    test_memnetaiclientplus()

API Documentation

1. Basic Client (MemNetAIClient)

Initialization Parameters

python
MemNetAIClient(api_key, base_url="https://api.memnetai.com")
ParameterTypeRequiredDefaultDescription
api_keystrRequiredNoneMemNet AI API key
base_urlstrOptional"https://api.memnetai.com"MemNet AI API base URL

1.1 Memory Management (memories)

python
memories(memory_agent_name, namespace, messages, language="zh-CN", is_third_person=0, metadata="", async_mode=0)
ParameterTypeRequiredDefaultDescription
memory_agent_nameOptional[str]RequiredNoneMemory agent name
messagesList[Message]RequiredNoneMessage list containing memory content to be saved
namespacestrOptionaldefaultNamespace for isolating memories from different applications
languagestrOptional"zh-CN"Expected language for memory summary
is_third_personintOptional0Whether to use third person (0: no, 1: yes)
metadatastrOptional""Metadata information
async_modeintOptional0Whether to enable asynchronous memory (0: synchronous, 1: asynchronous)

1.2 Recall Function (recall)

python
recall(memory_agent_name, namespace, query, character="User", recall_deep=1, is_include_linked_new_memories_from_invalid=0, is_using_associative_thinking=1, is_using_common_sense_database=1, is_using_global_common_sense_database=1, is_using_memory_agent_common_sense_database=0, common_sense_database_id_list=None, is_returning_detailed_memory_info=0)
ParameterTypeRequiredDefaultDescription
memory_agent_nameOptional[str]RequiredNoneMemory agent name
querystrRequiredNoneQuery content
namespacestrOptionaldefaultNamespace for isolating memories from different applications
characterstrOptional"User"Character name
recall_deepintOptional1Recall depth
is_include_linked_new_memories_from_invalidintOptional0Whether to include new memories linked from invalid memories
is_using_associative_thinkingintOptional1Whether to use associative thinking
is_using_common_sense_databaseintOptional1Whether to use common sense database
is_using_global_common_sense_databaseintOptional1Whether to use global common sense database
is_using_memory_agent_common_sense_databaseintOptional0Whether to use memory agent common sense database
common_sense_database_id_listOptional[List[str]]OptionalNoneList of common sense database IDs
is_returning_detailed_memory_infointOptional0Whether to return detailed memory information

1.3 Thinking Function (think)

python
think(memory_agent_name, namespace, subject="", async_mode=1, is_auto=0)
ParameterTypeRequiredDefaultDescription
memory_agent_nameOptional[str]RequiredNoneMemory agent name
namespacestrOptionaldefaultNamespace for isolating memories from different applications
subjectstrOptional""Thinking subject, randomly selected from historical memories if not specified
async_modeintOptional1Asynchronous mode (0: synchronous, 1: asynchronous)
is_autointOptional0Whether to auto-think (0: manual, 1: auto)

1.4 Dream Function (dream)

python
dream(memory_agent_name, namespace, subject="", async_mode=1, is_auto=0)
ParameterTypeRequiredDefaultDescription
memory_agent_nameOptional[str]RequiredNoneMemory agent name
namespacestrOptionaldefaultNamespace for isolating memories from different applications
subjectstrOptional""Dream subject, randomly selected from historical memories if not specified
async_modeintOptional1Asynchronous mode (0: synchronous, 1: asynchronous)
is_autointOptional0Whether to auto-dream (0: manual, 1: auto)

1.5 Common Sense Function (common_sense)

python
common_sense(common_sense_database_id, common_sense_text, async_mode=1)
ParameterTypeRequiredDefaultDescription
common_sense_database_idstrRequiredNoneCommon sense memory database ID
common_sense_textstrRequiredNoneCommon sense database text content
async_modeintOptional1Asynchronous mode (0: synchronous, 1: asynchronous)

1.6 Task Management Methods

All task management methods support the following parameter formats:

Method NameParametersDescription
memories_detailtask_idGet memory task details
memories_progresstask_idGet memory task progress
memories_allNoneGet all memory tasks
memories_deletetask_idDelete memory task
think_detailtask_idGet thinking task details
think_allNoneGet all thinking tasks
think_deletetask_idDelete thinking task
dream_detailtask_idGet dream task details
dream_allNoneGet all dream tasks
dream_deletetask_idDelete dream task
common_sense_detailtask_idGet common sense task details
common_sense_progresstask_idGet common sense task progress
common_sense_allNoneGet all common sense tasks
common_sense_deletetask_idDelete common sense task

2. Enhanced Client (MemNetAIClientPlus)

Initialization Parameters

python
MemNetAIClientPlus(config)
ParameterTypeRequiredDefaultDescription
configConfigRequiredNoneConfiguration object, supports OpenAIConfig, etc.

2.1 Intelligent Conversation (chat)

python
chat()
ParameterTypeRequiredDefaultDescription
NoneNoneNoneNoneChat with LLM, automatically handles memory and recall

Return value: str - Complete response content from LLM

2.2 User Input (input)

python
input(message=None)
ParameterTypeRequiredDefaultDescription
messageOptional[str]OptionalNoneUser input message, obtained from console if not provided

Return value: bool - Whether to continue running (True: continue, False: exit)

2.3 Close Client (close)

python
close()
ParameterTypeRequiredDefaultDescription
NoneNoneNoneNoneClear message queue and release resources

3. Configuration Classes

3.1 Basic Configuration (Config)

python
Config(memnetai_api_key, memory_agent_name, namespace="default", memnetai_base_url="https://api.memnetai.com", window_size=32)
ParameterTypeRequiredDefaultDescription
memnetai_api_keystrRequiredNoneMemNet AI API key
memory_agent_namestrRequiredNoneMemory agent name
namespacestrOptional"default"Namespace for isolating memories from different applications
memnetai_base_urlstrOptional"https://api.memnetai.com"MemNet AI API base URL
window_sizeintOptional32Conversation window size, minimum value is 32

3.2 OpenAI Configuration (OpenAIConfig)

python
OpenAIConfig(memnetai_api_key, memory_agent_name, base_url, model_name, api_key, namespace="default", memnetai_base_url="https://api.memnetai.com", temperature=0.7, max_tokens=500, window_size=32)
ParameterTypeRequiredDefaultDescription
memnetai_api_keystrRequiredNoneMemNet AI API key
memory_agent_namestrRequiredNoneMemory agent name
base_urlstrRequiredNoneOpenAI API base URL
model_namestrRequiredNoneOpenAI model name (e.g., "gpt-3.5-turbo")
api_keystrRequiredNoneOpenAI API key
namespacestrOptional"default"Namespace for isolating memories from different applications
memnetai_base_urlstrOptional"https://api.memnetai.com"MemNet AI API base URL
temperaturefloatOptional0.7Model temperature parameter, controls output randomness
max_tokensintOptional500Maximum number of tokens generated by the model
window_sizeintOptional32Conversation window size, minimum value is 32

4. Message Class (Message)

python
Message(role, content, character="")
ParameterTypeRequiredDefaultDescription
rolestrRequiredNoneRole (e.g., "user", "assistant", "system")
contentstrRequiredNoneMessage content
characterstrOptional""Character name

Example Applications

Complete Conversation Application

python
from memnetai import MemNetAIClientPlus
from memnetai import OpenAIConfig

# Configuration parameters
config = OpenAIConfig(
    # MemNet AI configuration
    memnetai_api_key="your_memnet_api_key",
    memory_agent_name="my_agent",
    namespace="my_app",
    
    # OpenAI configuration
    base_url="https://api.openai.com/v1",
    api_key="your_openai_api_key",
    model_name="gpt-3.5-turbo",
    temperature=0.7,
    max_tokens=1000,
    
    # Conversation window configuration
    window_size=64
)

# Create client
client = MemNetAIClientPlus(config)

try:
    print("Welcome to MemNet AI Enhanced Client! Enter 'exit' or 'quit' to exit.")
    while True:
        user_input = input("\nUser: ")
        if user_input.lower() in ['exit', 'quit']:
            print("Thank you for using, goodbye!")
            break
            
        # Add user message and get AI response
        if client.input(user_input):
            response = client.chat()
            print(f"AI: {response}")
            
finally:
    client.close()

Error Handling

MemNetAIClient has built-in the following error handling:

  • HTTP errors: Display status code and response content
  • Network errors: Prompt when unable to connect to the server
  • Timeout errors: Prompt for request timeout
  • JSON parsing errors: Prompt when API returns non-JSON data
  • Unknown exceptions: Catch all other exceptions and display detailed information

Notes

  1. API Key Security: Do not hardcode API keys in your code, it is recommended to use environment variables or configuration files
  2. Network Connection: Ensure your network can access MemNet AI and OpenAI API
  3. Version Compatibility: This SDK requires Python 3.9+
  4. Asynchronous Mode: Most APIs support asynchronous mode, suitable for handling large numbers of requests
  5. Window Size: The window_size parameter controls the length of conversation history, it is recommended to adjust according to memory conditions, the minimum value is 32, and memories will be stored once every 16 conversations.