Version of the CLI interface that attaches to a stream generator and prints along the way. When a chunk is received, we write the delta to the buffer. If the buffer type has changed, we write out a newline + set the formatting for the new line. The two buffer types are: (1) conte
| 72 | |
| 73 | |
| 74 | class StreamingCLIInterface(AgentChunkStreamingInterface): |
| 75 | """Version of the CLI interface that attaches to a stream generator and prints along the way. |
| 76 | |
| 77 | When a chunk is received, we write the delta to the buffer. If the buffer type has changed, |
| 78 | we write out a newline + set the formatting for the new line. |
| 79 | |
| 80 | The two buffer types are: |
| 81 | (1) content (inner thoughts) |
| 82 | (2) tool_calls (function calling) |
| 83 | |
| 84 | NOTE: this assumes that the deltas received in the chunks are in-order, e.g. |
| 85 | that once 'content' deltas stop streaming, they won't be received again. See notes |
| 86 | on alternative version of the StreamingCLIInterface that does not have this same problem below: |
| 87 | |
| 88 | An alternative implementation could instead maintain the partial message state, and on each |
| 89 | process chunk (1) update the partial message state, (2) refresh/rewrite the state to the screen. |
| 90 | """ |
| 91 | |
| 92 | # CLIInterface is static/stateless |
| 93 | nonstreaming_interface = CLIInterface() |
| 94 | |
| 95 | def __init__(self): |
| 96 | """The streaming CLI interface state for determining which buffer is currently being written to""" |
| 97 | |
| 98 | self.streaming_buffer_type = None |
| 99 | |
| 100 | def _flush(self): |
| 101 | pass |
| 102 | |
| 103 | def process_chunk( |
| 104 | self, |
| 105 | chunk: ChatCompletionChunkResponse, |
| 106 | message_id: str, |
| 107 | message_date: datetime, |
| 108 | expect_reasoning_content: bool = False, |
| 109 | name: Optional[str] = None, |
| 110 | message_index: int = 0, |
| 111 | ): |
| 112 | assert len(chunk.choices) == 1, chunk |
| 113 | |
| 114 | message_delta = chunk.choices[0].delta |
| 115 | |
| 116 | # Starting a new buffer line |
| 117 | if not self.streaming_buffer_type: |
| 118 | assert not ( |
| 119 | message_delta.content is not None and message_delta.tool_calls is not None and len(message_delta.tool_calls) |
| 120 | ), f"Error: got both content and tool_calls in message stream\n{message_delta}" |
| 121 | |
| 122 | if message_delta.content is not None: |
| 123 | # Write out the prefix for inner thoughts |
| 124 | print("Inner thoughts: ", end="", flush=True) |
| 125 | elif message_delta.tool_calls is not None: |
| 126 | assert len(message_delta.tool_calls) == 1, f"Error: got more than one tool call in response\n{message_delta}" |
| 127 | # Write out the prefix for function calling |
| 128 | print("Calling function: ", end="", flush=True) |
| 129 | |
| 130 | # Potentially switch/flush a buffer line |
| 131 | else: |
nothing calls this directly
no test coverage detected