Spaces:
Runtime error
Runtime error
Commit ·
ea6fec7
1
Parent(s): 50b60b4
chore-eliminate-all-type-errors
Browse files- app/server/chat_support.py +19 -10
- app/utils/helper.py +21 -16
app/server/chat_support.py
CHANGED
|
@@ -423,15 +423,24 @@ def append_tool_hint_to_last_user_message(messages: list[Message]) -> None:
|
|
| 423 |
|
| 424 |
if isinstance(msg.content, list):
|
| 425 |
for part in reversed(msg.content):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
if getattr(part, "type", None) != "text":
|
| 427 |
continue
|
| 428 |
-
text_value = part
|
| 429 |
if TOOL_HINT_STRIPPED in text_value:
|
| 430 |
return
|
| 431 |
-
part
|
| 432 |
return
|
| 433 |
|
| 434 |
-
msg.content.append(ContentItem(type="text", text=TOOL_WRAP_HINT.strip()))
|
| 435 |
return
|
| 436 |
|
| 437 |
|
|
@@ -536,7 +545,7 @@ def response_items_to_messages(
|
|
| 536 |
"detail": part.detail if part.detail else "auto",
|
| 537 |
},
|
| 538 |
)
|
| 539 |
-
)
|
| 540 |
elif part.type == "input_file":
|
| 541 |
if part.file_url or part.file_data:
|
| 542 |
normalized_contents.append(part)
|
|
@@ -546,9 +555,9 @@ def response_items_to_messages(
|
|
| 546 |
file_info["filename"] = part.filename
|
| 547 |
if part.file_url:
|
| 548 |
file_info["url"] = part.file_url
|
| 549 |
-
converted.append(ContentItem(type="file", file=file_info))
|
| 550 |
|
| 551 |
-
messages.append(Message(role=role, content=converted or None))
|
| 552 |
|
| 553 |
normalized_input.append(
|
| 554 |
ResponseInputItem(
|
|
@@ -601,7 +610,7 @@ def instructions_to_messages(
|
|
| 601 |
"detail": part.detail if part.detail else "auto",
|
| 602 |
},
|
| 603 |
)
|
| 604 |
-
)
|
| 605 |
elif part.type == "input_file":
|
| 606 |
file_info: dict[str, str | None] = {}
|
| 607 |
if part.file_data:
|
|
@@ -610,9 +619,9 @@ def instructions_to_messages(
|
|
| 610 |
if part.file_url:
|
| 611 |
file_info["url"] = part.file_url
|
| 612 |
if file_info:
|
| 613 |
-
converted.append(ContentItem(type="file", file=file_info))
|
| 614 |
|
| 615 |
-
instruction_messages.append(Message(role=role, content=converted or None))
|
| 616 |
|
| 617 |
return instruction_messages
|
| 618 |
|
|
@@ -646,7 +655,7 @@ def get_available_models() -> list[ModelData]:
|
|
| 646 |
for model_cfg in custom_models:
|
| 647 |
models_data.append(
|
| 648 |
ModelData(
|
| 649 |
-
id=model_cfg.model_name,
|
| 650 |
created=now,
|
| 651 |
owned_by="custom",
|
| 652 |
)
|
|
|
|
| 423 |
|
| 424 |
if isinstance(msg.content, list):
|
| 425 |
for part in reversed(msg.content):
|
| 426 |
+
if isinstance(part, dict):
|
| 427 |
+
if part.get("type") != "text":
|
| 428 |
+
continue
|
| 429 |
+
text_value = part.get("text") or ""
|
| 430 |
+
if TOOL_HINT_STRIPPED in str(text_value):
|
| 431 |
+
return
|
| 432 |
+
part["text"] = f"{text_value}\n{TOOL_WRAP_HINT}"
|
| 433 |
+
return
|
| 434 |
+
|
| 435 |
if getattr(part, "type", None) != "text":
|
| 436 |
continue
|
| 437 |
+
text_value = getattr(part, "text", "") or ""
|
| 438 |
if TOOL_HINT_STRIPPED in text_value:
|
| 439 |
return
|
| 440 |
+
setattr(part, "text", f"{text_value}\n{TOOL_WRAP_HINT}")
|
| 441 |
return
|
| 442 |
|
| 443 |
+
msg.content.append(ContentItem(type="text", text=TOOL_WRAP_HINT.strip())) # type: ignore[arg-type]
|
| 444 |
return
|
| 445 |
|
| 446 |
|
|
|
|
| 545 |
"detail": part.detail if part.detail else "auto",
|
| 546 |
},
|
| 547 |
)
|
| 548 |
+
) # type: ignore[arg-type]
|
| 549 |
elif part.type == "input_file":
|
| 550 |
if part.file_url or part.file_data:
|
| 551 |
normalized_contents.append(part)
|
|
|
|
| 555 |
file_info["filename"] = part.filename
|
| 556 |
if part.file_url:
|
| 557 |
file_info["url"] = part.file_url
|
| 558 |
+
converted.append(ContentItem(type="file", file=file_info)) # type: ignore[arg-type]
|
| 559 |
|
| 560 |
+
messages.append(Message(role=role, content=converted or None)) # type: ignore[arg-type, assignment]
|
| 561 |
|
| 562 |
normalized_input.append(
|
| 563 |
ResponseInputItem(
|
|
|
|
| 610 |
"detail": part.detail if part.detail else "auto",
|
| 611 |
},
|
| 612 |
)
|
| 613 |
+
) # type: ignore[arg-type]
|
| 614 |
elif part.type == "input_file":
|
| 615 |
file_info: dict[str, str | None] = {}
|
| 616 |
if part.file_data:
|
|
|
|
| 619 |
if part.file_url:
|
| 620 |
file_info["url"] = part.file_url
|
| 621 |
if file_info:
|
| 622 |
+
converted.append(ContentItem(type="file", file=file_info)) # type: ignore[arg-type]
|
| 623 |
|
| 624 |
+
instruction_messages.append(Message(role=role, content=converted or None)) # type: ignore[arg-type, assignment]
|
| 625 |
|
| 626 |
return instruction_messages
|
| 627 |
|
|
|
|
| 655 |
for model_cfg in custom_models:
|
| 656 |
models_data.append(
|
| 657 |
ModelData(
|
| 658 |
+
id=str(model_cfg.model_name),
|
| 659 |
created=now,
|
| 660 |
owned_by="custom",
|
| 661 |
)
|
app/utils/helper.py
CHANGED
|
@@ -9,10 +9,10 @@ import reprlib
|
|
| 9 |
import struct
|
| 10 |
import tempfile
|
| 11 |
from pathlib import Path
|
| 12 |
-
from typing import Any, Callable,
|
| 13 |
from urllib.parse import urlparse
|
| 14 |
|
| 15 |
-
import httpx
|
| 16 |
import orjson
|
| 17 |
from loguru import logger
|
| 18 |
|
|
@@ -26,8 +26,8 @@ def retry_with_backoff(
|
|
| 26 |
base_delay: float = 1.0,
|
| 27 |
max_delay: float = 30.0,
|
| 28 |
exponential_base: float = 2.0,
|
| 29 |
-
retryable_exceptions: tuple = (Exception,),
|
| 30 |
-
):
|
| 31 |
"""
|
| 32 |
Decorator that retries a function with exponential backoff.
|
| 33 |
|
|
@@ -39,18 +39,18 @@ def retry_with_backoff(
|
|
| 39 |
retryable_exceptions: Tuple of exception types to retry on
|
| 40 |
"""
|
| 41 |
|
| 42 |
-
def decorator(func: Callable[...,
|
| 43 |
@functools.wraps(func)
|
| 44 |
-
async def async_wrapper(*args, **kwargs) ->
|
| 45 |
-
last_exception = None
|
| 46 |
for attempt in range(max_retries + 1):
|
| 47 |
try:
|
| 48 |
-
return await func(*args, **kwargs)
|
| 49 |
except retryable_exceptions as e:
|
| 50 |
last_exception = e
|
| 51 |
if attempt == max_retries:
|
| 52 |
logger.error(f"All {max_retries + 1} attempts failed for {func.__name__}")
|
| 53 |
-
raise
|
| 54 |
|
| 55 |
# Calculate delay with exponential backoff and jitter
|
| 56 |
delay = min(base_delay * (exponential_base**attempt), max_delay)
|
|
@@ -66,11 +66,13 @@ def retry_with_backoff(
|
|
| 66 |
|
| 67 |
await asyncio.sleep(actual_delay)
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
|
| 71 |
@functools.wraps(func)
|
| 72 |
-
def sync_wrapper(*args, **kwargs) ->
|
| 73 |
-
last_exception = None
|
| 74 |
for attempt in range(max_retries + 1):
|
| 75 |
try:
|
| 76 |
return func(*args, **kwargs)
|
|
@@ -78,7 +80,7 @@ def retry_with_backoff(
|
|
| 78 |
last_exception = e
|
| 79 |
if attempt == max_retries:
|
| 80 |
logger.error(f"All {max_retries + 1} attempts failed for {func.__name__}")
|
| 81 |
-
raise
|
| 82 |
|
| 83 |
delay = min(base_delay * (exponential_base**attempt), max_delay)
|
| 84 |
jitter = random.uniform(0.1, 0.3) * delay
|
|
@@ -93,7 +95,9 @@ def retry_with_backoff(
|
|
| 93 |
|
| 94 |
time.sleep(actual_delay)
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
|
| 98 |
# Return appropriate wrapper based on whether function is async
|
| 99 |
import asyncio
|
|
@@ -206,7 +210,7 @@ def safe_json_loads(s: str) -> Any:
|
|
| 206 |
# Try to parse nested structures
|
| 207 |
try:
|
| 208 |
value = orjson.loads(value)
|
| 209 |
-
except:
|
| 210 |
pass
|
| 211 |
result[key] = value
|
| 212 |
if result:
|
|
@@ -278,7 +282,8 @@ async def save_url_to_tempfile(url: str, tempdir: Path | None = None) -> Path:
|
|
| 278 |
suffix = ".bin"
|
| 279 |
|
| 280 |
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=tempdir) as tmp:
|
| 281 |
-
|
|
|
|
| 282 |
path = Path(tmp.name)
|
| 283 |
|
| 284 |
return path
|
|
|
|
| 9 |
import struct
|
| 10 |
import tempfile
|
| 11 |
from pathlib import Path
|
| 12 |
+
from typing import Any, Callable, TypeVar
|
| 13 |
from urllib.parse import urlparse
|
| 14 |
|
| 15 |
+
import httpx # type: ignore
|
| 16 |
import orjson
|
| 17 |
from loguru import logger
|
| 18 |
|
|
|
|
| 26 |
base_delay: float = 1.0,
|
| 27 |
max_delay: float = 30.0,
|
| 28 |
exponential_base: float = 2.0,
|
| 29 |
+
retryable_exceptions: tuple[type[Exception], ...] = (Exception,),
|
| 30 |
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
| 31 |
"""
|
| 32 |
Decorator that retries a function with exponential backoff.
|
| 33 |
|
|
|
|
| 39 |
retryable_exceptions: Tuple of exception types to retry on
|
| 40 |
"""
|
| 41 |
|
| 42 |
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 43 |
@functools.wraps(func)
|
| 44 |
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 45 |
+
last_exception: Exception | None = None
|
| 46 |
for attempt in range(max_retries + 1):
|
| 47 |
try:
|
| 48 |
+
return await func(*args, **kwargs) # type: ignore
|
| 49 |
except retryable_exceptions as e:
|
| 50 |
last_exception = e
|
| 51 |
if attempt == max_retries:
|
| 52 |
logger.error(f"All {max_retries + 1} attempts failed for {func.__name__}")
|
| 53 |
+
raise e
|
| 54 |
|
| 55 |
# Calculate delay with exponential backoff and jitter
|
| 56 |
delay = min(base_delay * (exponential_base**attempt), max_delay)
|
|
|
|
| 66 |
|
| 67 |
await asyncio.sleep(actual_delay)
|
| 68 |
|
| 69 |
+
if last_exception:
|
| 70 |
+
raise last_exception
|
| 71 |
+
raise RuntimeError("Unreachable")
|
| 72 |
|
| 73 |
@functools.wraps(func)
|
| 74 |
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 75 |
+
last_exception: Exception | None = None
|
| 76 |
for attempt in range(max_retries + 1):
|
| 77 |
try:
|
| 78 |
return func(*args, **kwargs)
|
|
|
|
| 80 |
last_exception = e
|
| 81 |
if attempt == max_retries:
|
| 82 |
logger.error(f"All {max_retries + 1} attempts failed for {func.__name__}")
|
| 83 |
+
raise e
|
| 84 |
|
| 85 |
delay = min(base_delay * (exponential_base**attempt), max_delay)
|
| 86 |
jitter = random.uniform(0.1, 0.3) * delay
|
|
|
|
| 95 |
|
| 96 |
time.sleep(actual_delay)
|
| 97 |
|
| 98 |
+
if last_exception:
|
| 99 |
+
raise last_exception
|
| 100 |
+
raise RuntimeError("Unreachable")
|
| 101 |
|
| 102 |
# Return appropriate wrapper based on whether function is async
|
| 103 |
import asyncio
|
|
|
|
| 210 |
# Try to parse nested structures
|
| 211 |
try:
|
| 212 |
value = orjson.loads(value)
|
| 213 |
+
except Exception:
|
| 214 |
pass
|
| 215 |
result[key] = value
|
| 216 |
if result:
|
|
|
|
| 282 |
suffix = ".bin"
|
| 283 |
|
| 284 |
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix, dir=tempdir) as tmp:
|
| 285 |
+
if data is not None:
|
| 286 |
+
tmp.write(data)
|
| 287 |
path = Path(tmp.name)
|
| 288 |
|
| 289 |
return path
|