| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | from typing import Optional |
| 8 | |
| 9 | from llama_models.llama3.api.datatypes import * # noqa: F403 |
| 10 | from llama_models.llama3.api.tool_utils import ToolUtils |
| 11 | |
| 12 | from termcolor import cprint |
| 13 | |
| 14 | from llama_stack.apis.agents import AgentTurnResponseEventType, StepType |
| 15 | |
| 16 | |
| 17 | class LogEvent: |
| 18 | def __init__( |
| 19 | self, |
| 20 | role: Optional[str] = None, |
| 21 | content: str = "", |
| 22 | end: str = "\n", |
| 23 | color="white", |
| 24 | ): |
| 25 | self.role = role |
| 26 | self.content = content |
| 27 | self.color = color |
| 28 | self.end = "\n" if end is None else end |
| 29 | |
| 30 | def __str__(self): |
| 31 | if self.role is not None: |
| 32 | return f"{self.role}> {self.content}" |
| 33 | else: |
| 34 | return f"{self.content}" |
| 35 | |
| 36 | def print(self, flush=True): |
| 37 | cprint(f"{str(self)}", color=self.color, end=self.end, flush=flush) |
| 38 | |
| 39 | |
| 40 | EventType = AgentTurnResponseEventType |
| 41 | |
| 42 | |
| 43 | class EventLogger: |
| 44 | async def log( |
| 45 | self, |
| 46 | event_generator, |
| 47 | stream=True, |
| 48 | tool_prompt_format: ToolPromptFormat = ToolPromptFormat.json, |
| 49 | ): |
| 50 | previous_event_type = None |
| 51 | previous_step_type = None |
| 52 | |
| 53 | async for chunk in event_generator: |
| 54 | if not hasattr(chunk, "event"): |
| 55 | # Need to check for custom tool first |
| 56 | # since it does not produce event but instead |
| 57 | # a Message |
| 58 | if isinstance(chunk, ToolResponseMessage): |
| 59 | yield chunk, LogEvent( |
| 60 | role="CustomTool", content=chunk.content, color="grey" |
| 61 | ) |
| 62 | continue |
| 63 | |
| 64 | event = chunk.event |
| 65 | event_type = event.payload.event_type |
| 66 | if event_type in { |
| 67 | EventType.turn_start.value, |
| 68 | EventType.turn_complete.value, |
| 69 | }: |
| 70 | # Currently not logging any turn realted info |
| 71 | yield event, None |
| 72 | continue |
| 73 | |
| 74 | step_type = event.payload.step_type |
| 75 | # handle safety |
| 76 | if ( |
| 77 | step_type == StepType.shield_call |
| 78 | and event_type == EventType.step_complete.value |
| 79 | ): |
| 80 | violation = event.payload.step_details.violation |
| 81 | if not violation: |
| 82 | yield event, LogEvent( |
| 83 | role=step_type, content="No Violation", color="magenta" |
| 84 | ) |
| 85 | else: |
| 86 | yield event, LogEvent( |
| 87 | role=step_type, |
| 88 | content=f"{violation.metadata} {violation.user_message}", |
| 89 | color="red", |
| 90 | ) |
| 91 | |
| 92 | # handle inference |
| 93 | if step_type == StepType.inference: |
| 94 | if stream: |
| 95 | if event_type == EventType.step_start.value: |
| 96 | # TODO: Currently this event is never received |
| 97 | yield event, LogEvent( |
| 98 | role=step_type, content="", end="", color="yellow" |
| 99 | ) |
| 100 | elif event_type == EventType.step_progress.value: |
| 101 | # HACK: if previous was not step/event was not inference's step_progress |
| 102 | # this is the first time we are getting model inference response |
| 103 | # aka equivalent to step_start for inference. Hence, |
| 104 | # start with "Model>". |
| 105 | if ( |
| 106 | previous_event_type != EventType.step_progress.value |
| 107 | and previous_step_type != StepType.inference |
| 108 | ): |
| 109 | yield event, LogEvent( |
| 110 | role=step_type, content="", end="", color="yellow" |
| 111 | ) |
| 112 | |
| 113 | if event.payload.tool_call_delta: |
| 114 | if isinstance(event.payload.tool_call_delta.content, str): |
| 115 | yield event, LogEvent( |
| 116 | role=None, |
| 117 | content=event.payload.tool_call_delta.content, |
| 118 | end="", |
| 119 | color="cyan", |
| 120 | ) |
| 121 | else: |
| 122 | yield event, LogEvent( |
| 123 | role=None, |
| 124 | content=event.payload.model_response_text_delta, |
| 125 | end="", |
| 126 | color="yellow", |
| 127 | ) |
| 128 | else: |
| 129 | # step_complete |
| 130 | yield event, LogEvent(role=None, content="") |
| 131 | |
| 132 | else: |
| 133 | # Not streaming |
| 134 | if event_type == EventType.step_complete.value: |
| 135 | response = event.payload.step_details.model_response |
| 136 | if response.tool_calls: |
| 137 | content = ToolUtils.encode_tool_call( |
| 138 | response.tool_calls[0], tool_prompt_format |
| 139 | ) |
| 140 | else: |
| 141 | content = response.content |
| 142 | yield event, LogEvent( |
| 143 | role=step_type, |
| 144 | content=content, |
| 145 | color="yellow", |
| 146 | ) |
| 147 | |
| 148 | # handle tool_execution |
| 149 | if ( |
| 150 | step_type == StepType.tool_execution |
| 151 | and |
| 152 | # Only print tool calls and responses at the step_complete event |
| 153 | event_type == EventType.step_complete.value |
| 154 | ): |
| 155 | details = event.payload.step_details |
| 156 | for t in details.tool_calls: |
| 157 | yield event, LogEvent( |
| 158 | role=step_type, |
| 159 | content=f"Tool:{t.tool_name} Args:{t.arguments}", |
| 160 | color="green", |
| 161 | ) |
| 162 | for r in details.tool_responses: |
| 163 | yield event, LogEvent( |
| 164 | role=step_type, |
| 165 | content=f"Tool:{r.tool_name} Response:{r.content}", |
| 166 | color="green", |
| 167 | ) |
| 168 | |
| 169 | if ( |
| 170 | step_type == StepType.memory_retrieval |
| 171 | and event_type == EventType.step_complete.value |
| 172 | ): |
| 173 | details = event.payload.step_details |
| 174 | content = interleaved_text_media_as_str(details.inserted_context) |
| 175 | content = content[:200] + "..." if len(content) > 200 else content |
| 176 | |
| 177 | yield event, LogEvent( |
| 178 | role=step_type, |
| 179 | content=f"Retrieved context from banks: {details.memory_bank_ids}.\n====\n{content}\n>", |
| 180 | color="cyan", |
| 181 | ) |
| 182 | |
| 183 | preivous_event_type = event_type |
| 184 | previous_step_type = step_type |