Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions tee_gateway/controllers/chat_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@

logger = logging.getLogger(__name__)

# A model that is thinking, or writing a tool call that is buffered, streams
# nothing to the client, and a relay or proxy drops a stream that is silent for
# a few minutes (chat-api's OHTTP relay reads with a 210 s timeout). So a
# stream that has sent nothing for this long gets an SSE comment. Every client
# reads only `data:` lines, so it changes nothing else, and it is not signed.
KEEPALIVE_SECONDS = 15.0
_clock = time.monotonic


def _split_text_and_images(content: Any) -> tuple[str, list[str]]:
"""Split a LangChain message content into plain text and image data URIs.
Expand Down Expand Up @@ -587,6 +595,7 @@ def generate():
buffered_tool_calls = {}
finish_reason = "stop"
generated_images: list[str] = []
last_sent = _clock()

try:
if image_output_model:
Expand Down Expand Up @@ -693,6 +702,7 @@ def generate():
"model": chat_request.model,
}
yield f"data: {json.dumps(data)}\n\n"
last_sent = _clock()

# --- Tool call chunks ---
if hasattr(chunk, "tool_call_chunks") and chunk.tool_call_chunks:
Expand Down Expand Up @@ -775,6 +785,7 @@ def generate():
"model": chat_request.model,
}
yield f"data: {json.dumps(data)}\n\n"
last_sent = _clock()

# --- Usage metadata ---
# LangChain emits usage deltas for most providers, so those
Expand All @@ -798,6 +809,11 @@ def generate():
for key, value in normalized_chunk_usage.items():
final_usage[key] = final_usage.get(key, 0) + value

# --- Still here (see KEEPALIVE_SECONDS) ---
if _clock() - last_sent >= KEEPALIVE_SECONDS:
yield ": keep-alive\n\n"
last_sent = _clock()

# Flush buffered tool calls for OpenAI/Anthropic
if buffer_tool_calls and buffered_tool_calls:
for tc_index, tc in buffered_tool_calls.items():
Expand Down
77 changes: 77 additions & 0 deletions tee_gateway/test/test_chat_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,3 +403,80 @@ def test_create_chat_completion(self):

if __name__ == "__main__":
unittest.main()


class TestStreamKeepAlive(unittest.TestCase):
"""A model that is thinking streams nothing, and a relay drops a stream that
is silent for a few minutes (chat-api's reads time out after 210 s)."""

@patch("tee_gateway.controllers.chat_controller.get_tee_keys")
@patch("tee_gateway.controllers.chat_controller.get_chat_model_cached")
@patch("tee_gateway.controllers.chat_controller.connexion")
def test_a_long_think_keeps_the_stream_alive(
self, mock_connexion, mock_get_model, mock_get_tee_keys
):
from langchain_core.messages import AIMessageChunk

from tee_gateway.controllers import chat_controller

mock_connexion.request.is_json = True
mock_connexion.request.get_json.return_value = {
"model": "abliterated-model-large-v2",
"messages": [{"role": "user", "content": "hi"}],
"stream": True,
}
mock_get_tee_keys.return_value = _mock_tee_keys()
now = [0.0]

def stream(_messages):
for _ in range(12): # a minute of thinking, with nothing to show
now[0] += 5.0
yield AIMessageChunk(content="")
yield AIMessageChunk(
content="Hello",
usage_metadata={
"input_tokens": 3,
"output_tokens": 9,
"total_tokens": 12,
},
)

model = Mock()
model.stream.side_effect = stream
mock_get_model.return_value = model

with patch.object(chat_controller, "_clock", lambda: now[0]):
events = list(create_chat_completion(None).response)

self.assertEqual(4, events.count(": keep-alive\n\n")) # one per 15 s
data = [e for e in events if e.startswith("data: ")]
self.assertIn('"content": "Hello"', data[0])
final = json.loads(data[-2][len("data: ") :])
self.assertEqual("stop", final["choices"][0]["finish_reason"])
self.assertEqual(9, final["usage"]["completion_tokens"])
self.assertEqual("data: [DONE]\n\n", events[-1])

@patch("tee_gateway.controllers.chat_controller.get_tee_keys")
@patch("tee_gateway.controllers.chat_controller.get_chat_model_cached")
@patch("tee_gateway.controllers.chat_controller.connexion")
def test_a_quick_reply_has_none(
self, mock_connexion, mock_get_model, mock_get_tee_keys
):
from langchain_core.messages import AIMessageChunk

mock_connexion.request.is_json = True
mock_connexion.request.get_json.return_value = {
"model": "abliterated-model-large-v2",
"messages": [{"role": "user", "content": "hi"}],
"stream": True,
}
mock_get_tee_keys.return_value = _mock_tee_keys()
model = Mock()
model.stream.return_value = iter(
[AIMessageChunk(content=""), AIMessageChunk(content="Hello")]
)
mock_get_model.return_value = model

events = list(create_chat_completion(None).response)

self.assertNotIn(": keep-alive\n\n", events)
Loading