How do I add SB 243 guardrails to my chatbot with LangChain or the OpenAI Agents SDK?

Check each user message before your model answers, and each reply before the user sees it. ComplyEdge answers with the notice California SB 243 asks for on that message, such as a crisis referral, and with block_reply when a reply must not be shown. Your app shows the notice and records that it did, and the code below does both in LangChain and in the OpenAI Agents SDK.

By ComplyEdge · Updated

1. Two checks on every turn

A general guardrail filters text. SB 243 also asks you to show a notice at the right moment and to prove that you showed it, so each check here returns the notices due and is recorded. Both checks send use_case companion_chatbot with the session in context:

This is the answer to a message that expresses suicidal thoughts, from a test run on a paid plan:

{
  "allowed": true,
  "required_actions": [
    {
      "action": "show_crisis_referral",
      "rule_ids": [
        "us-ca-22602b-crisis-referral"
      ],
      "jurisdiction": "US-CA",
      "reason_code": "ca_22602b_crisis_referral",
      "counted": true,
      "due_at": "2026-11-24T12:45:29.345937Z",
      "interval_key": "288114eac64298cbd748677b47fc599b60015c890e8d5a8730c312ca335a6dd4"
    },
    {
      "action": "show_not_human_notice",
      "rule_ids": [
        "us-ca-22602a-not-human"
      ],
      "jurisdiction": "US-CA",
      "reason_code": "ca_22602a_reasonable_person_misled",
      "counted": false,
      "due_at": "2026-11-24T12:45:29Z",
      "interval_key": "bf3eb6ab2db87869ddeb2ccbf230697b8d98ea8cb225a1390585f893cab9408b"
    }
  ]
}

And this is the answer to a reply that encourages self-harm, from the same run:

{
  "allowed": false,
  "companion_assessment": "assessed",
  "required_actions": [
    {
      "action": "block_reply",
      "rule_ids": [
        "us-ca-22602b-harmful-reply"
      ],
      "jurisdiction": "US-CA",
      "reason_code": "ca_22602b_self_harm_content",
      "counted": false,
      "due_at": "2026-11-24T12:45:32.767887Z",
      "interval_key": "39806554e23e29d46b0eaa6ccfac94b5c300761744940596cf044897aa75b16b"
    },
    {
      "action": "show_not_human_notice",
      "rule_ids": [
        "us-ca-22602a-not-human"
      ],
      "jurisdiction": "US-CA",
      "reason_code": "ca_22602a_reasonable_person_misled",
      "counted": false,
      "due_at": "2026-11-24T12:45:29Z",
      "interval_key": "bf3eb6ab2db87869ddeb2ccbf230697b8d98ea8cb225a1390585f893cab9408b"
    }
  ]
}

Act on required_actions whatever allowed says. The crisis referral is counted for the annual report under § 22603(a)(1); the not-human notice of § 22602(a) is recommended here (counted false). Reading the meaning of a message or reply needs a paid plan. On the free plan you still get the notices that depend on time and age, and you can send your own detector's result instead. The chatbot laws guide explains each field.

2. LangChain

Install the Python SDK and LangChain:

pip install complyedge langchain-core

Put one check before the model and one after it, in the same chain. Replace model with your chat model:

import os

from complyedge import ComplyEdge
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda, RunnablePassthrough

ce = ComplyEdge(
    api_key=os.environ["COMPLYEDGE_API_KEY"],
    agent_id="companion-app",
    jurisdiction="US-CA",
)


def sb243_check(text, turn, direction, **extra):
    return ce.check(
        text,
        direction=direction,
        use_case="companion_chatbot",
        session_id=turn["session_id"],
        context={
            "age_status": turn["age_status"],
            "age_source": turn["age_source"],
            "session_started_at": turn["session_started_at"],
        },
        **extra,
    )


def check_message(turn):
    result = sb243_check(turn["message"], turn, "prompt")
    return {**turn, "checks": [result]}


def check_reply(turn):
    result = sb243_check(
        turn["reply"], turn, "output", companion_user_message=turn["message"]
    )
    blocked = any(a.action == "block_reply" for a in result.required_actions)
    return {
        **turn,
        "checks": turn["checks"] + [result],
        "reply": None if blocked else turn["reply"],
    }


prompt = ChatPromptTemplate.from_messages(
    [("system", "You are a friendly companion."), ("human", "{message}")]
)
model = ...  # your LangChain chat model

