Bottom Linear Gradient  Lines image

Article

9 min

read

A Semantic Gate Asks One Question Before an AI Agent Acts

A decision model checks what the caller meant before a SignalWire AI agent runs a function

Anthony Minessale

Anthony Minessale

CEO

Verify Caller Intent Before Your Voice AI Takes Action

In this article

Share

Angular Gradient Image

Build it free.

Create a space and ship your first call flow in minutes.

Subscribe

Tags

Voice AI

AI Agents

Developer Tutorials

A caller on a phone carrier's support line says, "I'm thinking about cancelling. What would that cost me?" The model hears "cancel" and calls cancel_plan. On this SignalWire agent, that function carries a semantic gate. Before anything reaches the cancellation code, a separate decision model answers the developer's question: has the caller explicitly asked to cancel their plan? The answer falls well short of the threshold. The plan stays active, and the model is told to ask whether the caller wants to cancel or only wants to hear the cost.

A semantic gate is a yes or no question attached to a function, answered right before the platform runs it. The decision model reads the recent conversation, the application's own record of the call, and the exact call the model proposed. The function runs when the answer clears the developer's threshold. Otherwise nothing is dispatched, and the model receives the developer's on_fail output as an ordinary tool result.

Gates are written in SWML, or with SemanticGate in the Python and TypeScript server SDKs. The support line's code runs on the Python SDK, signalwire-sdk 3.18.0.

Where a gate fits in System-Directed AI

SignalWire agents run on System-Directed AI. At each step, the model knows only what that step tells it and sees only that step's tools. Handlers in the developer's code check the real account before anything changes. The model requests an action, and the platform decides what runs.

Those layers settle which functions exist at a given moment and what is true in the application's systems. A gate adds a question about meaning: did the caller ask, and did they agree to that amount? Steps decide which doors exist, gates ask a question at the door, and handlers check what is true behind it.

The model never sees the gate or its score. When a gate stops a function, the model gets a result written by the developer, the same way any function returns one.

What the decision model reads

Each check sends the decision model a snapshot of the call, taken when the check starts. A question refers to each part by its name:

Name

What it holds

conversation

The most recent part of the call, oldest first, 20 entries by default. It includes what the agent was told to say, such as say actions and, on standard agents, fillers. An agent reply the caller cut off is marked interrupted.

semantic_state

Whatever the application stored in global_data.semantic_state. Nothing else from global_data is sent.

proposed_function

The function's name and description, and the arguments exactly as they would be dispatched.

visual_input

On a video call, the caller's newest frames, for a gate that asks for them.

Each gate has a threshold above 0 and at most 1, and passes when the probability of yes is at or above it. A function runs only when every one of its gates passes.

Each check also has a time budget, 2.5 seconds by default. A check that cannot finish, because it ran out of time or the decision model failed, does not run the function either. The model is never told that the action happened.

Defining a gate in Python or SignalWire Markup Language (SWML)

In the Python SDK, a gate is a SemanticGate passed to define_tool(). This one guards the support line's cancellation:

from signalwire import AgentBase, FunctionResult, SemanticGate

asked_to_cancel = SemanticGate(
    "Has the caller explicitly asked to cancel their plan in `conversation`?",
    true_means="The caller says they want to cancel.",
    false_means="The caller asked about cancelling, or said something else.",
    threshold=0.95,
    on_fail=FunctionResult(
        tool_result="cancel_plan was not run.",
        tool_prompt="Ask whether the caller wants to cancel the plan or hear what cancelling would cost.",
    ),
    id="asked_to_cancel",
)


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        self.prompt_add_section("Role", body="You answer the support line for a phone carrier.")

        self.define_tool(
            name="cancel_plan",
            description="Cancel the caller's plan.",
            parameters={
                "type": "object",
                "properties": {"reason": {"type": "string", "description": "Why they are cancelling."}},
            },
            handler=self.cancel_plan,
            gates=[asked_to_cancel],
            gate_fillers={"default": ["Let me check that."]},
        )

    def cancel_plan(self, args, raw_data):
        # Runs only after every gate on cancel_plan passed
        return FunctionResult("The plan is cancelled. The final bill is due on the 1st.")
