|
| 1 | +import os |
| 2 | +import sys |
| 3 | +from typing import Literal |
| 4 | + |
| 5 | +from pydantic import SecretStr |
| 6 | + |
| 7 | +from openhands.sdk import ( |
| 8 | + Conversation, |
| 9 | + get_logger, |
| 10 | +) |
| 11 | +from openhands.sdk.llm import LLM |
| 12 | +from openhands.sdk.llm.streaming import ModelResponseStream |
| 13 | +from openhands.tools.preset.default import get_default_agent |
| 14 | + |
| 15 | + |
| 16 | +logger = get_logger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +api_key = os.getenv("LLM_API_KEY") or os.getenv("OPENAI_API_KEY") |
| 20 | +if not api_key: |
| 21 | + raise RuntimeError("Set LLM_API_KEY or OPENAI_API_KEY in your environment.") |
| 22 | + |
| 23 | +model = os.getenv("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250929") |
| 24 | +base_url = os.getenv("LLM_BASE_URL") |
| 25 | +llm = LLM( |
| 26 | + model=model, |
| 27 | + api_key=SecretStr(api_key), |
| 28 | + base_url=base_url, |
| 29 | + usage_id="stream-demo", |
| 30 | + stream=True, |
| 31 | +) |
| 32 | + |
| 33 | +agent = get_default_agent(llm=llm, cli_mode=True) |
| 34 | + |
| 35 | + |
| 36 | +# Define streaming states |
| 37 | +StreamingState = Literal["thinking", "content", "tool_name", "tool_args"] |
| 38 | +# Track state across on_token calls for boundary detection |
| 39 | +_current_state: StreamingState | None = None |
| 40 | + |
| 41 | + |
| 42 | +def on_token(chunk: ModelResponseStream) -> None: |
| 43 | + """ |
| 44 | + Handle all types of streaming tokens including content, |
| 45 | + tool calls, and thinking blocks with dynamic boundary detection. |
| 46 | + """ |
| 47 | + global _current_state |
| 48 | + |
| 49 | + choices = chunk.choices |
| 50 | + for choice in choices: |
| 51 | + delta = choice.delta |
| 52 | + if delta is not None: |
| 53 | + # Handle thinking blocks (reasoning content) |
| 54 | + reasoning_content = getattr(delta, "reasoning_content", None) |
| 55 | + if isinstance(reasoning_content, str) and reasoning_content: |
| 56 | + if _current_state != "thinking": |
| 57 | + if _current_state is not None: |
| 58 | + sys.stdout.write("\n") |
| 59 | + sys.stdout.write("THINKING: ") |
| 60 | + _current_state = "thinking" |
| 61 | + sys.stdout.write(reasoning_content) |
| 62 | + sys.stdout.flush() |
| 63 | + |
| 64 | + # Handle regular content |
| 65 | + content = getattr(delta, "content", None) |
| 66 | + if isinstance(content, str) and content: |
| 67 | + if _current_state != "content": |
| 68 | + if _current_state is not None: |
| 69 | + sys.stdout.write("\n") |
| 70 | + sys.stdout.write("CONTENT: ") |
| 71 | + _current_state = "content" |
| 72 | + sys.stdout.write(content) |
| 73 | + sys.stdout.flush() |
| 74 | + |
| 75 | + # Handle tool calls |
| 76 | + tool_calls = getattr(delta, "tool_calls", None) |
| 77 | + if tool_calls: |
| 78 | + for tool_call in tool_calls: |
| 79 | + tool_name = ( |
| 80 | + tool_call.function.name if tool_call.function.name else "" |
| 81 | + ) |
| 82 | + tool_args = ( |
| 83 | + tool_call.function.arguments |
| 84 | + if tool_call.function.arguments |
| 85 | + else "" |
| 86 | + ) |
| 87 | + if tool_name: |
| 88 | + if _current_state != "tool_name": |
| 89 | + if _current_state is not None: |
| 90 | + sys.stdout.write("\n") |
| 91 | + sys.stdout.write("TOOL NAME: ") |
| 92 | + _current_state = "tool_name" |
| 93 | + sys.stdout.write(tool_name) |
| 94 | + sys.stdout.flush() |
| 95 | + if tool_args: |
| 96 | + if _current_state != "tool_args": |
| 97 | + if _current_state is not None: |
| 98 | + sys.stdout.write("\n") |
| 99 | + sys.stdout.write("TOOL ARGS: ") |
| 100 | + _current_state = "tool_args" |
| 101 | + sys.stdout.write(tool_args) |
| 102 | + sys.stdout.flush() |
| 103 | + |
| 104 | + |
| 105 | +conversation = Conversation( |
| 106 | + agent=agent, |
| 107 | + workspace=os.getcwd(), |
| 108 | + token_callbacks=[on_token], |
| 109 | +) |
| 110 | + |
| 111 | +story_prompt = ( |
| 112 | + "Tell me a long story about LLM streaming, write it a file, " |
| 113 | + "make sure it has multiple paragraphs. " |
| 114 | +) |
| 115 | +conversation.send_message(story_prompt) |
| 116 | +print("Token Streaming:") |
| 117 | +print("-" * 100 + "\n") |
| 118 | +conversation.run() |
| 119 | + |
| 120 | +cleanup_prompt = ( |
| 121 | + "Thank you. Please delete the streaming story file now that I've read it, " |
| 122 | + "then confirm the deletion." |
| 123 | +) |
| 124 | +conversation.send_message(cleanup_prompt) |
| 125 | +print("Token Streaming:") |
| 126 | +print("-" * 100 + "\n") |
| 127 | +conversation.run() |
| 128 | + |
| 129 | +# Report cost |
| 130 | +cost = llm.metrics.accumulated_cost |
| 131 | +print(f"EXAMPLE_COST: {cost}") |
0 commit comments