|
| 1 | +"""Streaming Responses API example. |
| 2 | +
|
| 3 | +This demonstrates how to enable token streaming for the Responses API path, |
| 4 | +log streaming deltas to ``./logs/stream/`` as JSON, and print the streamed text |
| 5 | +incrementally to the terminal. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import datetime as _dt |
| 11 | +import json |
| 12 | +import os |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +from pydantic import SecretStr |
| 17 | + |
| 18 | +from openhands.sdk import Conversation, LLMStreamEvent, get_logger |
| 19 | +from openhands.sdk.llm import LLM |
| 20 | +from openhands.tools.preset.default import get_default_agent |
| 21 | + |
| 22 | + |
| 23 | +logger = get_logger(__name__) |
| 24 | +LOG_DIR = Path("logs/stream") |
| 25 | + |
| 26 | + |
| 27 | +def _serialize_event(event: LLMStreamEvent) -> dict[str, Any]: |
| 28 | + record = { |
| 29 | + "type": event.type, |
| 30 | + "text": event.text, |
| 31 | + "arguments": event.arguments, |
| 32 | + "output_index": event.output_index, |
| 33 | + "content_index": event.content_index, |
| 34 | + "item_id": event.item_id, |
| 35 | + "is_final": event.is_final, |
| 36 | + } |
| 37 | + return record |
| 38 | + |
| 39 | + |
| 40 | +def main() -> None: |
| 41 | + api_key = os.getenv("LLM_API_KEY") or os.getenv("OPENAI_API_KEY") |
| 42 | + if not api_key: |
| 43 | + raise RuntimeError("Set LLM_API_KEY or OPENAI_API_KEY in your environment.") |
| 44 | + |
| 45 | + model = os.getenv("LLM_MODEL", "openhands/gpt-5-codex") |
| 46 | + base_url = os.getenv("LLM_BASE_URL") |
| 47 | + |
| 48 | + llm = LLM( |
| 49 | + model=model, |
| 50 | + api_key=SecretStr(api_key), |
| 51 | + base_url=base_url, |
| 52 | + service_id="stream-demo", |
| 53 | + ) |
| 54 | + |
| 55 | + agent = get_default_agent(llm=llm, cli_mode=True) |
| 56 | + |
| 57 | + timestamp = _dt.datetime.utcnow().strftime("%Y%m%d-%H%M%S") |
| 58 | + LOG_DIR.mkdir(parents=True, exist_ok=True) |
| 59 | + log_path = LOG_DIR / f"responses_stream_{timestamp}.jsonl" |
| 60 | + |
| 61 | + def on_token(event: LLMStreamEvent) -> None: |
| 62 | + record = _serialize_event(event) |
| 63 | + with log_path.open("a", encoding="utf-8") as fp: |
| 64 | + fp.write(json.dumps(record) + "\n") |
| 65 | + |
| 66 | + stream_chunk = event.text or event.arguments |
| 67 | + if stream_chunk: |
| 68 | + print(stream_chunk, end="", flush=True) |
| 69 | + if event.is_final: |
| 70 | + print("\n--- stream complete ---") |
| 71 | + |
| 72 | + conversation = Conversation( |
| 73 | + agent=agent, |
| 74 | + workspace=os.getcwd(), |
| 75 | + token_callbacks=[on_token], |
| 76 | + ) |
| 77 | + |
| 78 | + story_prompt = ( |
| 79 | + "Compose a vivid, many-paragraph story about a developer discovering " |
| 80 | + "the value of streaming token updates. Stream the narrative as you " |
| 81 | + "write it, and when you complete the story, save the full text to a " |
| 82 | + "file named 'streaming_story.md'." |
| 83 | + ) |
| 84 | + conversation.send_message(story_prompt) |
| 85 | + conversation.run() |
| 86 | + |
| 87 | + cleanup_prompt = ( |
| 88 | + "Thank you. Please delete streaming_story.md now that I've read it, " |
| 89 | + "then confirm the deletion." |
| 90 | + ) |
| 91 | + conversation.send_message(cleanup_prompt) |
| 92 | + conversation.run() |
| 93 | + |
| 94 | + logger.info("Stream log written to %s", log_path) |
| 95 | + |
| 96 | + |
| 97 | +if __name__ == "__main__": |
| 98 | + main() |
0 commit comments