Skip to main content

Availability

For how filters work, refer to Filters.

Script Input

Each script gets an input object with the request context:

Response Filter Input

Response filters use the same ScriptInput/ScriptOutput structure as request filters, with additional response-specific fields:
Input Object (Streaming):
Output Object:
Note: The payload and messages fields in output are ignored for response filters.

Tool Filter Input

A tool request filter gets the tool call arguments in input.raw_input. The arguments have the same format on every transport:
A request filter can change parameters, payload, and headers, and return them in output.payload. It cannot change operation_id. If it tries, AI Studio ignores the change and logs a warning. input.context contains tool_id, tool_name, app_id, and user_id, and also session_id and call_id when they are available. A tool response filter gets the tool response body as a plain string. The tyk.redact_pattern() helper is designed for LLM message structures (JSON format) and does not work with tool responses. Use the text module instead.

Script Output

Every script must set the output variable. If it does not, the script fails.

Example: Blocking Filter (PII Detection)

This script blocks requests containing PII patterns:

Example: Modification Filter (Email Redaction)

This script redacts emails while allowing the request to proceed:

Example: Advanced Modification (Messages Array)

This script shows complex message modification using the messages array approach:

Example: Combined Blocking and Modification

This script redacts emails but blocks if SSN is detected:

Helper Functions

The tyk module provides helper functions for common message modification tasks:
  1. redact_pattern(input, pattern, replacement):
    • Redacts a regex pattern from all messages (system, user, assistant)
    • Parameters:
      • input - The input object provided to your script
      • pattern - Regular expression pattern (string)
      • replacement - Replacement string
    • Returns: Modified payload as string
    • Example: tyk.redact_pattern(input, "\\d{3}-\\d{2}-\\d{4}", "[SSN]")
Vendor-Agnostic: Helper functions automatically handle differences between OpenAI, Anthropic, Google AI, and other vendor formats. On Amazon Bedrock requests, redact_pattern and tyk.redact rewrite the text in the request body in place. Bedrock still accepts the request, because system and content blocks, tool calls, tool results, images, and documents stay as they are. AI Studio never rewrites the model settings in additionalModelRequestFields. For tyk.detect and tyk.redact, refer to Guardrails.

Message Modification Approaches

Approach 1: Helper Functions (Simple, recommended for pattern-based redaction)
Approach 2: Messages Array (Flexible, recommended for complex logic)
When a script returns messages, AI Studio rebuilds the request body from them as plain {role, content} messages. Tool calls, tool results, images, and cache_control are lost. On requests that use tools, return a payload instead. Guardrail filters are not affected, because they rewrite only the redacted strings.

Tool Results and Segments

Available from Tyk AI Studio 2.3.0. input.messages is a simplified view of the request. For Anthropic and Google requests, it does not contain tool results. On LLM requests, a script can read input.segments instead. It lists each message text and each tool result, as a guardrail reads them. Each segment has these fields:
  • index: the position of the segment
  • role: system, user, assistant, or tool
  • kind: text or tool_result
  • tool_name: the name of the tool, for a tool result
  • text: the text of the segment
input.segments is a copy. To change the request, call tyk.quarantine_segment(input, index, placeholder) and set the result as the output payload. The function returns the request body with that segment replaced and all other fields kept. An empty placeholder uses [content removed by policy]. AI Studio fills input.segments only for scripts that use it, because it must parse the body. It is empty outside LLM requests. A script that screens tool results must block the request in these cases:
  • input.segments_readable is false, because AI Studio cannot read the body.
  • tyk.quarantine_segment returns an error for a flagged segment.
Use guardrail filters to screen tool results where you can. Guardrails also read the JSON escapes in tool output. A script sees the tool results as the client sent them. To test a script on input.segments, refer to Test the Script. In a chat room, request filters also get the answer of a user to a client tool card. They get it in the same way as a typed message.

Message Context

Scripts can access rich contextual information:

Available Tengo Modules

Scripts can import the Tengo standard library modules. The os module needs FILTER_SCRIPT_ALLOW_OS. Refer to Runtime Limits and Outbound Calls. The main modules are:

text Module

json Module

fmt Module

tyk Module

When a tyk.llm call fails, the script stops by default. A request filter whose script stops blocks the request, but a response filter lets the response through. From 2.3.0, set return_errors: true in the settings to get an error value instead. The script then decides what to do:
The error value can contain provider details. Put it in a compliance event. Do not put it in output.message, because the end user sees the message. Example - Use LLM for PII Detection:
Example - Call External Service:

Compliance Event Reporting

Filter scripts can emit structured Compliance Events to record governance-relevant activity, such as PII redactions, content rewrites, or guardrail triggers, without affecting the block/allow decision. Events flow through the analytics pipeline into the Compliance dashboard, where they appear in the Filter Events tab with severity filters, drill-down, and CSV export. To emit events, set the optional compliance_events field on the script output:
For the event fields, refer to Event Schema. Conditional Emission. Most filters should only emit events when a condition actually fires. Build the list dynamically:
Events work in every filter scope. For the recording behavior, the fields that AI Studio adds, and events from Edge Gateways, refer to Compliance Events.

Runtime Limits and Outbound Calls

Filter scripts run on the goroutine that serves the request. For this reason, AI Studio limits every script execution. Each limit is an environment variable. For defaults and formats, refer to the AI Studio environment variables. A change takes effect on the next execution, without a restart. tyk.makeHTTPRequest accepts only http and https URLs. It follows the outbound network policy, also for redirects. To allow an internal classifier, add it to LLM_UPSTREAM_ALLOWED_INTERNAL_HOSTS. tyk.llm gets the credential of the target LLM in the same way as the gateway. An LLM with a key stored as a $SECRET/... reference works from a script. From 2.3.0, an $ENV/... reference works only when AI_STUDIO_ENV_REF_ALLOWLIST lists the variable. Because response filters let the response through when they time out, a slow response filter does not block. If a response filter removes sensitive data, such as PII, a timeout sends the response to the user without that change. Keep response filter scripts fast, and test them with large responses. AI Studio compiles each script one time and caches it. Each execution runs on its own copy, so executions do not share state. When the caller of a request or chat session disconnects, AI Studio stops the script.
Scripts cannot use the Tengo os module unless you set FILTER_SCRIPT_ALLOW_OS=true.With FILTER_SCRIPT_ALLOW_OS=true, each filter script can read the environment of the process, including TYK_AI_SECRET_KEY and the database credentials. It can also read and write files, and run programs on AI Studio and on each Edge Gateway that runs the filter. A user who can create or edit a filter then controls the host. From 2.3.0, AI Studio and the Edge Gateway log a SECURITY WARNING at startup when this setting is on.

Legacy Script API

Old API (still supported for backward compatibility):
New Unified API (recommended):