AI Systems for Social Robot Companions

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
AI Systems for Social Robot Companions
Complex
from 2 weeks to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

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

  1. Storing everything without filtering — clogs the vector space with noise.
  2. No escalation for crisis signals — a risk to the user.
  3. Ignoring data privacy requirements (GDPR/local laws) — fines up to 4% of turnover.
  4. 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.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.