*This page
applies to **Apigee** and **Apigee hybrid**.*


*View [Apigee Edge](https://docs.apigee.com/api-platform/get-started/what-apigee-edge) documentation.*
![](https://fonts.gstatic.com/s/i/googlematerialicons/help/v13/gm_grey-24dp/1x/gm_help_gm_grey_24dp.png)

Apigee supports continuous response streaming from [server-sent event](https://en.wikipedia.org/wiki/Server-sent_events) (SSE) endpoints
to clients in real time. The Apigee SSE feature is useful for handling large language model (LLM) APIs that operate
most effectively by streaming their responses back to the client. SSE streaming reduces latency, and clients can
receive response data as soon as it is generated by an LLM. This feature supports the use of
AI agents that operate in real time environments, such as customer service bots or workflow
orchestrators.

> [!NOTE]
> **Note:** Streaming from SSE endpoints is supported in Apigee and in Apigee hybrid v1.15.0 and newer. The feature is also supported for use with the Apigee Extension Processor.

To use SSE with Apigee simply point an API proxy
to an SSE-enabled target or proxy endpoint. To achieve finer grained
control over the SSE response, Apigee provides a special endpoint flow called
`EventFlow`. Within the context of an `EventFlow`, you can add a [limited set of policies](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#eventflowpolicies) to
perform operations on the SSE response, such as filtering, modifying, or handling errors. To learn more about proxy flows,
see [Controlling API proxies with flows](https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/what-are-flows.md.txt).

> [!NOTE]
> **Note:** Apigee limits each response event to a maximum of 10 MB of data.

## Create an API proxy for SSE

The Apigee
UI provides a template for creating a new proxy that includes an `EventFlow`.

> [!NOTE]
> **Note:** Use of the SSE proxy template is optional. It gives you access to SSE-specific flow variables that can be useful for performing certain policy operations. However, you do not have to use `EventFlow` to use SSE with Apigee.

> [!WARNING]
> **Important:** Use separate target endpoint definitions for SSE targets. Mixing SSE and non-SSE target endpoints together might result in inconsistent behavior such as empty `response.content` flow variables. See [Known issues](https://docs.cloud.google.com/apigee/docs/release/known-issues.md.txt#449012244).

Follow these
steps to create an API proxy with the `EventFlow` template using the Apigee UI:

1. In the Google Cloud console, go to the **Apigee \> Proxy Development \> API Proxies** page.

   [Go to API Proxies](https://console.cloud.google.com/apigee/proxies)
2. In the **API Proxies** pane, click **+ Create**.
3. In the **Create a proxy** pane, under **Proxy template** , select **Proxy with Server-Sent Events (SSE)**.
4. Under **Proxy details** , enter the following:
   - **Proxy name:** Enter a name for the proxy, such as `myproxy`.
   - **Base Path** : Automatically set to the value you enter for **Proxy name** . The **Base
     Path** is part of the URL used to make requests to your API. Apigee uses the URL to match and route incoming requests to the appropriate API proxy.
   - **Description (Optional)**: Enter a description for your new API proxy, such as "Testing Apigee with a simple proxy."
   - **Target (Existing API):** Enter the SSE target URL for the API proxy. For example: `https://mocktarget.apigee.net/sse-events/5`
   - Click **Next**.
5. **Deploy (optional)** :
   - **Deployment environments** : Optional. Use the checkboxes to select one or more environments to which to deploy your proxy. If you prefer not to deploy the proxy at this point, leave the **Deployment environments** field empty. You can always deploy the proxy later.
   - **Service Account** : Optional. A [service account](https://docs.cloud.google.com/iam/docs/service-accounts) for the proxy. The service account represents the identity of the deployed proxy, and determines what permissions it has. This is an advanced feature, and for the purpose of this tutorial, you can ignore it.

   API proxies deployed with an `EventFlow` configuration will be [billed as Extensible](https://docs.cloud.google.com/apigee/docs/api-platform/reference/pay-as-you-go-updated-billing.md.txt).
6. Click **Create**.

See also [Building a simple API proxy](https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/build-simple-api-proxy.md.txt).

## Configure an EventFlow

To achieve finer grained
control over the SSE response, Apigee provides a special endpoint flow called
`EventFlow`. Within the context of an `EventFlow`, you can add a limited set of policies, listed below,
to modify the SSE response before it is streamed back to the client. To learn more about proxy flows,
see [Controlling API proxies with flows](https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/what-are-flows.md.txt).

### Placement of an EventFlow

An`EventFlow` has two attributes:

- `name`: A name to identify the flow.
- `content-type`: The value of this attribute must be `text/event-stream`.

See also [Flow configuration reference](https://docs.cloud.google.com/apigee/docs/api-platform/reference/flow-configuration-reference.md.txt#eventflow).

An `EventFlow` can be placed inside a `TargetEndpoint` or a `ProxyEndpoint` definition
as shown in the following code samples:

### \<ProxyEndpoint\>

```
<ProxyEndpoint name="default">
  <Description/>
  <FaultRules/>
  <PreFlow name="PreFlow">
    <Request/>
    <Response/>
  </PreFlow>
  <PostFlow name="PostFlow">
    <Request/>
    <Response/>
  </PostFlow>
  <Flows/>
  <EventFlow name="EventFlow" content-type="text/event-stream">
    <Response/>
  </EventFlow>
  <HTTPProxyConnection>
    <Properties/>
    <URL>https://httpbin.org/sse</URL>
  </HTTPProxyConnection>
</ProxyEndpoint>
```

### \<TargetEndpoint\>

```
<TargetEndpoint name="default">
  <Description/>
  <FaultRules/>
  <PreFlow name="PreFlow">
    <Request/>
    <Response/>
  </PreFlow>
  <PostFlow name="PostFlow">
    <Request/>
    <Response/>
  </PostFlow>
  <Flows/>
  <EventFlow name="EventFlow" content-type="text/event-stream">
    <Response/>
  </EventFlow>
  <HTTPTargetConnection>
    <Properties/>
    <URL>https://httpbin.org/sse</URL>
  </HTTPTargetConnection>
</TargetEndpoint>
```

> [!NOTE]
> **Note:** If you add multiple `EventFlow` stanzas to a endpoint, only the last one in the endpoint definition is executed. Any `EventFlow` stanzas that appear before the last one are ignored.

It is also important to note that although you can add an `EventFlow` to either a
`TargetEndpoint`, `ProxyEndpoint`, or both, only one `EventFlow` is executed.

The following table shows the execution of `EventFlow` stanzas based on endpoint placement:

| ProxyEndpoint | TargetEndpoint | EventFlow used |
|---|---|---|
| EventFlow in `ProxyEndpoint` | EventFlow in `TargetEndpoint` | EventFlow in `TargetEndpoint` |
| No `EventFlow` | EventFlow in `TargetEndpoint` | EventFlow in `TargetEndpoint` |
| EventFlow in `ProxyEndpoint` | No `EventFlow` | EventFlow in `ProxyEndpoint` |

### Add policies to an EventFlow

You can add up to a total of four policies to the `Response` element of the `EventFlow`. As with all flows,
policies are executed in the order they are added, and you can add [conditional steps](https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/flow-configurations.md.txt) to control their execution.
It's important to note that the types of policies you can add to an `EventFlow` are restricted to the following.
No other types of policies are allowed in an `EventFlow`:

- [DataCapture](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/data-capture-policy.md.txt)
- [Javascript](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt)
- [LLMTokenQuota](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt)
- [MessageLogging](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/message-logging-policy.md.txt)
- [PublishMessage](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/publish-message-policy.md.txt)
- [RaiseFault](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/raise-fault-policy.md.txt)
- [SanitizeModelResponse](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy.md.txt)

> [!NOTE]
> **Note:** When using these policies with SSE streams:
>
> - If the `DataCapture` policy is applied on every event, only the latest value is recorded.
> - `LLMTokenQuota` quota enforcement skips events that lack token usage metadata. Quotas are calculated based only on events that contain explicit token counts.

See also [Attaching and configuring policies in the UI](https://docs.cloud.google.com/apigee/docs/api-platform/develop/attaching-and-configuring-policies-management-ui.md.txt)
and [Attaching and configuring policies in XML files](https://docs.cloud.google.com/apigee/docs/api-platform/develop/attaching-and-configuring-policies-xml-files.md.txt).

<br />

The following examples show an `EventFlow` with a conditional RaiseFault policy step added:

### \<ProxyEndpoint\>

```
<ProxyEndpoint name="default">
  <EventFlow content-type="text/event-stream">
    <Response>
      <Step>
        <Name>Raise-Fault-Cred-Invalid</Name>
        <Condition>fault.name equals "invalid_access_token"</Condition>
      </Step>
    </Response>
  </EventFlow>
  <HTTPProxyConnection>
</ProxyEndpoint></pre>
```

### \<TargetEndpoint\>

```
<TargetEndpoint name="default">
  <EventFlow content-type="text/event-stream">
    <Response>
      <Step>
        <Name>Raise-Fault-Cred-Invalid</Name>
        <Condition>fault.name equals "invalid_access_token"</Condition>
      </Step>
    </Response>
  </EventFlow>
  <HTTPTargetConnection>
</TargetEndpoint></pre>
```

For more `EventFlow` code examples, see the [EventFlow use cases and examples](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#examples) section.

## Flow variables

An `EventFlow` populates three response flow variables. Note that these variables
are only usable within the scope of the current event being processed within the `EventFlow`.
Accessing or setting these variables outside of the `EventFlow` scope has no effect. They
are only meaningful within the context of the `EventFlow`.

- `response.event.current.content`: A string containing the current event's entire response. Apigee does not parse the string in any way. It contains the entire response unchanged, including all of the data fields.

  > [!NOTE]
  > **Note:** Apigee limits each response event to a maximum of 10 MB of data.

  > [!NOTE]
  > **Note:** Setting the value of this variable to a blank string (""), prevents the event from being sent to the client. For an example, see [Filter an SSE response](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#filterresponse).

- `response.event.current.data`: A string containing the data payload of the current event. You can modify this variable in the `EventFlow` to change the data payload sent to the client.
- `response.event.current.count`: Incrementally counts the number of response events sent. This value is updated for each received event. The count will be 1 for the first event, and it increments for subsequent events.

  > [!NOTE]
  > **Note:** If you access this value, in a JavaScript policy, for example, the very first event will have a value of 1; however, the number of events sent to the client at this point will be 0.

See also
[Flow variable reference](https://docs.cloud.google.com/apigee/docs/api-platform/reference/variables-reference.md.txt#response).

## EventFlow use cases and examples

The following examples show how to implement common use cases for SSE proxies:

- [Modify an SSE response](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#modifyresponse)
- [Filter an SSE response](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#filterresponse)
- [Send an SSE event to an external system](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#send-event)
- [Use an Apigee Model Armor policy in an EventFlow](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#model-armor-policy)
- [Error handling in the EventFlow](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#unexpected-response)
- [Propagate fault messages in an EventFlow](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#propagate-error)
- [Use DataCapture to collect token counts in analytics](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#datacapture-token-counts)
- [Use an LLMTokenQuota policy to enforce token quotas in an EventFlow](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#llm-token-quota)

### Modify an SSE response

This example shows how to remove data from an SSE `EventFlow` response before returning it to the client.
The contents of the SSE response is stored in a flow variable called
`response.event.current.content`.
In this case, we use a JavaScript policy to retrieve the value of the flow variable, parse, and
modify it. See also [Flow variables](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#flowvariables).

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new [JavaScript policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt) with the following definition. In this example, the JavaScript code is included directly in the policy. Putting the JavaScript code in a [resource file](https://docs.cloud.google.com/apigee/docs/api-platform/develop/resource-files.md.txt) is another option for configuring the policy.

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <Javascript continueOnError="false" enabled="true" timeLimit="200" name="js-update-resp">
     <DisplayName>js-update-resp</DisplayName>
     <Properties/>
     <Source>
       var event = JSON.parse(context.getVariable("response.event.current.content"));
       event.modelVersion = null;
       context.setVariable("response.event.current.content",JSON.stringify(event));
     </Source>
   </Javascript>
   ```
4. Add the JavaScript policy to the `EventFlow` of the proxy. The `EventFlow` is attached to the default `TargetEndpoint` or `ProxyEndpoint`. This example uses the [Gemini API in Vertex AI](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference) to generate content.

   ### \<ProxyEndpoint\>

   ```
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-update-resp</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPProxyConnection>
   </ProxyEndpoint>
   ```

   ### \<TargetEndpoint\>

   ```
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-update-resp</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPTargetConnection>
   </TargetEndpoint>
   ```
5. Save the proxy and deploy it.
6. Call the deployed proxy:

   ```
   curl -X POST -H 'Content-Type: application/json'  \
     "https://YOUR_APIGEE_ENVIRONMENT_GROUP_HOSTNAME/YOUR_API_PATH" \
     -d '{ "contents":[{"parts":[{"text": "Write a story about a magic pen."}]}]}'
   ```

   #### Show a sample response

   This is a sample response without any filtering applied. Note that the response includes a
   `modelVersion": "gemini-2.5-flash"` attribute.

   ```
   data: {
       "candidates": [
         {
           "content": {
             "parts": [
               {
                 "text": "ara found the pen tucked away in a dusty antique shop, nestled amongst chipped tea"
               }
             ],
             "role": "model"
           }
         }
       ],
       "usageMetadata": {
         "promptTokenCount": 8,
         "totalTokenCount": 8
       },
       "modelVersion": "gemini-2.5-flash"
     }
   ```

   This is another sample response with the JavaScript policy applied. The `modelVersion` attribute is removed.

   ```
   data: {
       "candidates": [
         {
           "content": {
             "parts": [
               {
                 "text": " the fantastical creatures of her imagination.  The quiet beauty of a simple life was a magic all its own.\n"
               }
             ],
             "role": "model"
           },
           "finishReason": "STOP"
         }
       ],
       "usageMetadata": {
         "promptTokenCount": 8,
         "candidatesTokenCount": 601,
         "totalTokenCount": 609,
         "promptTokensDetails": [
           {
             "modality": "TEXT",
             "tokenCount": 8
           }
         ],
         "candidatesTokensDetails": [
           {
             "modality": "TEXT",
             "tokenCount": 601
           }
         ]
       }
     }
   ```

### Filter an SSE response

This example shows how to filter data from an SSE response before returning it to the client.
In this case, we filter event data from the response using a JavaScript policy.
The policy parses the event response into JSON, modifies the JSON to remove the event data,
and then sends the modified response data back to the client.

Like in the previous example, this example retrieves the value of the `response.event.current.content`
flow variable and parses it into JSON, then applies logic to implement the intended filtering.

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new [JavaScript policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt) with the following definition. In this example, the JavaScript code is included directly in the policy. Putting the JavaScript code in a [resource file](https://docs.cloud.google.com/apigee/docs/api-platform/develop/resource-files.md.txt) is another option for configuring the policy.

   ```
   <Javascript continueOnError="false" enabled="true" timeLimit="200" name="js-filter-resp">
     <DisplayName>js-filter-resp</DisplayName>
     <Properties/>
     <Source>
       var event = JSON.parse(context.getVariable("response.event.current.content"));
       if("error" in event){
         // Do not send event to customer
         context.setVariable("response.event.current.content", "");
       }
     </Source>
   </Javascript>
   ```
4. Add the JavaScript policy to the `EventFlow` of the proxy. The `EventFlow` is attached to the default `TargetEndpoint` or `ProxyEndpoint`. This example uses the [Gemini API in Vertex AI](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference) to generate content.

   ### \<ProxyEndpoint\>

   ```
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-filter-resp</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
   	  <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse	</URL>
     </HTTPProxyConnection>
   </ProxyEndpoint>
   ```

   ### \<TargetEndpoint\>

   ```
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-filter-resp</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
   	  <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse	</URL>
     </HTTPTargetConnection>
   </TargetEndpoint>
   ```
5. Save the proxy and deploy it.
6. Call the deployed proxy:

   ```
   curl -X POST -H 'Content-Type: application/json'  \
       "https://YOUR_APIGEE_ENVIRONMENT_GROUP_HOSTNAME/YOUR_API_PATH" \
       -d '{ "contents":[{"parts":[{"text": "Write a story about a magic pen."}]}]}'
   ```

   #### Show a sample response

   Here's a sample of how the response might look without applying any filtering. Notice it includes error data:

   ```
   data: {
       "candidates": [
         {
           "content": {
             "parts": [
               {
                 "text": "El"
               }
             ],
             "role": "model"
           }
         }
       ],
       "usageMetadata": {
         "promptTokenCount": 8,
         "totalTokenCount": 8
       },
       "modelVersion": "gemini-2.5-flash"
     }
       data: {
       "error": "Service temporarily unavailable. We are experiencing high traffic.",
       "modelVersion": "gemini-2.5-flash"
       }
   ```

   Here's another sample response after filtering is applied with the error message scrubbed.

   ```
   data: {
     "candidates": [
       {
         "content": {
           "parts": [
             {
               "text": "El"
             }
           ],
           "role": "model"
         }
       }
     ],
     "usageMetadata": {
       "promptTokenCount": 8,
       "totalTokenCount": 8
     },
     "modelVersion": "gemini-2.5-flash"
   }
   data: {
     "candidates": [
       {
         "content": {
           "parts": [
             {
               "text": "ara found the pen tucked away in a dusty antique shop, nestled amongst chipped tea"
             }
           ],
           "role": "model"
         }
       }
     ],
     "usageMetadata": {
       "promptTokenCount": 8,
       "totalTokenCount": 8
     },
     "modelVersion": "gemini-2.5-flash"
   }
   ```

### Send an SSE event to an external system

In this example, we attach the Apigee [PublishMessage policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/publish-message-policy.md.txt) to the `EventFlow`
to send an SSE event to a [Pub/Sub topic](https://docs.cloud.google.com/pubsub/docs/overview.md.txt).

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new PublishMessage policy with the following definition:

   ```
   <PublishMessage continueOnError="false" enabled="true" name="PM-record-event">
     <DisplayName>PM-record-event</DisplayName>
     <Source>{response.event.current.content}</Source>
     <CloudPubSub>
       <Topic>projects/<customer_project>/topics/<topic_name></Topic>
     </CloudPubSub>
   </PublishMessage>
   ```
4. Add the PublishMessage policy as a step in the `EventFlow` of the API proxy.

   ### \<ProxyEndpoint\>

   ```
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>PM-record-event</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
   </ProxyEndpoint>
   ```

   ### \<TargetEndpoint\>

   ```
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>PM-record-event</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
   </TargetEndpoint>
   ```
5. Deploy and test the API proxy.
6. With your generated content added to the Pub/Sub topic, you can, for example, create a Cloud Run function to process messages from the topic.

### Use an Apigee Model Armor policy in an EventFlow

> [!NOTE]
> **Note:** In Apigee hybrid, Model Armor policies are supported in [v1.15.1](https://docs.cloud.google.com/apigee/docs/hybrid/release-notes.md.txt#October_12_2025) and newer.

You can use the
[SanitizeModelResponse
policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy) to sanitize server-sent events in an `EventFlow`. Set
`<ContinuousScan>` to `true` to check the whole
stream, as in the following steps, or leave it `false` (the default)
to check each event separately. With `true`, the policy holds each
event until Model Armor confirms that its text is clean, and then
releases it whole, unchanged, and in order to later steps and to the client.

For more information about how the policy handles matches, errors, and quotas,
see
[Sanitize
streaming Server-Sent Events (SSE) responses](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy#streaming-sse). For more information about
Model Armor, see
[Model Armor
overview](https://docs.cloud.google.com/security-command-center/docs/model-armor-overview).

To configure the policy, complete the following steps:

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a [SanitizeModelResponse
   policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy) with `<ContinuousScan>true</ContinuousScan>` and `<LLMResponseSource>` configured to extract the text delta from `response.event.current.data`. The following example is for Gemini SSE streams:

   ```xml
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <SanitizeModelResponse async="false" continueOnError="false"
       enabled="true" name="SMR-modelresponse">
     <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
     <DisplayName>SMR-modelresponse</DisplayName>
     <ModelArmor>
       <TemplateName>projects/{project}/locations/{location}/templates/{template-name}</TemplateName>
     </ModelArmor>
     <LLMResponseSource>{jsonPath('$.candidates[-1].content.parts[-1].text',response.event.current.data,true)}</LLMResponseSource>
     <ContinuousScan>true</ContinuousScan>
   </SanitizeModelResponse>
   ```

   For OpenAI-compatible SSE streams, set `<LLMResponseSource>`
   to
   `{jsonPath('$.choices[-1].delta.content',response.event.current.data,true)}`.
   For Anthropic Claude SSE streams, set `<LLMResponseSource>`
   to `{jsonPath('$.delta.text',response.event.current.data,true)}`.
4. Attach the `SanitizeModelResponse` policy to the `<Response>` element of the `EventFlow` in your proxy. If you also use [`LLMTokenQuota`](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#llm-token-quota) or [`DataCapture`](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#datacapture-token-counts) in the `EventFlow`, place `SanitizeModelResponse` first so that those policies receive only checked events:

   ```xml
   <EventFlow name="EventFlow" content-type="text/event-stream">
     <Request/>
     <Response>
       <Step>
         <Name>SMR-modelresponse</Name>
       </Step>
     </Response>
   </EventFlow>
   ```
5. Deploy and test the API proxy.

### Error handling in the EventFlow

By default, the event stream ends when a fault occurs. However,
if you want to do extra debugging you can send fault information to Cloud Logging
as shown in this example.

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new RaiseFault policy with the following definition:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <RaiseFault continueOnError="false" enabled="true" name="RF-Empty-Event">
     <DisplayName>RF-Empty-Event</DisplayName>
     <Properties/>
     <FaultResponse>
       <AssignVariable>
         <Name>faultReason</Name>
         <Value>empty-event</Value>
       </AssignVariable>
     </FaultResponse>
     <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
   </RaiseFault>
   ```
4. Attach the RaiseFault policy to the `EventFlow` of the SSE proxy:

   ```
   <EventFlow content-type="text/event-stream">
     <Response>
       <Step>
         <Name>RF-Empty-Event</Name>
         <Condition>response.event.current.content ~ "data: "</Condition>
       </Step>
     </Response>
   </EventFlow>
   ```
5. Create a MessageLogging policy to log errors. For example:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <MessageLogging continueOnError="false" enabled="true" name="ML-log-error">
     <DisplayName>ML-log-error</DisplayName>
     <CloudLogging>
       <LogName>projects/{organization.name}/logs/apigee_errors</LogName>
       <Message contentType="text/plain">Request failed due to {faultReason}.</Message>
       <ResourceType>api</ResourceType>
     </CloudLogging>
     <logLevel>ALERT</logLevel>
   </MessageLogging>
   ```
6. Add the MessageLogging policy to the FaultRules of the target or proxy endpoint:

   ### \<TargetEndpoint\>

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <TargetEndpoint name="TargetEndpoint-1">
     <Description/>
     <FaultRules>
       <FaultRule name="default-fault">
         <Step>
           <Name>ML-log-error</Name>
         </Step>
       </FaultRule>
     </FaultRules>
     ...
   </TargetEndpoint>
   ```

   ### \<ProxyEndpoint\>

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <ProxyEndpoint name="ProxyEndpoint-1">
     <Description/>
     <FaultRules>
       <FaultRule name="default-fault">
         <Step>
           <Name>ML-log-error</Name>
         </Step>
       </FaultRule>
     </FaultRules>
     ...
   </ProxyEndpoint>
   ```
7. Deploy and test the API proxy.

### Propagate fault errors in an EventFlow

In this example, we show you how to use an `EventFlow` to propagate fault errors to the client.
The process works to notify the client of errors immediately during policy execution.

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new JavaScript policy with the following definition:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     <Javascript continueOnError="false" enabled="true" timeLimit="200" name="js-error">
       <DisplayName>js-error</DisplayName>
       <Properties/>
       <Source>
         if(context.getVariable("response.event.current.count")=="2") {
           throw new Error("Internal Error");
         }
         context.setVariable("response.event.current.content", context.getVariable("response.event.current.content"));
       </Source>
     </Javascript>
   ```

   This policy is designed to throw an error when a specific condition is met.
4. Attach the JavaScript policy to the `EventFlow` of the SSE proxy within the `TargetEndpoint` or `ProxyEndpoint` configuration. This step ensures that the EventFlow processes the policy during response handling:

   ### \<TargetEndpoint\>

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-error</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent</URL>
     </HTTPTargetConnection>
   </TargetEndpoint>
   ```

   ### \<ProxyEndpoint\>

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>js-error</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent</URL>
     </HTTPProxyConnection>
   </ProxyEndpoint>
   ```
5. Deploy the API proxy.
6. Test with proxy behavior using the following `curl` command:

   ```bash
   curl -X POST -H 'Content-Type: application/json'  "https://ENVIRONMENT_GROUP_NAME/llm-api" -d '{ "contents":[{"parts":[{"text": "Write a story about a magic pen."}]}]}'
   ```

   Replace <var translate="no">ENVIRONMENT_GROUP_NAME</var> with the name of your environment
   group.

   The output should look similar to the following example:

   ```
   data: {"candidates": [{"content": {"parts": [{"text": "El"}],"role": "model"}}],"usageMetadata": {"promptTokenCount": 8,"totalTokenCount": 8},"modelVersion": "gemini-2.5-flash"}
   data: {"fault":{"faultstring":"Execution of JS-error failed with error: Exception thrown from JavaScript : Error: Internal Error (Resource_1_js#2)","detail":{"errorcode":"steps.javascript.ScriptExecutionFailed"}}}
   ```

   The output shows the initial data stream followed by a `fault`
   message. In the event of an error, Apigee captures the fault information and sends it to
   the client as an event.

For more information about fault handling in Apigee, see [Handling faults](https://docs.cloud.google.com/apigee/docs/api-platform/fundamentals/fault-handling.md.txt).

### Use DataCapture to collect token counts in analytics

This example shows you how to use the
[DataCapture policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/data-capture-policy.md.txt)
inside an `EventFlow` to collect token counts from SSE events for use in
Apigee analytics.

1. Create data collectors for token counts. Run the following commands to create the required data collectors in your organization:

   ```
   curl -X POST "https://apigee.googleapis.com/v1/organizations/ORG_NAME/datacollectors" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "dc_tokenCount",
       "description": "Collects token count",
       "type": "INTEGER"
     }'
   ```

   ```
   curl -X POST "https://apigee.googleapis.com/v1/organizations/ORG_NAME/datacollectors" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "dc_thoughtsTokenCount",
       "description": "Collects thought token count",
       "type": "INTEGER"
     }'
   ```
2. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
3. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
4. Create a new [JavaScript policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt) to parse token counts from the SSE event data. In the Apigee proxy editor, click **+** next to **Policies** , select **JavaScript** as the policy type, and enter a name for the policy (for example, `JS-parse-token`). The resulting policy XML should look like the following:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <Javascript continueOnError="false" enabled="true" timeLimit="200" name="JS-parse-token">
     <DisplayName>JS-parse-token</DisplayName>
     <Properties/>
     <Source>
       const event=context.getVariable('response.event.current.content')
       try {
         const jsonString = event.replace(/^data:\s*/, '').trim();
         const parsed = JSON.parse(jsonString);
         const usage = parsed.usageMetadata || {};
         context.setVariable("thoughtsToken", usage.thoughtsTokenCount);
         context.setVariable("totalToken", usage.totalTokenCount);
       } catch (e) {
         context.setVariable("js_error_occurred", true);
       }
     </Source>
   </Javascript>
   ```
5. Create a new [DataCapture policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/data-capture-policy.md.txt) to capture the token counts. In the Apigee proxy editor, click **+** next to **Policies** , select **DataCapture** as the policy type, and enter a name for the policy (for example, `DC-capture-tokencount`). The resulting policy XML should look like the following:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <DataCapture name="DC-capture-tokencount" continueOnError="false" enabled="true">
     <DisplayName>DC-capture-tokencount</DisplayName>
     <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
     <Capture>
       <Collect ref="thoughtsToken" default="-1"/>
       <DataCollector>dc_thoughtsTokenCount</DataCollector>
     </Capture>
     <Capture>
       <Collect ref="totalToken" default="-1"/>
       <DataCollector>dc_tokenCount</DataCollector>
     </Capture>
   </DataCapture>
   ```
6. Attach the JavaScript policy first, followed by the DataCapture policy, inside the `EventFlow` of the SSE proxy within the `TargetEndpoint` or `ProxyEndpoint` configuration. This step ensures that the `EventFlow` processes the policies during response handling. The resulting XML should look like the following:

   ### \<TargetEndpoint\>

   ```
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>JS-parse-token</Name>
         </Step>
         <Step>
           <Name>DC-capture-tokencount</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPTargetConnection>
   </TargetEndpoint>
   ```

   ### \<ProxyEndpoint\>

   ```
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>JS-parse-token</Name>
         </Step>
         <Step>
           <Name>DC-capture-tokencount</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPProxyConnection>
   </ProxyEndpoint>
   ```
7. Save and deploy the proxy. For details, see [Deploying API proxies](https://docs.cloud.google.com/apigee/docs/api-platform/deploy/deploying-overview).
8. Send test requests to the proxy. After the proxy processes SSE responses, the captured token counts are available in [Apigee analytics](https://docs.cloud.google.com/apigee/docs/api-platform/analytics/analytics-services-overview.md.txt) through the `dc_tokenCount` and `dc_thoughtsTokenCount` data collectors.

### Use an LLMTokenQuota policy to enforce token quotas in an EventFlow

This example shows you how to use the
[LLMTokenQuota policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt)
inside an `EventFlow` to count and enforce token quotas for an SSE
stream. While processing the event stream, token counting is executed only when
the token usage metadata from the LLM response is found in the event. When the
token usage metadata is discovered it is extracted and the policy is executed.
For all other events, the policy results in a no-op.

> [!NOTE]
> **Note:** When the LLMTokenQuota policy is part of an `EventFlow`, the [`<LLMTokenUsageSource>`](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt#llmtokenusagesource) and [`<LLMModelSource>`](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt#llmmodelsource) elements must read from the current event's data using the `response.event.current.data` flow variable, with the `jsonPath` function's third argument set to `false`.

1. Create a new proxy with the SSE proxy template. See [Create an API proxy with server-sent events (SSE)](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#create).
2. Open the proxy in the Apigee proxy editor and click the **Develop** tab.
3. Create a new [LLMTokenQuota policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt) to count the tokens consumed by the SSE stream. In the Apigee proxy editor, click **+** next to **Policies** , select **LLMTokenQuota** as the policy type, and enter a name for the policy (for example, `LTQ-Count-Only`). The resulting policy XML should look like the following:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <LLMTokenQuota name="LTQ-Count-Only" type="rollingwindow">
     <SharedName>common-counter</SharedName>
     <CountOnly>true</CountOnly>
     <Allow count="15000"/>
     <Interval>30</Interval>
     <TimeUnit>minute</TimeUnit>
     <Distributed>true</Distributed>
     <LLMTokenUsageSource>{jsonPath('$.usageMetadata.candidatesTokenCount',response.event.current.data,false)}</LLMTokenUsageSource>
     <LLMModelSource>{jsonPath('$.modelVersion',response.event.current.data,false)}</LLMModelSource>
   </LLMTokenQuota>
   ```
4. Create a second [LLMTokenQuota policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt) to enforce the token quota on incoming requests. In the Apigee proxy editor, click **+** next to **Policies** , select **LLMTokenQuota** as the policy type, and enter a name for the policy (for example, `LTQ-Enforce-Only`). This policy uses the same `<SharedName>` as the counting policy so that both policies share the same quota counter. The resulting policy XML should look like the following:

   ```
   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
   <LLMTokenQuota name="LTQ-Enforce-Only" type="rollingwindow">
     <SharedName>common-counter</SharedName>
     <EnforceOnly>true</EnforceOnly>
     <Allow count="15000"/>
     <Interval>30</Interval>
     <TimeUnit>minute</TimeUnit>
     <Distributed>true</Distributed>
   </LLMTokenQuota>
   ```
5. Add the `LTQ-Enforce-Only` policy as a step in the `Request` of the `PreFlow` of the `ProxyEndpoint`. This step ensures that the quota is checked on each incoming request. The resulting XML should look like the following:

   ```
   <ProxyEndpoint name="default">
     <PreFlow name="PreFlow">
       <Request>
         <Step>
           <Name>LTQ-Enforce-Only</Name>
         </Step>
       </Request>
       <Response/>
     </PreFlow>
   </ProxyEndpoint>
   ```
6. Add the `LTQ-Count-Only` policy as a step inside the `EventFlow` of the SSE proxy within the `TargetEndpoint` or `ProxyEndpoint` configuration. This step ensures that the `EventFlow` processes the policy during response handling and increments the shared quota counter. The resulting XML should look like the following:

   ### \<TargetEndpoint\>

   ```
   <TargetEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>LTQ-Count-Only</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPTargetConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPTargetConnection>
   </TargetEndpoint>
   ```

   ### \<ProxyEndpoint\>

   ```
   <ProxyEndpoint name="default">
     <EventFlow content-type="text/event-stream">
       <Response>
         <Step>
           <Name>LTQ-Count-Only</Name>
         </Step>
       </Response>
     </EventFlow>
     <HTTPProxyConnection>
       <URL>https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?key=GEMINI_API_KEY&alt=sse</URL>
     </HTTPProxyConnection>
   </ProxyEndpoint>
   ```
7. Save and deploy the proxy. For details, see [Deploying API proxies](https://docs.cloud.google.com/apigee/docs/api-platform/deploy/deploying-overview).
8. Send test requests to the proxy. On each incoming request, the `LTQ-Enforce-Only` policy checks the shared quota counter and rejects the request if the configured limit has already been reached. As the proxy processes SSE responses, the `LTQ-Count-Only` policy counts the tokens reported in the token usage metadata of each event and increments the same shared quota counter. When the counter reaches the configured limit, subsequent token-consuming requests are rejected until the counter resets.

For more information about the LLMTokenQuota policy, including how to use it
with SSE responses and how to configure shared quota counters, see the
[LLMTokenQuota policy](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt).

## Viewing SSE data in Apigee analytics

Data for SSE proxies shows up in [Apigee analytics](https://docs.cloud.google.com/apigee/docs/api-platform/analytics/analytics-services-overview.md.txt)
as expected for any API proxy. In the Cloud console, go to **Analytics \> API metrics**.

## Debugging SSE proxies

Use the [Apigee debug tool](https://docs.cloud.google.com/apigee/docs/api-platform/debug/trace-overview.md.txt) to debug SSE proxies.
Debug data is captured for `EventFlow` just as it is for the other flow types.

## Troubleshooting

For real-time traffic issues, check the [Apigee access logs](https://docs.cloud.google.com/apigee/docs/api-platform/system-administration/cloud-logging-ingress-access.md.txt) to determine the cause.

## Limitations

The following limitations apply to SSE proxies:

- If the [DataCapture](https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/data-capture-policy.md.txt) policy is applied on every event, only the latest value will be recorded.
- While an SSE connection can be kept open indefinitely, its duration is ultimately constrained by the timeout setting of the Load Balancer downstream of Apigee. By default, the Apigee Load Balancer timeout is set to `30` seconds. For longer-running connections, we recommend [increasing this timeout](https://docs.cloud.google.com/load-balancing/docs/backend-service.md.txt#timeout-setting) or creating a separate backend service with a higher timeout value to handle the SSE traffic.
- Because analytics data is recorded after the SSE session closes, you may notice some delay in the reporting of analytics data.
- Faults inside an EventFlow cause the stream to exit immediately and throw an error. For information on manually logging these kinds of errors, or sending them to the client,see [EventFlow use cases and examples](https://docs.cloud.google.com/apigee/docs/api-platform/develop/server-sent-events.md.txt#examples).
- A client receiving streamed SSE responses will receive the `HTTP` headers, including any status codes, at the beginning of the event stream. As a result, if the event stream gets into an error state, the status code initially received will not reflect the error state.

  This limitation can be seen when viewing a [debug session](https://docs.cloud.google.com/apigee/docs/api-platform/debug/trace-overview.md.txt).
  In the session, you may notice that the `HTTP` status code for streams that
  enter the error state differ from the status codes sent to the client. This can occur because
  the debug session entry is generated after the entire request has been processed, rather than at the beginning of the event stream.
  The debug session may reflect the fault code generated by the error, while the client only sees the 2xx status initially
  received in the headers.