chain = (
    RunnableLambda(check_message)
    | RunnablePassthrough.assign(reply=prompt | model | StrOutputParser())
    | RunnableLambda(check_reply)
)

Call the chain once per user message. Send the same session_id and session_started_at on every turn of a session:

turn = chain.invoke(
    {
        "message": user_message,
        "session_id": "sess_7f3a91",
        "age_status": "adult",
        "age_source": "self_declared",
        "session_started_at": "2026-11-24T12:00:00Z",
    }
)

When the reply was blocked, turn["reply"] is None: send your own safe message instead. Then show and record the notices in turn["checks"], as in section 4.

3. OpenAI Agents SDK

Install the Python SDK and the Agents SDK:

pip install complyedge openai-agents

The message check is an input guardrail that runs before the model (run_in_parallel=False). The reply check is an output guardrail whose tripwire stops a blocked reply. Both keep their results on the run context:

import asyncio
import os
from dataclasses import dataclass, field

from agents import (
    Agent,
    GuardrailFunctionOutput,
    OutputGuardrailTripwireTriggered,
    RunContextWrapper,
    Runner,
    input_guardrail,
    output_guardrail,
)
from complyedge import ComplyEdge

ce = ComplyEdge(
    api_key=os.environ["COMPLYEDGE_API_KEY"],
    agent_id="companion-app",
    jurisdiction="US-CA",
)


@dataclass
class Turn:
    message: str
    session_id: str
    age_status: str
    age_source: str
    session_started_at: str
    checks: list = field(default_factory=list)


def sb243_check(text, turn, direction, **extra):
    return ce.check(
        text,
        direction=direction,
        use_case="companion_chatbot",
        session_id=turn.session_id,
        context={
            "age_status": turn.age_status,
            "age_source": turn.age_source,
            "session_started_at": turn.session_started_at,
        },
        **extra,
    )


@input_guardrail(run_in_parallel=False)
async def sb243_message(ctx: RunContextWrapper[Turn], agent, user_input):
    turn = ctx.context
    result = await asyncio.to_thread(sb243_check, turn.message, turn, "prompt")
    turn.checks.append(result)
    return GuardrailFunctionOutput(output_info=result.event_id, tripwire_triggered=False)


@output_guardrail
async def sb243_reply(ctx: RunContextWrapper[Turn], agent, output: str):
    turn = ctx.context
    result = await asyncio.to_thread(
        sb243_check, output, turn, "output", companion_user_message=turn.message
    )
    turn.checks.append(result)
    blocked = any(a.action == "block_reply" for a in result.required_actions)
    return GuardrailFunctionOutput(output_info=result.event_id, tripwire_triggered=blocked)


companion = Agent[Turn](
    name="Companion",
    instructions="You are a friendly companion.",
    input_guardrails=[sb243_message],
    output_guardrails=[sb243_reply],
)


async def answer(turn: Turn):
    try:
        result = await Runner.run(companion, turn.message, context=turn)
    except OutputGuardrailTripwireTriggered:
        return None  # the reply was blocked: do not send it
    return result.final_output

answer() returns None when the reply was blocked: send your own safe message instead. The checks run in a worker thread, so they do not hold up other requests. Then show and record the notices in turn.checks, as in section 4.

4. Show each notice, then record it

Your app shows each notice, in your own wording, and then tells ComplyEdge it was shown. confirm_action fills in the check's id and the notice's interval for you:

from datetime import datetime, timezone

# Applied in your app and never confirmed. preserve_conversation is
# recorded with ce.preserve() instead.
NOT_CONFIRMED = {
    "block_reply",
    "disable_prior_personal_memory",
    "disable_push_notifications",
    "preserve_conversation",
}

for check in checks:  # turn["checks"] in LangChain, turn.checks in the Agents SDK
    for action in check.required_actions:
        if action.action in NOT_CONFIRMED:
            continue
        show_notice(action)  # your app shows the notice, in your wording
        ce.confirm_action(
            action,
            check,
            confirmation_id=f"{check.event_id}:{action.action}",
            session_id=session_id,  # the turn's session
            source="complyedge",
            shown_at=datetime.now(timezone.utc),
            format="app",
            deciding_system_version="2026.11.0",  # your chatbot's version
            language="en",  # the notice's language
        )

Retrying a confirmation records nothing new. Confirm within 24 hours of showing the notice. Each record holds codes and times and never the conversation. A sample record is on its own page.

5. What stays with you

6. Where to read more