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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import os
import sys
import json
import base64
import re
import time
import random
import mimetypes
from urllib.parse import urlparse
import requests

# Key: Add project root to Python module search path
current_file_path = os.path.abspath(__file__)
run_dir = os.path.dirname(current_file_path)
project_root = os.path.dirname(run_dir)
sys.path.insert(0, os.path.abspath(project_root))

from run.prompts import (
    USER_CONTRADICTION_CHECK_PROMPT,
    USER_RESPONSE_CORRECTION_PROMPT,
    USER_TEXT_ONLY_PROMPT_EASY,
    USER_TEXT_ONLY_PROMPT_HARD,
)
from run.apis import call_llm


# --- Media processing utility functions ---

def is_url(path):
    """Check if path is a URL"""
    try:
        result = urlparse(path)
        return all([result.scheme, result.netloc])
    except Exception:
        return False


def get_media_type_from_url(url):
    """Get media type from URL"""
    mime_type, _ = mimetypes.guess_type(url)
    if mime_type and mime_type.startswith('video'):
        return 'video'
    elif mime_type and mime_type.startswith('image'):
        return 'image'
    else:
        parsed_url = urlparse(url)
        ext = os.path.splitext(parsed_url.path)[1].lower()
        video_exts = ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm']
        if ext in video_exts:
            return 'video'
        return 'image'


def get_media_mime_type_from_url(url):
    """Get specific MIME type from URL"""
    mime_type, _ = mimetypes.guess_type(url)
    if mime_type:
        return mime_type

    parsed_url = urlparse(url)
    ext = os.path.splitext(parsed_url.path)[1].lower()
    mime_map = {
        '.mp4': 'video/mp4',
        '.avi': 'video/avi',
        '.mov': 'video/quicktime',
        '.mkv': 'video/x-matroska',
        '.webm': 'video/webm',
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.webp': 'image/webp'
    }
    return mime_map.get(ext, 'image/jpeg')


def encode_image(image_path):
    """Encode image file"""
    if not image_path or not os.path.exists(image_path):
        return None
    with open(image_path, "rb") as f:
        return base64.b64encode(f.read()).decode('utf-8')


def encode_video(video_path):
    """Encode video file"""
    if not video_path or not os.path.exists(video_path):
        return None
    with open(video_path, "rb") as f:
        return base64.b64encode(f.read()).decode('utf-8')


def download_media_from_url(url):
    """Download media content from URL"""
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.content
    except Exception as e:
        print(f"Failed to download media: {e}")
        return None


def get_media_type(file_path):
    """Determine media type based on file extension"""
    if is_url(file_path):
        return get_media_type_from_url(file_path)
    else:
        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type and mime_type.startswith('video'):
            return 'video'
        elif mime_type and mime_type.startswith('image'):
            return 'image'
        else:
            ext = os.path.splitext(file_path)[1].lower()
            video_exts = ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm']
            if ext in video_exts:
                return 'video'
            return 'image'


def get_media_mime_type(file_path):
    """Get specific MIME type"""
    if is_url(file_path):
        return get_media_mime_type_from_url(file_path)
    else:
        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type:
            return mime_type

        ext = os.path.splitext(file_path)[1].lower()
        mime_map = {
            '.mp4': 'video/mp4',
            '.avi': 'video/avi',
            '.mov': 'video/quicktime',
            '.mkv': 'video/x-matroska',
            '.webm': 'video/webm',
            '.jpg': 'image/jpeg',
            '.jpeg': 'image/jpeg',
            '.png': 'image/png',
            '.gif': 'image/gif',
            '.webp': 'image/webp'
        }
        return mime_map.get(ext, 'image/jpeg')


