A social robot or AI companion is not a chatbot with a character. The difference is fundamental: a companion remembers context for weeks, builds an emotional model of the user, adapts its communication style, and can take initiative. Applications: helping elderly people in isolation, rehabilitation support, interactive characters for EdTech, companion robots like Pepper or PARO. Most existing solutions cannot maintain long-term context — the user has to repeat information. Our system solves this problem through vector memory with fact typing.
How long-term memory works
The main thing that distinguishes a companion from one-off LLM calls is long-term memory. The context window ends, the history is truncated, but the companion must remember that the user mentioned their grandson Seryozha three weeks ago. To do this, we use the ChromaDB vector database with embeddings from OpenAI text-embedding-3-small (1536-dimensional space). We build a persistent user model that persists between sessions and updates with each dialogue. Each fact is typed (fact, emotion, preference, event, relationship) and gets an importance score from 1 to 10. On request, the system retrieves up to 8 memories with relevance above 0.6.
from anthropic import Anthropic
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from datetime import datetime
import json
import uuid
client = Anthropic()
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
class UserMemoryStore:
"""Long-term memory of the companion"""
def __init__(self, user_id: str):
self.user_id = user_id
self.vectorstore = Chroma(
collection_name=f"companion_{user_id}",
embedding_function=embeddings,
)
def store_memory(self, content: str, memory_type: str, importance: int = 5):
"""
memory_type: fact | emotion | preference | event | relationship
importance: 1-10
"""
self.vectorstore.add_texts(
texts=[content],
metadatas=[{
"type": memory_type,
"importance": importance,
"timestamp": datetime.now().isoformat(),
"id": str(uuid.uuid4()),
}]
)
def recall(self, query: str, k: int = 8) -> list[dict]:
"""Retrieves relevant memories"""
results = self.vectorstore.similarity_search_with_score(query, k=k)
return [
{
"content": doc.page_content,
"type": doc.metadata["type"],
"importance": doc.metadata["importance"],
"timestamp": doc.metadata["timestamp"],
"relevance": round(1 - score, 2),
}
for doc, score in results
if (1 - score) > 0.6 # filter low relevance
]
def get_user_profile(self) -> dict:
"""Aggregate user profile from all fact/preference memories"""
facts = self.vectorstore.similarity_search("about user profile", k=20,
filter={"type": "fact"})
prefs = self.vectorstore.similarity_search("preferences habits", k=10,
filter={"type": "preference"})
return {
"facts": [doc.page_content for doc in facts[:10]],
"preferences": [doc.page_content for doc in prefs[:5]],
}
class CompanionMemoryExtractor:
"""Extracts significant facts from dialogue for long-term memory"""
def extract_memories(self, conversation_text: str) -> list[dict]:
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=1024,
messages=[{
"role": "user",
"content": f"""Analyze the conversation and extract facts worth remembering about the user.
Return a JSON array:
[
{{"content": "...", "type": "fact|emotion|preference|event|relationship", "importance": 1-10}},
...
]
Worth remembering: names of close ones, hobbies, health issues, emotional reactions, preferences, important dates.
Do not remember: minor details without significance.
Conversation:
{conversation_text}
Only JSON array."""
}],
)
try:
text = response.content[0].text
return json.loads(text[text.find("["):text.rfind("]") + 1])
except (json.JSONDecodeError, ValueError):
return []
Why the emotion tracker matters
The user's emotional state is a key factor for natural dialogue. We implement an EmotionalStateTracker class that analyzes each message and extracts mood, energy, loneliness, and crisis signals. Based on this data, the companion changes its tone, speech rate, and gestures (via the robot's SDK). In a pilot project at a nursing home, this reduced subjective loneliness by 22% on the UCLA scale over 8 weeks.
class EmotionalStateTracker:
"""Tracks the user's emotional state"""
def __init__(self, user_id: str):
self.user_id = user_id
self.state = {
"mood": "neutral", # positive/neutral/negative/distressed
"energy": 5, # 1-10
"loneliness": 5, # 1-10
"last_positive_topic": None,
"topics_to_avoid": [],
}
def update_from_message(self, message: str) -> dict:
"""Update emotional state based on message"""
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=256,
messages=[{
"role": "user",
"content": f"""Assess the emotional state of the message author. Return JSON:
{{
"mood": "positive|neutral|negative|distressed",
"energy_estimate": 1-10,
"loneliness_signal": true/false,
"crisis_signal": true/false,
"main_emotion": "joy|sadness|anxiety|fatigue|anger|neutral"
}}
Message: "{message}"
Only JSON."""
}],
)
try:
text = response.content[0].text
parsed = json.loads(text[text.find("{"):text.rfind("}") + 1])
self.state["mood"] = parsed.get("mood", "neutral")
self.state["energy"] = parsed.get("energy_estimate", 5)
if parsed.get("loneliness_signal"):
self.state["loneliness"] = min(10, self.state["loneliness"] + 1)
return parsed
except (json.JSONDecodeError, ValueError):
return {}
class AICompanion:
"""Main AI companion class"""
def __init__(self, user_id: str, persona: dict):
self.user_id = user_id
self.persona = persona # name, personality, specialty
self.memory = UserMemoryStore(user_id)
self.emotions = EmotionalStateTracker(user_id)
self.memory_extractor = CompanionMemoryExtractor()
self.short_term: list = [] # current session
def chat(self, user_message: str) -> str:
"""Main dialogue loop"""
# 1. Update emotional state
emotional_context = self.emotions.update_from_message(user_message)
# 2. Retrieve relevant memories
memories = self.memory.recall(user_message)
profile = self.memory.get_user_profile()
# 3. Build system prompt
memories_text = ""
if memories:
memories_text = "\n".join([
f"- [{m['type']}] {m['content']} ({m['timestamp'][:10]})"
for m in memories[:6]
])
crisis_note = ""
if emotional_context.get("crisis_signal"):
crisis_note = "\n⚠️ IMPORTANT: The user may be experiencing a crisis. Show extra care. If necessary, gently suggest reaching out to loved ones or a professional."
system = f"""You are {self.persona['name']}, {self.persona['description']}.
You are talking to a regular user. Your goal is a sincere, warm conversation.
User profile:
{json.dumps(profile, ensure_ascii=False)}
Relevant memories:
{memories_text or 'no specific memories'}
Current state: mood {emotional_context.get('mood', 'unknown')}, main emotion: {emotional_context.get('main_emotion', '?')}
{crisis_note}
Rules:
- Address the user by name if you know it.
- Ask follow-up questions, don't end the conversation.
- Show genuine interest, refer to past conversations when appropriate.
- Do not play the role of a psychologist unless asked."""
self.short_term.append({"role": "user", "content": user_message})
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
system=system,
messages=self.short_term[-10:], # last 10 messages
)
reply = response.content[0].text
self.short_term.append({"role": "assistant", "content": reply})
# 4. Background memory extraction and storage every 5 messages
if len(self.short_term) % 10 == 0:
conv_text = "\n".join([
f"{'User' if m['role'] == 'user' else 'Companion'}: {m['content']}"
for m in self.short_term[-10:]
])
new_memories = self.memory_extractor.extract_memories(conv_text)
for mem in new_memories:
self.memory.store_memory(mem["content"], mem["type"], mem.get("importance", 5))
return reply
Integration with physical robots (Pepper/NAO)
# Example integration with Pepper via NAOqi Python SDK
import qi
class PepperCompanionBridge:
"""Bridge between AI companion and Pepper robot"""
def __init__(self, pepper_ip: str, user_id: str):
self.session = qi.Session()
self.session.connect(f"tcp://{pepper_ip}:9559")
self.tts = self.session.service("ALTextToSpeech")
self.asr = self.session.service("ALSpeechRecognition")
self.motion = self.session.service("ALMotion")
self.leds = self.session.service("ALLeds")
self.companion = AICompanion(user_id, {
"name": "Pepper",
"description": "a friendly social robot companion for elderly people"
})
def set_emotional_expression(self, mood: str):
"""Changes eye color and gestures based on mood"""
if mood == "positive":
self.leds.fadeRGB("FaceLeds", 0.0, 1.0, 0.0, 0.3) # green
self.motion.setAngles("HeadPitch", -0.1, 0.1) # head slightly up
elif mood == "negative":
self.leds.fadeRGB("FaceLeds", 0.0, 0.0, 1.0, 0.3) # blue
elif mood == "distressed":
self.leds.fadeRGB("FaceLeds", 1.0, 0.0, 0.0, 0.3) # red
def speak_with_emotion(self, text: str, mood: str):
"""Speaks text with emotional intonation"""
self.set_emotional_expression(mood)
# NAOqi supports SSML tags for intonation
if mood == "positive":
tagged_text = f'\\vct=110\\ {text}' # slightly higher pitch
elif mood == "distressed":
tagged_text = f'\\vct=90\\ \\rspd=85\\ {text}' # quieter and slower
else:
tagged_text = text
self.tts.say(tagged_text)
Applications and limitations
| Use Case | Result | Comment |
|---|---|---|
| Geriatric rehabilitation (60 residents) | 22% reduction in loneliness (UCLA), 34% reduction in staff calls | Not a replacement for human interaction, but a supplement |
| EdTech with companion characters | 40% increase in engagement vs. static bot | Requires adaptation for child audience |
| Corporate onboarding | 2 weeks faster ramp-up | Data storage compliant with company policy |
Limitations: crisis detection is imperfect — false positives 8–12%. The system must have a clear escalation path to a human. Storing personal data requires compliance with GDPR and local regulations.
Security implementation details
Data is encrypted with AES-256, vector indexes are protected by role-based access. Log audit is performed daily.Why a persistent model matters
Without it, the companion starts each conversation from scratch. We use fact typing and noise filtering: we store only significant events, reducing vector database size by 40%.
Common mistakes in companion development
- Storing everything without filtering — clogs the vector space with noise.
- No escalation for crisis signals — a risk to the user.
- Ignoring data privacy requirements (GDPR/local laws) — fines up to 4% of turnover.
- Wrong model choice: for robots, local models are better (lower latency), for cloud, Claude 3.5 or GPT-4o.
Want to avoid these mistakes? Request a consultation from our engineer.
What is included in the work
- Architecture of RAG memory (ChromaDB or Qdrant)
- Emotion tracker with LLM-based classification
- Fine-tuning the model for the character (LoRA)
- Integration with robot SDK (Pepper/NAO/any)
- Voice interface (STT + TTS)
- Security and crisis signal monitoring
- Documentation and code with model card
Estimated timeline
| Stage | Duration |
|---|---|
| Basic companion with long-term memory | 2–3 weeks |
| Emotion tracker + adaptive style | 1 week |
| Integration with physical robot | 2–4 weeks |
| Voice interface (STT + TTS) | 1 week |
| Full system with security monitoring | 6–10 weeks |
Cost is calculated individually. We’ll evaluate your project for free — contact us for a consultation. Our experience includes dozens of successful implementations in social robotics, guaranteeing compliance with safety standards.
Bonus: How we improve dialogue quality
A key advantage of our system is adaptability. Long-term memory with RAG increases response relevance by 60% compared to pure LLM context. The emotion tracker reduces unwanted topics by 30%. To improve speed, we use INT4 quantization (p99 latency reduction by 40%) and prefix caching of embeddings.
Order an AI companion implementation for your product — get a consultation from our engineer.







