AI Cognitive Behavioral Therapy System (CBT AI)

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 1 servicesAll 1566 services
AI Cognitive Behavioral Therapy System (CBT AI)
Complex
~2-4 weeks
FAQ
AI Development Areas
AI Solution Development Stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1215
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_logo-advance_0.png
    B2B Advance company logo design
    561
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823

AI System for Cognitive Behavioral Therapy (CBT)

CBT lends itself well to structuring: its techniques are repeatable protocols with clear logic. ABC model, thought records, exposure, behavioral activation — all can be automated as interactive AI-guided exercises. Not standalone therapy, but expanding access to CBT methods between therapist sessions.

Key CBT Modules in the System

Thought Record — structured ABC (Activating event → Belief → Consequence), identification of cognitive distortions, formulation of alternative thoughts.

Behavioral Activation — activity tracking with pleasure/mastery ratings, activity planning, monitoring activity-mood connections.

Exposure Hierarchy — building anxiety scale, gradual exposure with SUDS (Subjective Units of Distress Scale) tracking.

Mindfulness Exercises — guided meditations with voice, present-moment journal.

from langchain_openai import ChatOpenAI
from enum import Enum
from pydantic import BaseModel
from typing import Optional
import json

class CognitiveDistortion(Enum):
    ALL_OR_NOTHING = "all-or-nothing thinking"
    CATASTROPHIZING = "catastrophizing"
    MIND_READING = "mind reading"
    FORTUNE_TELLING = "fortune telling"
    EMOTIONAL_REASONING = "emotional reasoning"
    SHOULD_STATEMENTS = "should statements"
    OVERGENERALIZATION = "overgeneralization"
    PERSONALIZATION = "personalization"
    MENTAL_FILTER = "mental filter"
    LABELING = "labeling"

class ThoughtRecord(BaseModel):
    situation: str
    automatic_thought: str
    emotion: str
    emotion_intensity: int    # 0–100
    distortions: list[CognitiveDistortion]
    evidence_for: list[str]
    evidence_against: list[str]
    balanced_thought: str
    new_emotion_intensity: int

class CBTSessionEngine:
    THOUGHT_RECORD_PROMPT = """You are an AI assistant helping practice CBT thought record technique.
Guide the user through steps methodically, one at a time.
Don't move to the next step until the user has answered the current one.
Ask open-ended questions. Don't interpret for the user.
When the user identifies a cognitive distortion — explain it briefly, without judgment."""

    DISTORTION_DETECTION_PROMPT = """Analyze the automatic thought and identify cognitive distortions.

Thought: "{thought}"
Situation context: "{situation}"

From the list of CBT distortions, identify 1–3 that best fit:
- All-or-nothing thinking: everything/nothing, always/never
- Catastrophizing: worst possible outcome is inevitable
- Mind reading: "I know what they think"
- Fortune telling: "This will definitely fail"
- Emotional reasoning: "I feel like a failure, so I am a failure"
- Should statements: "I must", "I can't"
- Overgeneralization: "This always happens"
- Personalization: taking responsibility for external events

Return JSON: {{distortions: [{{name, explanation_for_user}}]}}"""

    def __init__(self):
        self.llm = ChatOpenAI(model="gpt-4o", temperature=0.3)

    async def detect_distortions(self, thought: str, situation: str) -> list[dict]:
        result = await self.llm.ainvoke(
            self.DISTORTION_DETECTION_PROMPT.format(
                thought=thought,
                situation=situation
            )
        )
        return json.loads(result.content)["distortions"]

    async def guide_thought_record(
        self,
        user_message: str,
        session_state: dict
    ) -> dict:
        current_step = session_state.get("current_step", "situation")

        step_prompts = {
            "situation": "What exactly happened? Describe the specific situation — when, where, what occurred.",
            "thought": "What thought crossed your mind at that moment? Try to catch the first automatic reaction.",
            "emotion": "What did you feel? Name the emotion and rate its intensity from 0 to 100.",
            "evidence_for": "What facts support this thought? Only real facts, not feelings.",
            "evidence_against": "What facts contradict this thought?",
            "balanced_thought": "Considering all the facts, how can you formulate a more balanced thought?"
        }

        # Save user's response
        session_state[current_step] = user_message

        # If step is 'thought' — analyze distortions
        if current_step == "thought" and "situation" in session_state:
            distortions = await self.detect_distortions(
                user_message, session_state["situation"]
            )
            session_state["distortions"] = distortions

        # Determine next step
        steps = list(step_prompts.keys())
        current_idx = steps.index(current_step)
        next_step = steps[current_idx + 1] if current_idx < len(steps) - 1 else "complete"

        session_state["current_step"] = next_step

        if next_step == "complete":
            return await self._summarize_thought_record(session_state)

        response_text = step_prompts[next_step]

        # When moving to "evidence_for" add distortion info
        if next_step == "evidence_for" and session_state.get("distortions"):
            distortion_names = ", ".join([d["name"] for d in session_state["distortions"]])
            response_text = f"In your thought I see signs of: **{distortion_names}**. But let's not rush to conclusions.\n\n{response_text}"

        return {"response": response_text, "step": next_step, "state": session_state}

Behavioral Activation: Activity Tracking

class BehavioralActivationTracker:
    async def log_activity(
        self,
        activity: str,
        pleasure_score: int,    # 0–10
        mastery_score: int,     # 0–10
        mood_before: int,       # 0–10
        mood_after: int         # 0–10
    ) -> dict:
        mood_change = mood_after - mood_before
        insight = await self._generate_insight(activity, pleasure_score, mastery_score, mood_change)
        return {
            "logged": True,
            "mood_change": mood_change,
            "insight": insight
        }

    async def _generate_insight(self, activity, pleasure, mastery, mood_change) -> str:
        if mood_change > 2:
            return f"After {activity} your mood improved by {mood_change} points. This is an important signal — such activities should be scheduled more often."
        elif mood_change < -1:
            return f"Activity {activity} lowered your mood. Let's talk about it — sometimes discomfort is temporary and related to avoidance, not the activity itself."
        return "Activity recorded. Let's continue tracking patterns."

Case study: corporate mental health support program, 1200 employees. CBT module used as self-help between meetings with corporate psychologist. Over 3 months: 340 unique users, average 4.2 sessions per user. Survey results: 67% noted reduced anxiety thought intensity, 71% found thought record useful as a tool.

Ethical restrictions: system doesn't work with severe depression, suicidal thoughts, psychosis. All such cases are automatically referred to a specialist.

Timeframe: basic CBT modules (thought record + behavioral activation): 4–6 weeks; full platform with progress tracking and analytics: 10–14 weeks.