def build_message_with_media(text, media_path=None, use_vision=False, service_model_name="qwen3-vl-235b"):
    """Determine whether to include media files and message format based on use_vision parameter and service_model_name"""
    content = [{"type": "text", "text": text}]

    if use_vision and media_path:
        media_type = "video"
        mime_type = get_media_mime_type(media_path)
        media_url = media_path
        if (
            not is_url(media_path)
            and media_type == "video"
            and service_model_name not in {"kimi-k2.6", "gemini-3.1-pro-preview"}
        ):
            base64_media = encode_video(media_path)
            if base64_media:
                media_url = f"data:{mime_type};base64,{base64_media}"

        # Build different message formats for different models
        if service_model_name in ["glm-5v-turbo", "qwen3.6-plus", "mimo-v2.5-omni", "kimi-k2.6"]:
            if media_type == 'video':
                content.append({"type": "video_url", "video_url": {"url": media_url}})
            else:
                content.append({"type": "image_url", "image_url": {"url": media_path}})

        elif service_model_name == "gemini-3.1-pro-preview":
            # Gemini format
            if is_url(media_path):
                if media_type == 'video':
                    content.append({
                        "type": "input_audio",
                        "input_audio": {"data": media_path, "format": "video/mp4"}
                    })
                else:
                    content.append({"type": "image_url", "image_url": {"url": media_path}})
            else:
                if media_type == 'video':
                    base64_media = encode_video(media_path)
                    if base64_media:
                        content.append({
                            "type": "input_audio",
                            "input_audio": {"data": base64_media, "format": mime_type}
                        })
                else:
                    base64_media = encode_image(media_path)
                    if base64_media:
                        content.append({"type": "image_url", "image_url": {"url": f"{mime_type};base64,{base64_media}"}})
        else:
            # Default format
            if media_type == 'video':
                content.append({"type": "video_url", "video_url": {"url": media_url}})
            else:
                content.append({"type": "image_url", "image_url": {"url": media_path}})

    return content


def build_message_with_image(text, image_path=None, use_vision=False, service_model_name="qwen3-vl-235b"):
    """Backward compatible function, recommend using build_message_with_media"""
    return build_message_with_media(text, image_path, use_vision, service_model_name)


# --- Tool execution functions ---

def execute_tool(db_instance, tool_calls_data):
    """Parse and execute one or more tool calls, return structured results containing role, tool_name, parameters, content"""
    if isinstance(tool_calls_data, dict):
        tool_calls_data = [tool_calls_data]
    elif not isinstance(tool_calls_data, list):
        return [{"role": "tool", "tool_name": "unknown", "parameters": {}, "content": json.dumps({"error": "Invalid tool call format. Expected dict or list."}, ensure_ascii=False)}]

    results = []
    for tool_call_obj in tool_calls_data:
        try:
            method_name = tool_call_obj.get("tool_name")
            if not method_name:
                results.append({
                    "role": "tool",
                    "tool_name": "unknown",
                    "parameters": {},
                    "content": json.dumps({"error": "Missing tool identifier 'tool_name'"}, ensure_ascii=False)
                })
                continue

            params = tool_call_obj.get("parameters", tool_call_obj.get("arguments", {}))

            print(f"  [Tool Execution] Calling: {method_name} Parameters: {params}")

            if hasattr(db_instance, method_name):
                method = getattr(db_instance, method_name)
                result = method(**params)
                print(f"  [Tool Execution] Return result: {result}")
                results.append({
                    "role": "tool",
                    "tool_name": method_name,
                    "parameters": params,
                    "content": json.dumps(result, ensure_ascii=False, default=str)
                })
            else:
                results.append({
                    "role": "tool",
                    "tool_name": method_name,
                    "parameters": params,
                    "content": json.dumps({"error": f"Tool '{method_name}' not found"}, ensure_ascii=False)
                })
        except Exception as e:
            results.append({
                "role": "tool",
                "tool_name": tool_call_obj.get("tool_name") or "unknown",
                "parameters": tool_call_obj.get("parameters", tool_call_obj.get("arguments", {})),
                "content": json.dumps({"error": str(e)}, ensure_ascii=False)
            })

    return results


# --- Tool call check functions ---