from signalwire import AgentBase, FunctionResult, SemanticGate

asked_to_cancel = SemanticGate(
    "Has the caller explicitly asked to cancel their plan in `conversation`?",
    true_means="The caller says they want to cancel.",
    false_means="The caller asked about cancelling, or said something else.",
    threshold=0.95,
    on_fail=FunctionResult(
        tool_result="cancel_plan was not run.",
        tool_prompt="Ask whether the caller wants to cancel the plan or hear what cancelling would cost.",
    ),
    id="asked_to_cancel",
)


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        self.prompt_add_section("Role", body="You answer the support line for a phone carrier.")

        self.define_tool(
            name="cancel_plan",
            description="Cancel the caller's plan.",
            parameters={
                "type": "object",
                "properties": {"reason": {"type": "string", "description": "Why they are cancelling."}},
            },
            handler=self.cancel_plan,
            gates=[asked_to_cancel],
            gate_fillers={"default": ["Let me check that."]},
        )

    def cancel_plan(self, args, raw_data):
        # Runs only after every gate on cancel_plan passed
        return FunctionResult("The plan is cancelled. The final bill is due on the 1st.")
from signalwire import AgentBase, FunctionResult, SemanticGate

asked_to_cancel = SemanticGate(
    "Has the caller explicitly asked to cancel their plan in `conversation`?",
    true_means="The caller says they want to cancel.",
    false_means="The caller asked about cancelling, or said something else.",
    threshold=0.95,
    on_fail=FunctionResult(
        tool_result="cancel_plan was not run.",
        tool_prompt="Ask whether the caller wants to cancel the plan or hear what cancelling would cost.",
    ),
    id="asked_to_cancel",
)


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        self.prompt_add_section("Role", body="You answer the support line for a phone carrier.")

        self.define_tool(
            name="cancel_plan",
            description="Cancel the caller's plan.",
            parameters={
                "type": "object",
                "properties": {"reason": {"type": "string", "description": "Why they are cancelling."}},
            },
            handler=self.cancel_plan,
            gates=[asked_to_cancel],
            gate_fillers={"default": ["Let me check that."]},
        )

    def cancel_plan(self, args, raw_data):
        # Runs only after every gate on cancel_plan passed
        return FunctionResult("The plan is cancelled. The final bill is due on the 1st.")
from signalwire import AgentBase, FunctionResult, SemanticGate

asked_to_cancel = SemanticGate(
    "Has the caller explicitly asked to cancel their plan in `conversation`?",
    true_means="The caller says they want to cancel.",
    false_means="The caller asked about cancelling, or said something else.",
    threshold=0.95,
    on_fail=FunctionResult(
        tool_result="cancel_plan was not run.",
        tool_prompt="Ask whether the caller wants to cancel the plan or hear what cancelling would cost.",
    ),
    id="asked_to_cancel",
)


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        self.prompt_add_section("Role", body="You answer the support line for a phone carrier.")

        self.define_tool(
            name="cancel_plan",
            description="Cancel the caller's plan.",
            parameters={
                "type": "object",
                "properties": {"reason": {"type": "string", "description": "Why they are cancelling."}},
            },
            handler=self.cancel_plan,
            gates=[asked_to_cancel],
            gate_fillers={"default": ["Let me check that."]},
        )

    def cancel_plan(self, args, raw_data):
        # Runs only after every gate on cancel_plan passed
        return FunctionResult("The plan is cancelled. The final bill is due on the 1st.")

The question names its input, conversation, in backticks, the way the decision model sees it. true_means and false_means spell out the near miss: a caller who asks about cancelling has not asked to cancel. The 0.95 threshold suits an action that is hard to undo.

on_fail becomes the function's result. tool_result states what happened, tool_prompt adds an instruction, and the model writes its own reply to the caller from both. gate_fillers is what the caller hears while the check runs.

