File size: 7,726 Bytes
371b96b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import base64
from typing import List , Optional
import os
from ambient.config import settings
import aiohttp
import asyncio
from pydantic import BaseModel
import tenacity
from ambient import Clip, Frame
import logging

logger = logging.getLogger(__name__)

RETRYABLE_STATUS_CODES = {408, 409, 425, 429, 500, 502, 503, 504}


def is_retryable_exception(exc: BaseException) -> bool:
    if isinstance(exc, (aiohttp.ClientConnectionError, asyncio.TimeoutError)):
        return True
    if isinstance(exc, aiohttp.ClientResponseError):
        return exc.status in RETRYABLE_STATUS_CODES
    return False


def video_to_data_url(path: str, mime="video/mp4") -> str:
    with open(path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode("utf-8")
    return f"data:{mime};base64,{b64}"


def _clip_to_frame_urls(mp4: str, fps: float = 0.5, cap: int = 28, dim: int = 768) -> list:
    """Sample chronological frames from a clip mp4 as base64 image data-URLs.
    Used for image-only vision models (e.g. qwen) that reject video_url input."""
    import subprocess, tempfile, glob as _glob
    d = tempfile.mkdtemp(prefix="clipfr_")
    subprocess.run(
        ["ffmpeg", "-nostdin", "-loglevel", "error", "-i", mp4, "-vf",
         f"fps={fps},scale='if(gt(iw,ih),{dim},-2)':'if(gt(iw,ih),-2,{dim})'", "-q:v", "4",
         os.path.join(d, "f%04d.jpg")], check=False)
    out = []
    for p in sorted(_glob.glob(os.path.join(d, "*.jpg")))[:cap]:
        with open(p, "rb") as f:
            out.append("data:image/jpeg;base64," + base64.b64encode(f.read()).decode())
    return out


def construct_payload(clips: Optional[List[Clip]] = None, frames: Optional[List[Frame]] = None):
    payload = []
    if clips is None and frames is None:
        raise ValueError("Either clips or frames must be provided")
    if clips is not None:
        for clip in clips:
            # check if local file or s3 url
            is_clip_url = clip.clip_url is not None
            is_clip_file_path = clip.clip_file_path is not None and os.path.exists(clip.clip_file_path)

            timestamp = f"Timestamp: {clip.start_time} seconds to {clip.end_time} seconds"
            image_only = "gemini" not in (settings.llm_model or "").lower()

            if is_clip_file_path and image_only:
                # image-only vision model (e.g. qwen3.6-27b): send sampled frames, not video_url
                payload.append({"type": "text",
                                "text": f"Clip ID: {clip.id}\n{timestamp}\n(chronological sampled frames)"})
                for u in _clip_to_frame_urls(clip.clip_file_path):
                    payload.append({"type": "image_url", "image_url": {"url": u}})
            else:
                if is_clip_url:
                    url = clip.clip_url
                elif is_clip_file_path:
                    url = video_to_data_url(clip.clip_file_path)
                else:
                    raise ValueError(f"Clip {clip.id} has no valid url or file path")
                payload.extend([
                    {"type": "text", "text": f"Clip ID: {clip.id}\n{timestamp}"},
                    {"type": "video_url", "video_url": {"url": url}},
                ])

    if frames is not None:
        start_time = frames[0].timestamp
        end_time = frames[-1].timestamp
        payload.append(
                {
                    "type": "text",
                    "text": f"Frames from video between {start_time} seconds and {end_time} seconds",
                }
            )
        for idx,frame in enumerate(frames):
            # check if local file or s3 url
            is_frame_url = frame.frame_url is not None
            is_frame_file_path = frame.frame_file_path is not None and os.path.exists(frame.frame_file_path)

            if is_frame_url:
                url = frame.frame_url
            elif is_frame_file_path:
                url = video_to_data_url(frame.frame_file_path,"image/jpeg")
            else:
                raise ValueError(f"Frame {frame.id} has no valid url or file path")

            timestamp = f"Timestamp: {frame.timestamp} seconds"

            if idx%5 == 0 and idx+5 < len(frames):
                payload.append(
                    {
                        "type": "text",
                        "text": f"Frames between {frame.timestamp} seconds and {frames[idx+5].timestamp} seconds",
                    }
                )
            
            payload.append(
                {
                    "type": "image_url",
                    "image_url": {"url": url},
                }
            )

    return payload


def get_provider_params(model: str, base_url: str) -> dict:
    if "gemini" in model.lower() and "openrouter" in base_url.lower():
        return {
            "provider": {
                "only": ["google-ai-studio"],
            },
        }
    
    # if "qwen3.5-35b-a3b" in model.lower() and "openrouter" in base_url.lower():
    #     return {
    #         "provider": {
    #             "only": ["atlas-cloud/fp8"],
    #         },  
    #     }
    return {}


@tenacity.retry(
    stop=tenacity.stop_after_attempt(2),
    wait=tenacity.wait_exponential(multiplier=1, min=2, max=6),
    retry=tenacity.retry_if_exception(is_retryable_exception),
)
async def llm_call(
    prompt: str,
    query: str,
    model: str,
    base_url: str,
    api_key: str,
    video_clips: Optional[List[Clip]] = None,
    history: Optional[List[dict]] = None,
    timeout: int = 300,
    video_frames: Optional[List[Frame]] = None,
    reasoning_enabled: bool = True,
    max_tokens: Optional[int] = None,
) -> BaseModel:
    payload = construct_payload(video_clips,video_frames)
    
    provider_params = get_provider_params(model, base_url)
    # print(payload)
    logger.info(f"Making LLM call to model {model} with {len(payload)} items")
    async with aiohttp.ClientSession(
        timeout=aiohttp.ClientTimeout(total=timeout)
    ) as session:
        async with session.post(
            f"{base_url}/chat/completions",
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": settings.llm_model,
                "messages": [
                    {"role": "system", "content": prompt},
                    *([{
                        "role": "user",
                        "content": f"History Context:\n\n{history}",
                    }] if history else []),
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": f"query: {query}"},
                            *payload,
                        ],
                    },
                ],
                "reasoning": {"enabled": reasoning_enabled},
                **({"max_tokens": max_tokens} if max_tokens else {}),
                **provider_params,
            },
        ) as response:
            if response.status != 200:
                body = await response.text()
                logger.error("LLM call failed: %s %s", response.status, body)
                raise aiohttp.ClientResponseError(
                    response.request_info,
                    response.history,
                    status=response.status,
                    message=body,
                    headers=response.headers,
                )
            try:
                response_json = await response.json()
                logger.info(f"LLM call successful for model {model}")
            except Exception as e:
                print(f"Error: {e} {await response.text()}")
                raise e
            return response_json