def check_tool_call(response_text):
    """
    Extract all JSON format strings containing tool calls from text
    Recognition rule: a JSON object must contain the top-level tool_name key.
    Returns: (whether tool call was found, extracted tool call JSON list)
    """
    text = response_text.strip()

    # Only ``tool_name`` identifies a tool.  ``name`` is also a common business
    # parameter (for example, a household item name), so accepting it here can
    # turn a nested parameters object into a false tool call.
    def is_tool_call(obj):
        return isinstance(obj, dict) and "tool_name" in obj

    # Try parsing entire text as JSON first
    try:
        data = json.loads(text)
        if isinstance(data, list) and len(data) > 0:
            tool_calls = [item for item in data if is_tool_call(item)]
            if tool_calls:
                return True, tool_calls
        elif is_tool_call(data):
            return True, [data]
    except json.JSONDecodeError:
        pass

    # Regex to extract all possible JSON object fragments
    json_pattern = r'\{([^{}]|(\{[^{}]*\}))*\}'
    potential_jsons = re.findall(json_pattern, text, re.DOTALL)

    valid_tool_calls = []
    for match in potential_jsons:
        json_str = match[0] if isinstance(match, tuple) else match
        if not json_str.startswith('{'):
            json_str = '{' + json_str
        if not json_str.endswith('}'):
            json_str = json_str + '}'

        try:
            obj = json.loads(json_str)
            if is_tool_call(obj):
                valid_tool_calls.append(obj)
        except (json.JSONDecodeError, ValueError):
            continue

    # Additional handling for JSON array scenario
    if not valid_tool_calls:
        array_pattern = r'\[.*\]'
        array_matches = re.findall(array_pattern, text, re.DOTALL)

        for arr_str in array_matches:
            try:
                arr = json.loads(arr_str)
                if isinstance(arr, list):
                    for item in arr:
                        if is_tool_call(item):
                            valid_tool_calls.append(item)
            except (json.JSONDecodeError, ValueError):
                continue

    if valid_tool_calls:
        return True, valid_tool_calls
    return False, None

# --- User response evaluation functions ---

def _evaluate_user_response_internal(user_response, user_instruction, last_agent_response, history_str="", user_model_name="Qwen3.5-397B-A17B"):
    """Internal helper function: build prompt and call LLM to evaluate user response"""
    eval_user_content = f"""
[User Original Instruction]
{user_instruction}

[Interaction Process]
{history_str}

[Service Agent Response]
{last_agent_response}

[Simulated User Response]
{user_response}
"""

    contradiction_check_messages = [
        {"role": "system", "content": USER_CONTRADICTION_CHECK_PROMPT},
        {"role": "user", "content": eval_user_content}
    ]

    eval_response_text, _, _ = call_llm(contradiction_check_messages, agent_type="user", user_model_name=user_model_name)

    evaluation_result = {}
    try:
        import re
        code_block_match = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", eval_response_text, re.DOTALL)
        if code_block_match:
            evaluation_result = json.loads(code_block_match.group(1))
        else:
            try:
                evaluation_result = json.loads(eval_response_text)
            except:
                start = eval_response_text.find('{')
                end = eval_response_text.rfind('}')
                if start != -1 and end != -1:
                    json_str = eval_response_text[start:end+1]
                    evaluation_result = json.loads(json_str)
                else:
                    return {"error": "No JSON found", "raw": eval_response_text}
    except Exception as e:
        return {"error": str(e), "raw": eval_response_text}

    return evaluation_result