The SDK checks every gate by the platform's rules when the tool is defined. A gate the platform would refuse raises ValueError in the developer's code instead of reaching a call. The platform drops any function with an invalid gate, so a gated function can never run without its gates.

The same gate in SWML sits on the function in SWAIG.functions:

SWAIG:
  functions:
    - function: cancel_plan
      description: Cancel the caller's plan.
      web_hook_url: https://example.com/swaig
      gate_fillers:
        default:
          - Let me check that.
      gates:
        - id: asked_to_cancel
          question: Has the caller explicitly asked to cancel their plan in `conversation`?
          criteria:
            "true": The caller says they want to cancel.
            "false": The caller asked about cancelling, or said something else.
          threshold: 0.95
          on_fail:
            response:
              tool_result: cancel_plan was not run.
              tool_prompt

SWAIG:
  functions:
    - function: cancel_plan
      description: Cancel the caller's plan.
      web_hook_url: https://example.com/swaig
      gate_fillers:
        default:
          - Let me check that.
      gates:
        - id: asked_to_cancel
          question: Has the caller explicitly asked to cancel their plan in `conversation`?
          criteria:
            "true": The caller says they want to cancel.
            "false": The caller asked about cancelling, or said something else.
          threshold: 0.95
          on_fail:
            response:
              tool_result: cancel_plan was not run.
              tool_prompt

SWAIG:
  functions:
    - function: cancel_plan
      description: Cancel the caller's plan.
      web_hook_url: https://example.com/swaig
      gate_fillers:
        default:
          - Let me check that.
      gates:
        - id: asked_to_cancel
          question: Has the caller explicitly asked to cancel their plan in `conversation`?
          criteria:
            "true": The caller says they want to cancel.
            "false": The caller asked about cancelling, or said something else.
          threshold: 0.95
          on_fail:
            response:
              tool_result: cancel_plan was not run.
              tool_prompt

SWAIG:
  functions:
    - function: cancel_plan
      description: Cancel the caller's plan.
      web_hook_url: https://example.com/swaig
      gate_fillers:
        default:
          - Let me check that.
      gates:
        - id: asked_to_cancel
          question: Has the caller explicitly asked to cancel their plan in `conversation`?
          criteria:
            "true": The caller says they want to cancel.
            "false": The caller asked about cancelling, or said something else.
          threshold: 0.95
          on_fail:
            response:
              tool_result: cancel_plan was not run.
              tool_prompt

A gate can check the arguments or the application's record

A gate's question can be about the call the model is making. On a refund, the model proposes an amount, and the gate asks whether the caller agreed to it:

agreed_amount = SemanticGate(
    "Has the caller agreed to the refund amount in `proposed_function` in `conversation`?",
    threshold=0.9,
    on_fail="refund_charge was not run. Confirm the amount with the caller first.",
    id="agreed_amount",
)
agreed_amount = SemanticGate(
    "Has the caller agreed to the refund amount in `proposed_function` in `conversation`?",
    threshold=0.9,
    on_fail="refund_charge was not run. Confirm the amount with the caller first.",
    id="agreed_amount",
)
agreed_amount = SemanticGate(
    "Has the caller agreed to the refund amount in `proposed_function` in `conversation`?",
    threshold=0.9,
    on_fail="refund_charge was not run. Confirm the amount with the caller first.",
    id="agreed_amount",
)
agreed_amount = SemanticGate(
    "Has the caller agreed to the refund amount in `proposed_function` in `conversation`?",
    threshold=0.9,
    on_fail="refund_charge was not run. Confirm the amount with the caller first.",
    id="agreed_amount",
)

When a caller has said "Twenty is fine" and the model calls refund_charge with 200, the decision model sees both. proposed_function holds 200 while conversation holds twenty, so the answer is no and no refund is issued.

A question can also be about what the application recorded. A caller can say "I already confirmed it," and the decision model has no way to check that claim. A gate that asks about semantic_state judges what the application itself established instead. The same holds for arithmetic and dates. The application works out the answer, stores it in semantic_state, and the gate asks about the stored result.

