File size: 6,125 Bytes
b4f2238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Module for streaming."""

from __future__ import annotations

import logging
from collections.abc import AsyncIterator, Callable, Iterator
from typing import Any

from .backends import ILLMBackend, LLMStreamChunk
from .exceptions import (
    LLMAPIError,
    LLMAuthenticationError,
    LLMBackendUnavailableError,
    LLMNetworkError,
    LLMTimeoutError,
)

logger = logging.getLogger("apps.core.llm.streaming")
_RETRIABLE_ERRORS = (LLMTimeoutError, LLMNetworkError, LLMAPIError)


def _resolve_backends(
    get_backend: Callable[[str], ILLMBackend],
    get_backends_by_priority: Callable[[], list[tuple[str, ILLMBackend]]],
    backend: str | None,
    fallback: bool,
) -> list[tuple[str, ILLMBackend]]:
    """解析要尝试的后端列表"""
    if backend:
        backends_to_try: list[tuple[str, ILLMBackend]] = [(backend, get_backend(backend))]
        if fallback:
            for name, b in get_backends_by_priority():
                if name != backend:
                    backends_to_try.append((name, b))
        return backends_to_try
    return get_backends_by_priority()


def _handle_stream_error(
    name: str, e: Exception, fallback: bool, errors: list[Any], log_prefix: str = "stream"
) -> None:
    """处理流式调用错误"""
    errors.append((name, e))
    if isinstance(e, _RETRIABLE_ERRORS):
        logger.warning(
            f"后端 {log_prefix} 调用失败,尝试下一个",
            extra={"backend": name, "error": str(e), "error_type": type(e).__name__},
        )
        if not fallback:
            raise
    else:
        logger.warning(
            f"后端 {log_prefix} 调用发生未知错误",
            extra={"backend": name, "error": str(e), "error_type": type(e).__name__},
        )
        if not fallback:
            raise LLMAPIError(message=f"调用后端 {name} 时发生错误: {e!s}", errors={"detail": str(e)}) from e


def _build_stream_kwargs(
    messages: Any,
    model: Any,
    temperature: Any,
    max_tokens: Any,
    extra_kwargs: dict[str, Any] | None = None,
) -> dict[str, Any]:
    kwargs = {"messages": messages, "model": model, "temperature": temperature, "max_tokens": max_tokens}
    if extra_kwargs:
        kwargs.update(extra_kwargs)
    return kwargs


def stream_with_fallback(
    *,
    get_backend: Callable[[str], ILLMBackend],
    get_backends_by_priority: Callable[[], list[tuple[str, ILLMBackend]]],
    backend: str | None,
    fallback: bool,
    messages: list[dict[str, str]],
    model: str | None,
    temperature: float,
    max_tokens: int | None,
    **kwargs: Any,
) -> Iterator[LLMStreamChunk]:
    from .fallback_policy import _diagnose_unavailable

    kwargs = _build_stream_kwargs(messages, model, temperature, max_tokens, kwargs)
    if backend and (not fallback):
        yield from get_backend(backend).stream(**kwargs)
        return
    backends_to_try = _resolve_backends(get_backend, get_backends_by_priority, backend, fallback)
    errors: list[tuple[str, Exception]] = []
    skipped: list[tuple[str, str]] = []
    for name, backend_instance in backends_to_try:
        if not backend_instance.is_available():
            reason = _diagnose_unavailable(name, backend_instance)
            logger.warning("后端不可用,跳过", extra={"backend": name, "reason": reason})
            skipped.append((name, reason))
            continue
        it = None
        try:
            it = iter(backend_instance.stream(**kwargs))
            first = next(it)
        except StopIteration:
            return
        except LLMAuthenticationError:
            raise
        except Exception as e:
            logger.exception("操作失败")
            _handle_stream_error(name, e, fallback, errors, "stream")
            continue
        yield first
        if it is not None:
            yield from it
        return
    attempts_detail = [(n, str(e)) for n, e in errors]
    attempts_detail.extend([(n, reason) for n, reason in skipped])
    raise LLMBackendUnavailableError(
        message="所有 LLM 后端均不可用",
        errors={"attempts": attempts_detail, "skipped": skipped},
    )


async def astream_with_fallback(
    *,
    get_backend: Callable[[str], ILLMBackend],
    get_backends_by_priority: Callable[[], list[tuple[str, ILLMBackend]]],
    backend: str | None,
    fallback: bool,
    messages: list[dict[str, str]],
    model: str | None,
    temperature: float,
    max_tokens: int | None,
    **kwargs: Any,
) -> AsyncIterator[LLMStreamChunk]:
    from .fallback_policy import _diagnose_unavailable

    kwargs = _build_stream_kwargs(messages, model, temperature, max_tokens, kwargs)
    if backend and (not fallback):
        async for chunk in get_backend(backend).astream(**kwargs):  # type: ignore[attr-defined]
            yield chunk
        return
    backends_to_try = _resolve_backends(get_backend, get_backends_by_priority, backend, fallback)
    errors: list[tuple[str, Exception]] = []
    skipped: list[tuple[str, str]] = []
    for name, backend_instance in backends_to_try:
        if not backend_instance.is_available():
            reason = _diagnose_unavailable(name, backend_instance)
            logger.warning("后端不可用,跳过", extra={"backend": name, "reason": reason})
            skipped.append((name, reason))
            continue
        try:
            ait = backend_instance.astream(**kwargs).__aiter__()  # type: ignore[attr-defined]
            first = await ait.__anext__()
        except StopAsyncIteration:
            return
        except LLMAuthenticationError:
            raise
        except Exception as e:
            logger.exception("操作失败")
            _handle_stream_error(name, e, fallback, errors, "astream")
            continue
        yield first
        async for chunk in ait:
            yield chunk
        return
    attempts_detail = [(n, str(e)) for n, e in errors]
    attempts_detail.extend([(n, reason) for n, reason in skipped])
    raise LLMBackendUnavailableError(
        message="所有 LLM 后端均不可用",
        errors={"attempts": attempts_detail, "skipped": skipped},
    )