def check_user_contradiction(user_response, user_instruction, image_description="", multi_agent_user=False, last_agent_response="", history=[], summarized_history=None, user_mode="easy", user_model_name="Qwen3.5-397B-A17B", max_retries=3):
    """
    Check if user response contradicts the task (based on scoring mechanism)
    If multi_agent_user is True and there is a contradiction (any dimension <= 0 points), use LLM to correct user response
    Will retry up to max_retries times until the evaluation passes
    :param user_mode: User difficulty mode ("easy" or "hard"), used to select corresponding correction prompt
    :param max_retries: Maximum number of retry attempts (default: 3)
    :return: (corrected_response, evaluation_result)
    """
    if not multi_agent_user:
        return user_response, None

    # Build history conversation string
    if summarized_history:
        history_str = summarized_history
    else:
        history_str = ""
        for item in history:
            role = "User" if item["role"] == "user" else "Service Agent"
            content = item["content"]
            history_str += f"{role}: {content}\n"

    # Select corresponding prompt based on user_mode
    if user_mode == "hard":
        correction_prompt_template = USER_TEXT_ONLY_PROMPT_HARD
    else:
        correction_prompt_template = USER_TEXT_ONLY_PROMPT_EASY

    current_response = user_response
    all_attempts = []

    # Evaluate original response first
    print("Evaluating user response (Corrections Check)...")
    evaluation_result = _evaluate_user_response_internal(current_response, user_instruction, last_agent_response, history_str, user_model_name="Qwen3.5-397B-A17B")

    if "error" in evaluation_result:
        print(f"Evaluation failed: {evaluation_result['error']}")
        return user_response, evaluation_result

    scores = evaluation_result.get("scores", {})

    try:
        score_values = [float(v) for v in scores.values()]
        avg_score = round(sum(score_values) / len(score_values), 2) if score_values else 0
    except:
        avg_score = 0
    evaluation_result["average_score"] = avg_score

    # Check if correction is needed
    def needs_correction_check(scores_dict):
        for k, v in scores_dict.items():
            try:
                if float(v) <= 0:
                    return True
            except:
                pass
        return False

    needs_fix = needs_correction_check(scores)
    corrected_response = current_response
    evaluation_result["original_response"] = user_response

    if not needs_fix:
        evaluation_result["correction_applied"] = False
        evaluation_result["retry_count"] = 0
        print(f"Scores passed (average: {avg_score})")
        return corrected_response, evaluation_result

    # Need correction - start retry loop
    print(f"Low score detected (average: {avg_score}), starting to correct user response... (Scores: {scores})")

    for attempt in range(1, max_retries + 1):
        print(f"\n--- Correction Attempt {attempt}/{max_retries} ---")

        # Get feedback from previous attempt
        if attempt == 1:
            feedback = evaluation_result.get("suggestion", "")
            response_to_correct = user_response
        else:
            feedback = all_attempts[-1].get("suggestion", "")
            response_to_correct = all_attempts[-1].get("response", user_response)

        correction_input = correction_prompt_template.format(
            user_instruction=user_instruction,
            image_description=image_description,
            original_user_response=response_to_correct,
            evaluation_feedback=feedback,
            history_summary=history_str,
            service_agent_response=last_agent_response
        )

        correction_messages = [{"role": "user", "content": correction_input}]
        corrected_response_text, _, _ = call_llm(correction_messages, agent_type="user", user_model_name=user_model_name)

        cleaned_response = corrected_response_text.strip()
        if cleaned_response.startswith("```"):
            lines = cleaned_response.split('\n')
            if len(lines) >= 2:
                cleaned_response = '\n'.join(lines[1:-1])

        corrected_response = cleaned_response.strip()
        print(f"Corrected response (attempt {attempt}): {corrected_response}")

        # Evaluate the corrected response
        print(f"Evaluating corrected response (attempt {attempt})...")
        corrected_evaluation = _evaluate_user_response_internal(corrected_response, user_instruction, last_agent_response, history_str, user_model_name=user_model_name)

        attempt_record = {
            "attempt": attempt,
            "response": corrected_response,
            "scores": corrected_evaluation.get("scores", {}),
            "suggestion": corrected_evaluation.get("suggestion", "")
        }

        if "error" not in corrected_evaluation:
            corrected_scores = corrected_evaluation.get("scores", {})
            try:
                c_values = [float(v) for v in corrected_scores.values()]
                c_avg_score = round(sum(c_values) / len(c_values), 2) if c_values else 0
            except:
                c_avg_score = 0
            attempt_record["average_score"] = c_avg_score
            print(f"Attempt {attempt} scores: {corrected_scores} (average: {c_avg_score})")

            # Check if this attempt passes
            if not needs_correction_check(corrected_scores):
                print(f"Attempt {attempt} passed evaluation!")
                all_attempts.append(attempt_record)
                break
            else:
                print(f"Attempt {attempt} still has low scores, will retry...")
        else:
            attempt_record["error"] = corrected_evaluation.get("error")
            print(f"Attempt {attempt} evaluation failed: {corrected_evaluation.get('error')}")

        all_attempts.append(attempt_record)

        # If this is the last attempt, we keep the corrected_response from this attempt
        if attempt == max_retries:
            print(f"Reached maximum retries ({max_retries}), using last attempt's response")

    # Build final evaluation result
    evaluation_result["correction_applied"] = True
    evaluation_result["retry_count"] = len(all_attempts)
    evaluation_result["corrected_response"] = corrected_response
    evaluation_result["all_attempts"] = all_attempts

    if all_attempts:
        final_attempt = all_attempts[-1]
        evaluation_result["corrected_scores"] = final_attempt.get("scores", {})
        evaluation_result["corrected_average_score"] = final_attempt.get("average_score", 0)

    return corrected_response, evaluation_result