Confirming a change uses the SDK's Proposal pattern

The hardest gate to write is the one that waits for a yes. A caller's "yes" might answer an earlier question, arrive before the read-back finished, or be an "uh-huh" said while the agent was still talking. A decision model asked to find consent anywhere in a long call has far more to weigh than one asked about a single read-back.

The Python SDK's Proposal pattern narrows it. One function proposes the change: it records the change in semantic_state, reads it back word for word, and waits for the caller. The function that makes the change carries the gates from confirm_gates(), judged only on what was said since the proposal:

from signalwire import AgentBase, FunctionResult
from signalwire.patterns import Proposal

plan_change = Proposal("change_plan", decline_tool="keep_plan")

NEW_PLAN = {
    "type": "object",
    "properties": {"new_plan": {"type": "string", "description": "The plan the caller wants, by name"}},
    "required": ["new_plan"],
}


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        # ... the role and the cancel_plan tool, as above ...
        self.define_tool("review_plan_change", "Read the plan change back to the caller",
                         NEW_PLAN, self.review_plan_change)
        self.define_tool("change_plan", "Change the plan the caller said yes to",
                         {}, self.change_plan, gates=plan_change.confirm_gates())
        self.define_tool("keep_plan", "Keep the caller's current plan",
                         {}, self.keep_plan)

    def review_plan_change(self, args, raw_data):
        read_back = f"That's a switch to the {args['new_plan']} plan, starting with your next bill. Is that right?"
        return plan_change.propose(read_back, raw_data=raw_data, details={"new_plan": args["new_plan"]})

    def change_plan(self, args, raw_data):
        # The plan comes from the application's record of the proposal, not from the model
        new_plan = raw_data["global_data"]["semantic_state"]["new_plan"]
        return plan_change.complete(f"The plan is now {new_plan}, from the next bill.")

    def keep_plan(self, args, raw_data):
        return FunctionResult("The plan stays as it is.")
from signalwire import AgentBase, FunctionResult
from signalwire.patterns import Proposal

plan_change = Proposal("change_plan", decline_tool="keep_plan")

NEW_PLAN = {
    "type": "object",
    "properties": {"new_plan": {"type": "string", "description": "The plan the caller wants, by name"}},
    "required": ["new_plan"],
}


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        # ... the role and the cancel_plan tool, as above ...
        self.define_tool("review_plan_change", "Read the plan change back to the caller",
                         NEW_PLAN, self.review_plan_change)
        self.define_tool("change_plan", "Change the plan the caller said yes to",
                         {}, self.change_plan, gates=plan_change.confirm_gates())
        self.define_tool("keep_plan", "Keep the caller's current plan",
                         {}, self.keep_plan)

    def review_plan_change(self, args, raw_data):
        read_back = f"That's a switch to the {args['new_plan']} plan, starting with your next bill. Is that right?"
        return plan_change.propose(read_back, raw_data=raw_data, details={"new_plan": args["new_plan"]})

    def change_plan(self, args, raw_data):
        # The plan comes from the application's record of the proposal, not from the model
        new_plan = raw_data["global_data"]["semantic_state"]["new_plan"]
        return plan_change.complete(f"The plan is now {new_plan}, from the next bill.")

    def keep_plan(self, args, raw_data):
        return FunctionResult("The plan stays as it is.")
from signalwire import AgentBase, FunctionResult
from signalwire.patterns import Proposal

plan_change = Proposal("change_plan", decline_tool="keep_plan")

