A library for managing LLM conversations and context
Project description
Generic LLM Memorizer
A Python library for managing LLM conversations and context with automatic fact extraction and structured data handling.
Installation
pip install generic-llm-memorizer
Usage
Basic Conversation Management
from generic_llm_memorizer import Conversation
# Create a new conversation
conv = Conversation(system_prompt="You are a helpful assistant.")
# Add messages
conv.add_user_message("Hello, how are you?")
conv.add_assistant_message("I'm doing well, thank you! How can I help you today?")
# Get conversation history
messages = conv.get_messages()
# Format for LLM API (expects list of dicts with role and content)
from generic_llm_memorizer import format_conversation_for_prompt
formatted = format_conversation_for_prompt(conv)
# Output: [{"role": "system", "content": "You are a helpful assistant."}, ...]
from generic_llm_memorizer import Conversation
# Create a new conversation
conv = Conversation(system_prompt="You are a helpful assistant.")
# Add messages
conv.add_user_message("Hello, how are you?")
conv.add_assistant_message("I'm doing well, thank you! How can I help you today?")
# Get conversation history
messages = conv.get_messages()
# Format for LLM API (expects list of dicts with role and content)
from generic_llm_memorizer import format_conversation_for_prompt
formatted = format_conversation_for_prompt(conv)
# Output: [{"role": "system", "content": "You are a helpful assistant."}, ...]
Persisting Conversations
from generic_llm_memorizer import Conversation
# Save conversation to JSON
conv_json = conv.to_json()
with open("conversation.json", "w") as f:
f.write(conv_json)
# Load conversation from JSON
with open("conversation.json", "r") as f:
conv_json = f.read()
loaded_conv = Conversation.from_json(conv_json)
from generic_llm_memorizer import Conversation
# Save conversation to JSON
conv_json = conv.to_json()
with open("conversation.json", "w") as f:
f.write(conv_json)
# Load conversation from JSON
with open("conversation.json", "r") as f:
conv_json = f.read()
loaded_conv = Conversation.from_json(conv_json)
Utility Functions
Extending with Custom Models
You can create your own Pydantic models for domain-specific extractions:
from pydantic import BaseModel
from typing import List
from enum import Enum
class Priority(str, Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
class Task(BaseModel):
title: str
description: str
priority: Priority
assignee: str
class TaskList(BaseModel):
tasks: List[Task]
# Use with the generic llm_call function
tasks = llm_call("Extract tasks from this conversation", TaskList)
Advanced Usage with Structured Data Extraction
The library now supports a generic llm_call function that works with Pydantic models for structured data extraction:
from typing import Type, TypeVar
from pydantic import BaseModel
from generic_llm_memorizer.conversation import Conversation
from generic_llm_memorizer.memory import Summary, Memory, Fact
# Define a generic type variable bounded by BaseModel
T = TypeVar("T", bound=BaseModel)
def llm_call(prompt: str, model_class: Type[T]) -> T:
"""
Generic LLM call function that returns structured data.
Args:
prompt: The prompt to send to the LLM
model_class: The Pydantic model class to parse the response into
Returns:
An instance of the specified model_class
"""
# In a real implementation, this would call an actual LLM API
# and parse the response into the specified Pydantic model
# Mock implementation for demonstration
if model_class == Summary:
return Summary(content="Mock summary of the conversation")
elif model_class == Memory:
return Memory(facts=[
Fact(
content="Example fact extracted from conversation",
kind="example",
timestamp="2023-01-01T10:00:00Z",
validity="forever"
)
])
# Return a default instance of the model
return model_class()
# Usage with LLMMemorizer
from generic_llm_memorizer.llm_memorizer import LLMMemorizer
conversation = Conversation(system_prompt="You are a helpful assistant")
conversation.add_user_message("Hello, my name is John Doe and I'm a software engineer")
memorizer = LLMMemorizer(
user_id="user_123",
session_id="session_456",
llm_call=llm_call,
conversation=conversation
)
# Extract structured facts
memory = memorizer.extract_facts()
print(f"Extracted {len(memory.facts)} facts")
# Generate structured summary
summary = memorizer.summarize()
print(f"Summary: {summary.content}")
## API Reference
```python
from generic_llm_memorizer import extract_last_user_message, extract_last_assistant_message
# Extract last user message
last_user = extract_last_user_message(conv)
# Extract last assistant message
last_assistant = extract_last_assistant_message(conv)
API Reference
Conversation Class
Manages a conversation with an LLM.
Methods
add_message(role, content, metadata=None): Add a message to the conversationadd_user_message(content, metadata=None): Add a user messageadd_assistant_message(content, metadata=None): Add an assistant messageget_messages(): Get all messagesget_recent_messages(count): Get the most recent messagesclear(): Clear all messagesto_dict(): Convert to dictionary formatto_json(indent=2): Convert to JSON stringfrom_dict(data): Create from dictionary datafrom_json(json_str): Create from JSON string
Message Dataclass
Represents a single message in a conversation.
Attributes
role: Role of the message sender ("user", "assistant", "system", etc.)content: Message contenttimestamp: ISO format timestamp (automatically set)metadata: Additional metadata dictionary
Utility Functions
format_conversation_for_prompt(conversation): Format conversation for LLM APIextract_last_user_message(conversation): Get last user message contentextract_last_assistant_message(conversation): Get last assistant message content
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file generic_llm_memorizer-0.1.3.tar.gz.
File metadata
- Download URL: generic_llm_memorizer-0.1.3.tar.gz
- Upload date:
- Size: 20.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
58feaef6d79951795de9f46159758e8880dc2cd445cc349562682889cbe12acf
|
|
| MD5 |
b2f926ed6bba4ba710cb8710b22bd25d
|
|
| BLAKE2b-256 |
6f99041a47a5ea3b5d226b8cada8545978543820de01d9dccbfb52afe0a3b750
|
File details
Details for the file generic_llm_memorizer-0.1.3-py3-none-any.whl.
File metadata
- Download URL: generic_llm_memorizer-0.1.3-py3-none-any.whl
- Upload date:
- Size: 15.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.6.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1a4e95cf339d9b5ef5d7bd1fc2d274cd5f3189edf99466b2c6935f3c29f72b81
|
|
| MD5 |
4463826222569f322eb80e98e5709de0
|
|
| BLAKE2b-256 |
63dc43adbd40feca166e09a7d2697cab2afa78dba4f4041d18549df68491c636
|