Spaces:
Sleeping
Sleeping
File size: 10,136 Bytes
bec8a7b 25cdf03 bec8a7b 25cdf03 bec8a7b 25cdf03 bec8a7b 25cdf03 bec8a7b 25cdf03 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
from app.schemas.message_schema import IChatResponse
from app.utils.adaptive_cards.cards import create_adaptive_card, create_image_card
from app.utils.chains import get_suggestions_questions
from langchain.callbacks.base import AsyncCallbackHandler
from app.utils.utils import generate_uuid
from fastapi import WebSocket
from uuid import UUID
from typing import Any
from langchain.schema.agent import AgentFinish
from langchain.schema.output import LLMResult
DEFAULT_ANSWER_PREFIX_TOKENS = ["Final", " Answer", ":"]
class CustomAsyncCallbackHandler(AsyncCallbackHandler):
def append_to_last_tokens(self, token: str) -> None:
self.last_tokens.append(token)
self.last_tokens_stripped.append(token.strip())
if len(self.last_tokens) > len(self.answer_prefix_tokens):
self.last_tokens.pop(0)
self.last_tokens_stripped.pop(0)
def check_if_answer_reached(self) -> bool:
if self.strip_tokens:
return self.last_tokens_stripped == self.answer_prefix_tokens_stripped
else:
return self.last_tokens == self.answer_prefix_tokens
def update_message_id(self, message_id: str = generate_uuid()):
self.message_id = message_id
def __init__(
self,
websocket: WebSocket,
*,
message_id: str = generate_uuid(),
answer_prefix_tokens: list[str] | None = None,
strip_tokens: bool = True,
stream_prefix: bool = False,
) -> None:
"""Instantiate FinalStreamingStdOutCallbackHandler.
Args:
answer_prefix_tokens: Token sequence that prefixes the answer.
Default is ["Final", "Answer", ":"]
strip_tokens: Ignore white spaces and new lines when comparing
answer_prefix_tokens to last tokens? (to determine if answer has been
reached)
stream_prefix: Should answer prefix itself also be streamed?
"""
self.websocket: WebSocket = websocket
self.message_id: str = message_id
self.text: str = ""
self.started: bool = False
self.loading_card = create_image_card(
"https://res.cloudinary.com/dnv0qwkrk/image/upload/v1691005682/Alita/Ellipsis-2.4s-81px_1_nja8hq.gif"
)
self.adaptive_card = self.loading_card
if answer_prefix_tokens is None:
self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS
else:
self.answer_prefix_tokens = answer_prefix_tokens
if strip_tokens:
self.answer_prefix_tokens_stripped = [
token.strip() for token in self.answer_prefix_tokens
]
else:
self.answer_prefix_tokens_stripped = self.answer_prefix_tokens
self.last_tokens = [""] * len(self.answer_prefix_tokens)
self.last_tokens_stripped = [""] * len(self.answer_prefix_tokens)
self.strip_tokens = strip_tokens
self.stream_prefix = stream_prefix
self.answer_reached = False
async def on_llm_start(
self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any
) -> None:
"""Run when LLM starts running."""
resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.loading_card.to_dict(),
type="start",
)
await self.websocket.send_json(resp.dict())
async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Run on new LLM token. Only available when streaming is enabled."""
# Remember the last n tokens, where n = len(answer_prefix_tokens)
self.append_to_last_tokens(token)
self.text += f"{token}"
self.adaptive_card = create_adaptive_card(self.text)
resp = IChatResponse(
# id=generate_uuid(),
id="",
message_id=self.message_id,
sender="bot",
message=self.adaptive_card.to_dict(),
type="stream",
)
await self.websocket.send_json(resp.model_dump())
async def on_llm_end(
self,
response: LLMResult,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
tags: list[str] | None = None,
**kwargs: Any,
) -> None:
"""Run when LLM ends running."""
resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.adaptive_card.to_dict(),
type="end",
)
await self.websocket.send_json(resp.model_dump())
class CustomFinalStreamingStdOutCallbackHandler(AsyncCallbackHandler):
"""Callback handler for streaming in agents.
Only works with agents using LLMs that support streaming.
Only the final output of the agent will be streamed.
"""
def append_to_last_tokens(self, token: str) -> None:
self.last_tokens.append(token)
self.last_tokens_stripped.append(token.strip())
if len(self.last_tokens) > len(self.answer_prefix_tokens):
self.last_tokens.pop(0)
self.last_tokens_stripped.pop(0)
def check_if_answer_reached(self) -> bool:
if self.strip_tokens:
return self.last_tokens_stripped == self.answer_prefix_tokens_stripped
else:
return self.last_tokens == self.answer_prefix_tokens
def update_message_id(self, message_id: str = generate_uuid()):
self.message_id = message_id
def __init__(
self,
websocket: WebSocket,
*,
message_id: str = generate_uuid(),
answer_prefix_tokens: list[str] | None = None,
strip_tokens: bool = True,
stream_prefix: bool = False,
) -> None:
"""Instantiate FinalStreamingStdOutCallbackHandler.
Args:
answer_prefix_tokens: Token sequence that prefixes the answer.
Default is ["Final", "Answer", ":"]
strip_tokens: Ignore white spaces and new lines when comparing
answer_prefix_tokens to last tokens? (to determine if answer has been
reached)
stream_prefix: Should answer prefix itself also be streamed?
"""
self.websocket: WebSocket = websocket
self.message_id: str = message_id
self.text: str = ""
self.started: bool = False
self.loading_card = create_image_card(
"https://res.cloudinary.com/dnv0qwkrk/image/upload/v1691005682/Alita/Ellipsis-2.4s-81px_1_nja8hq.gif"
)
self.adaptive_card = self.loading_card
if answer_prefix_tokens is None:
self.answer_prefix_tokens = DEFAULT_ANSWER_PREFIX_TOKENS
else:
self.answer_prefix_tokens = answer_prefix_tokens
if strip_tokens:
self.answer_prefix_tokens_stripped = [
token.strip() for token in self.answer_prefix_tokens
]
else:
self.answer_prefix_tokens_stripped = self.answer_prefix_tokens
self.last_tokens = [""] * len(self.answer_prefix_tokens)
self.last_tokens_stripped = [""] * len(self.answer_prefix_tokens)
self.strip_tokens = strip_tokens
self.stream_prefix = stream_prefix
self.answer_reached = False
async def on_llm_start(
self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any
) -> None:
"""Run when LLM starts running."""
if self.started == False:
self.started = True
resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.loading_card.to_dict(),
type="start",
)
await self.websocket.send_json(resp.model_dump())
async def on_agent_finish(
self,
finish: AgentFinish,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run on agent end."""
message: str = (
self.text
if self.text != ""
# else "😕 Lo siento no he podido hallar lo que buscabas"
else finish.return_values["output"]
)
self.adaptive_card = create_adaptive_card(message)
resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.adaptive_card.to_dict(),
type="stream",
)
await self.websocket.send_json(resp.dict())
suggested_responses = await get_suggestions_questions(message)
if len(suggested_responses) > 0:
self.adaptive_card = create_adaptive_card(
answer=message,
)
medium_resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.adaptive_card.to_dict(),
type="end",
suggested_responses=suggested_responses,
)
await self.websocket.send_json(medium_resp.model_dump())
# Reset values
self.text = ""
self.answer_reached = False
self.started = False
async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
"""Run on new LLM token. Only available when streaming is enabled."""
# Remember the last n tokens, where n = len(answer_prefix_tokens)
self.append_to_last_tokens(token)
# Check if the last n tokens match the answer_prefix_tokens list ...
if self.check_if_answer_reached():
self.answer_reached = True
return
# ... if yes, then print tokens from now on
if self.answer_reached:
self.text += f"{token}"
self.adaptive_card = create_adaptive_card(self.text)
resp = IChatResponse(
id="",
message_id=self.message_id,
sender="bot",
message=self.adaptive_card.to_dict(),
type="stream",
)
await self.websocket.send_json(resp.model_dump()) |