NEW_PLAN = {
    "type": "object",
    "properties": {"new_plan": {"type": "string", "description": "The plan the caller wants, by name"}},
    "required": ["new_plan"],
}


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        # ... the role and the cancel_plan tool, as above ...
        self.define_tool("review_plan_change", "Read the plan change back to the caller",
                         NEW_PLAN, self.review_plan_change)
        self.define_tool("change_plan", "Change the plan the caller said yes to",
                         {}, self.change_plan, gates=plan_change.confirm_gates())
        self.define_tool("keep_plan", "Keep the caller's current plan",
                         {}, self.keep_plan)

    def review_plan_change(self, args, raw_data):
        read_back = f"That's a switch to the {args['new_plan']} plan, starting with your next bill. Is that right?"
        return plan_change.propose(read_back, raw_data=raw_data, details={"new_plan": args["new_plan"]})

    def change_plan(self, args, raw_data):
        # The plan comes from the application's record of the proposal, not from the model
        new_plan = raw_data["global_data"]["semantic_state"]["new_plan"]
        return plan_change.complete(f"The plan is now {new_plan}, from the next bill.")

    def keep_plan(self, args, raw_data):
        return FunctionResult("The plan stays as it is.")
from signalwire import AgentBase, FunctionResult
from signalwire.patterns import Proposal

plan_change = Proposal("change_plan", decline_tool="keep_plan")

NEW_PLAN = {
    "type": "object",
    "properties": {"new_plan": {"type": "string", "description": "The plan the caller wants, by name"}},
    "required": ["new_plan"],
}


class SupportLine(AgentBase):
    def __init__(self):
        super().__init__(name="support-line", route="/support")
        # ... the role and the cancel_plan tool, as above ...
        self.define_tool("review_plan_change", "Read the plan change back to the caller",
                         NEW_PLAN, self.review_plan_change)
        self.define_tool("change_plan", "Change the plan the caller said yes to",
                         {}, self.change_plan, gates=plan_change.confirm_gates())
        self.define_tool("keep_plan", "Keep the caller's current plan",
                         {}, self.keep_plan)

    def review_plan_change(self, args, raw_data):
        read_back = f"That's a switch to the {args['new_plan']} plan, starting with your next bill. Is that right?"
        return plan_change.propose(read_back, raw_data=raw_data, details={"new_plan": args["new_plan"]})

    def change_plan(self, args, raw_data):
        # The plan comes from the application's record of the proposal, not from the model
        new_plan = raw_data["global_data"]["semantic_state"]["new_plan"]
        return plan_change.complete(f"The plan is now {new_plan}, from the next bill.")

    def keep_plan(self, args, raw_data):
        return FunctionResult("The plan stays as it is.")

confirm_gates() returns three gates, asked together in one check:

  • answered: the caller's latest turn is an answer, and not a listening sound made over the read-back.

  • agreed: that answer is a yes to this change.

  • read_back: what the caller answered was a read-back of this change.

The questions are the platform's own, replayed against logged confirmation checks.

change_plan takes no arguments. It reads the new plan from semantic_state, the record of what was read back, so the model cannot swap in a different plan. After the change, complete() records what was done, and a later proposal is judged on its own read-back.

When a gate stops change_plan, the model is told why and answers the caller in words before it calls another tool. Two of the gates quote the proposal from semantic_state in what the model is told. The SDK's guide gives the confirmation its own step. That step's only tools are the confirm tool, the decline tool and a tool that notes other requests. "Yes, and can you add a line for my daughter?" then becomes two calls.

Proposal(..., unclear=True, threshold=0.6) lets the gates answer unclear as well as yes or no. An unclear answer asks the caller again, up to twice in a row for the same proposal, and a third counts as a no.

On a video call, a gate can look at the camera

A gate with visual_input also sees the caller's newest video frames. On the support line, a caller verifies on camera:

id_on_camera = SemanticGate(
    "Is the caller holding a photo ID up to the camera in `visual_input`?",
    threshold=0.9,
    visual_input=1,
    on_fail="verify_identity was not run. Ask the caller to hold their ID up to the camera.",
    id="id_on_camera",
)
id_on_camera = SemanticGate(
    "Is the caller holding a photo ID up to the camera in `visual_input`?",
    threshold=0.9,
    visual_input=1,
    on_fail="verify_identity was not run. Ask the caller to hold their ID up to the camera.",
    id="id_on_camera",
)
id_on_camera = SemanticGate(
    "Is the caller holding a photo ID up to the camera in `visual_input`?",
    threshold=0.9,
    visual_input=1,
    on_fail="verify_identity was not run. Ask the caller to hold their ID up to the camera.",
    id="id_on_camera",
)
id_on_camera = SemanticGate(
    "Is the caller holding a photo ID up to the camera in `visual_input`?",
    threshold=0.9,
    visual_input=1,
    on_fail="verify_identity was not run. Ask the caller to hold their ID up to the camera.",
    id="id_on_camera",
)

The gate checks that an ID is on camera, and checking the ID against the account stays in the handler. Passing visual_input=1 to define_tool() for verify_identity sends the handler the frame the gate judged, never a newer one. When the call has no video frame to show, the gate fails without being asked. Frames are taken at most one per second, none older than eight seconds, and go to the decision model as part of the check.

What the caller hears while a gate is checked

A gated function's wait_file plays only after its gates pass. By default, the function's own fillers start as soon as the model calls it, while the check runs. A filler that announces the action, such as "OK, cancelling your plan now," is then heard even when the gate says no. On standard agents it also lands in the conversation the gate reads.

Two settings prevent that. A neutral gate_fillers phrase such as "Let me check that." covers the check, and fillers_at_gates=False holds a function's own fillers until after a pass.

Every check lands in the call record

Each checked function call carries a semantic_gates entry in its record, delivered with the post-prompt data and the calling.ai.swaig event. For the cancellation question at the top, a fail looks like this:

"semantic_gates": {
  "evaluation_id": "d7b5c0f2-…",
  "phase": "text",
  "outcome": "fail",
  "dispatched": false,
  "latency_ms": 212,
  "gates": [
    {"id": "asked_to_cancel", "threshold": 0.95, "confidence": 0.12, "pass": false}
  ]
}
"semantic_gates": {
  "evaluation_id": "d7b5c0f2-…",
  "phase": "text",
  "outcome": "fail",
  "dispatched": false,
  "latency_ms": 212,
  "gates": [
    {"id": "asked_to_cancel", "threshold": 0.95, "confidence": 0.12, "pass": false}
  ]
}
"semantic_gates": {
  "evaluation_id": "d7b5c0f2-…",
  "phase": "text",
  "outcome": "fail",
  "dispatched": false,
  "latency_ms": 212,
  "gates": [
    {"id": "asked_to_cancel", "threshold": 0.95, "confidence": 0.12, "pass": false}
  ]
}
"semantic_gates": {
  "evaluation_id": "d7b5c0f2-…",
  "phase": "text",
  "outcome": "fail",
  "dispatched": false,
  "latency_ms": 212,
  "gates": [
    {"id": "asked_to_cancel", "threshold": 0.95, "confidence": 0.12, "pass": false}
  ]
}

outcome is pass, fail or unclear, or names an error such as timeout, and dispatched says whether the function ran. Each gate's confidence sits beside its threshold, so thresholds can be tuned on real calls. The post-prompt data also carries a tally of every check in the call.

As starting points, the platform guide recommends 0.9 or above for actions that are hard to undo. The confirm gates use 0.8, or about 0.6 when they can answer unclear.

Questions a decision model can answer well

The decision model reads each question literally and answers only it, so the wording does most of the work:

  • A good question asks one thing. "Did the caller confirm the order and the address?" works better as two gates.

  • A question names its input in backticks: conversation, semantic_state, proposed_function or visual_input.

  • criteria say what counts as yes and as no, which matters most for near misses.

  • Calculations and date comparisons happen in the application, which stores the result in semantic_state.

  • A question about the application's record holds up when a caller insists something is already done.

Documentation and the SDK

Semantic gates need signalwire-sdk 3.6.0 or later, gates on video 3.7.1, and the confirm pattern 3.8.0. The current release is 3.18.0.

Bottom Linear Gradient  Lines image

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.

The Communications Stack for What's Next

APIs built for speed. Infrastructure built for scale. AI built in from day one.