-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmain.py
More file actions
2458 lines (2079 loc) · 106 KB
/
main.py
File metadata and controls
2458 lines (2079 loc) · 106 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Toolify: Empower any LLM with function calling capabilities.
# Copyright (C) 2025 FunnyCups (https://github.com/funnycups)
import os
import re
import json
import uuid
import httpx
import secrets
import string
import traceback
import time
import random
import logging
import tiktoken
import xml.etree.ElementTree as ET
from typing import List, Dict, Any, Optional, Literal, Union
from fastapi import FastAPI, Request, Header, HTTPException, Depends
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ValidationError
from config_loader import config_loader
logger = logging.getLogger(__name__)
# Token Counter for counting tokens
class TokenCounter:
"""Token counter using tiktoken"""
# Model prefix to encoding mapping (from tiktoken source)
MODEL_PREFIX_TO_ENCODING = {
"o1-": "o200k_base",
"o3-": "o200k_base",
"o4-mini-": "o200k_base",
# chat
"gpt-5-": "o200k_base",
"gpt-4.5-": "o200k_base",
"gpt-4.1-": "o200k_base",
"chatgpt-4o-": "o200k_base",
"gpt-4o-": "o200k_base",
"gpt-4-": "cl100k_base",
"gpt-3.5-turbo-": "cl100k_base",
"gpt-35-turbo-": "cl100k_base", # Azure deployment name
"gpt-oss-": "o200k_harmony",
# fine-tuned
"ft:gpt-4o": "o200k_base",
"ft:gpt-4": "cl100k_base",
"ft:gpt-3.5-turbo": "cl100k_base",
"ft:davinci-002": "cl100k_base",
"ft:babbage-002": "cl100k_base",
}
def __init__(self):
self.encoders = {}
def get_encoder(self, model: str):
"""Get or create encoder for the model"""
if model not in self.encoders:
encoding = None
# First try to get encoding from model name directly
try:
self.encoders[model] = tiktoken.encoding_for_model(model)
return self.encoders[model]
except KeyError:
pass
# Try to find encoding by prefix matching
for prefix, enc_name in self.MODEL_PREFIX_TO_ENCODING.items():
if model.startswith(prefix):
encoding = enc_name
break
# Default to o200k_base for newer models
if encoding is None:
logger.warning(f"Model {model} not found in prefix mapping, using o200k_base encoding")
encoding = "o200k_base"
try:
self.encoders[model] = tiktoken.get_encoding(encoding)
except Exception as e:
logger.warning(f"Failed to get encoding {encoding} for model {model}: {e}. Falling back to cl100k_base")
self.encoders[model] = tiktoken.get_encoding("cl100k_base")
return self.encoders[model]
def count_tokens(self, messages: list, model: str = "gpt-3.5-turbo") -> int:
"""Count tokens in message list"""
encoder = self.get_encoder(model)
# All modern chat models use similar token counting
return self._count_chat_tokens(messages, encoder, model)
def _count_chat_tokens(self, messages: list, encoder, model: str) -> int:
"""Accurate token calculation for chat models
Based on OpenAI's token counting documentation:
- Each message has a fixed overhead
- Content tokens are counted per message
- Special tokens for message formatting
"""
# Token overhead varies by model
if model.startswith(("gpt-3.5-turbo", "gpt-35-turbo")):
# gpt-3.5-turbo uses different message overhead
tokens_per_message = 4 # <|start|>role<|separator|>content<|end|>
tokens_per_name = -1 # Name is omitted if not present
else:
# Most models including gpt-4, gpt-4o, o1, etc.
tokens_per_message = 3
tokens_per_name = 1
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
# Count tokens for each field in the message
for key, value in message.items():
if key == "content":
# Handle case where content might be a list (multimodal messages)
if isinstance(value, list):
for item in value:
if isinstance(item, dict) and item.get("type") == "text":
content_text = item.get("text", "")
num_tokens += len(encoder.encode(content_text, disallowed_special=()))
# Note: Image tokens are not counted here as they have fixed costs
elif isinstance(value, str):
num_tokens += len(encoder.encode(value, disallowed_special=()))
elif key == "name":
num_tokens += tokens_per_name
if isinstance(value, str):
num_tokens += len(encoder.encode(value, disallowed_special=()))
elif key == "role":
# Role is already counted in tokens_per_message
pass
elif isinstance(value, str):
# Other string fields
num_tokens += len(encoder.encode(value, disallowed_special=()))
# Every reply is primed with assistant role
num_tokens += 3
return num_tokens
def count_text_tokens(self, text: str, model: str = "gpt-3.5-turbo") -> int:
"""Count tokens in plain text"""
encoder = self.get_encoder(model)
return len(encoder.encode(text, disallowed_special=()))
# Global token counter instance
token_counter = TokenCounter()
def generate_random_trigger_signal() -> str:
"""Generate a random, self-closing trigger signal like <Function_AB1c_Start/>."""
chars = string.ascii_letters + string.digits
random_str = ''.join(secrets.choice(chars) for _ in range(4))
return f"<Function_{random_str}_Start/>"
try:
app_config = config_loader.load_config()
log_level_str = app_config.features.log_level
if log_level_str == "DISABLED":
log_level = logging.CRITICAL + 1
else:
log_level = getattr(logging, log_level_str, logging.INFO)
logging.basicConfig(
level=log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger.info(f"✅ Configuration loaded successfully: {config_loader.config_path}")
logger.info(f"📊 Configured {len(app_config.upstream_services)} upstream services")
logger.info(f"🔑 Configured {len(app_config.client_authentication.allowed_keys)} client keys")
MODEL_TO_SERVICE_MAPPING, ALIAS_MAPPING = config_loader.get_model_to_service_mapping()
DEFAULT_SERVICE = config_loader.get_default_service()
ALLOWED_CLIENT_KEYS = config_loader.get_allowed_client_keys()
GLOBAL_TRIGGER_SIGNAL = generate_random_trigger_signal()
logger.info(f"🎯 Configured {len(MODEL_TO_SERVICE_MAPPING)} model mappings")
if ALIAS_MAPPING:
logger.info(f"🔄 Configured {len(ALIAS_MAPPING)} model aliases: {list(ALIAS_MAPPING.keys())}")
logger.info(f"🔄 Default service: {DEFAULT_SERVICE['name']}")
except Exception as e:
logger.error(f"❌ Configuration loading failed: {type(e).__name__}")
logger.error(f"❌ Error details: {str(e)}")
logger.error("💡 Please ensure config.yaml file exists and is properly formatted")
exit(1)
def build_tool_call_index_from_messages(messages: List[Dict[str, Any]]) -> Dict[str, Dict[str, str]]:
"""
Build tool_call_id -> {name, arguments} index from message history.
This replaces the server-side mapping by extracting tool calls from assistant messages.
Args:
messages: List of message dicts from the request
Returns:
Dict mapping tool_call_id to {name, arguments}
"""
index = {}
for msg in messages:
if isinstance(msg, dict) and msg.get("role") == "assistant":
tool_calls = msg.get("tool_calls")
if tool_calls and isinstance(tool_calls, list):
for tc in tool_calls:
if isinstance(tc, dict):
tc_id = tc.get("id")
func = tc.get("function", {})
if tc_id and isinstance(func, dict):
name = func.get("name", "")
arguments = func.get("arguments", "{}")
if not isinstance(arguments, str):
try:
arguments = json.dumps(arguments, ensure_ascii=False)
except Exception:
arguments = str(arguments)
if name:
index[tc_id] = {
"name": name,
"arguments": arguments
}
logger.debug(f"🔧 Indexed tool_call_id: {tc_id} -> {name}")
logger.debug(f"🔧 Built tool_call index with {len(index)} entries")
return index
def get_fc_error_retry_prompt(original_response: str, error_details: str) -> str:
custom_template = app_config.features.fc_error_retry_prompt_template
if custom_template:
return custom_template.format(
original_response=original_response,
error_details=error_details
)
return f"""Your previous response attempted to make a function call but the format was invalid or could not be parsed.
**Your original response:**
```
{original_response}
```
**Error details:**
{error_details}
**Instructions:**
Please retry and output the function call in the correct XML format. Remember:
1. Start with the trigger signal on its own line
2. Immediately follow with the <function_calls> XML block
3. Use <args_json> with valid JSON for parameters
4. Do not add any text after </function_calls>
Please provide the corrected function call now. DO NOT OUTPUT ANYTHING ELSE."""
def _schema_type_name(v: Any) -> str:
if v is None:
return "null"
if isinstance(v, bool):
return "boolean"
if isinstance(v, int) and not isinstance(v, bool):
return "integer"
if isinstance(v, float):
return "number"
if isinstance(v, str):
return "string"
if isinstance(v, list):
return "array"
if isinstance(v, dict):
return "object"
return type(v).__name__
def _validate_value_against_schema(value: Any, schema: Dict[str, Any], path: str = "args", depth: int = 0) -> List[str]:
"""Best-effort JSON Schema validation for tool arguments.
Intentional subset:
- type, properties, required, additionalProperties
- items (array)
- enum, const
- anyOf/oneOf/allOf (basic)
- pattern/minLength/maxLength (string)
Returns a list of human-readable errors.
"""
if schema is None:
schema = {}
if depth > 8:
return [] # prevent pathological recursion
errors: List[str] = []
# Combinators
if isinstance(schema.get("allOf"), list):
for idx, sub in enumerate(schema["allOf"]):
errors.extend(_validate_value_against_schema(value, sub or {}, f"{path}.allOf[{idx}]", depth + 1))
return errors
if isinstance(schema.get("anyOf"), list):
option_errors = [
_validate_value_against_schema(value, sub or {}, path, depth + 1)
for sub in schema["anyOf"]
]
if not any(len(e) == 0 for e in option_errors):
errors.append(f"{path}: value does not satisfy anyOf options")
return errors
if isinstance(schema.get("oneOf"), list):
option_errors = [
_validate_value_against_schema(value, sub or {}, path, depth + 1)
for sub in schema["oneOf"]
]
ok_count = sum(1 for e in option_errors if len(e) == 0)
if ok_count != 1:
errors.append(f"{path}: value must satisfy exactly one oneOf option (matched {ok_count})")
return errors
# enum/const
if "const" in schema:
if value != schema.get("const"):
errors.append(f"{path}: expected const={schema.get('const')!r}, got {value!r}")
return errors
enum_vals = schema.get("enum")
if isinstance(enum_vals, list):
if value not in enum_vals:
errors.append(f"{path}: expected one of {enum_vals!r}, got {value!r}")
return errors
stype = schema.get("type")
if stype is None:
# If schema omits type but has object keywords, treat as object.
if any(k in schema for k in ("properties", "required", "additionalProperties")):
stype = "object"
# type checks
def _type_ok(t: str) -> bool:
if t == "object":
return isinstance(value, dict)
if t == "array":
return isinstance(value, list)
if t == "string":
return isinstance(value, str)
if t == "boolean":
return isinstance(value, bool)
if t == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if t == "number":
return (isinstance(value, (int, float)) and not isinstance(value, bool))
if t == "null":
return value is None
return True
if isinstance(stype, str):
if not _type_ok(stype):
errors.append(f"{path}: expected type '{stype}', got '{_schema_type_name(value)}'")
return errors
elif isinstance(stype, list):
if not any(_type_ok(t) for t in stype if isinstance(t, str)):
errors.append(f"{path}: expected type in {stype!r}, got '{_schema_type_name(value)}'")
return errors
# string constraints
if isinstance(value, str):
min_len = schema.get("minLength")
max_len = schema.get("maxLength")
if isinstance(min_len, int) and len(value) < min_len:
errors.append(f"{path}: string shorter than minLength={min_len}")
if isinstance(max_len, int) and len(value) > max_len:
errors.append(f"{path}: string longer than maxLength={max_len}")
pat = schema.get("pattern")
if isinstance(pat, str):
try:
if re.search(pat, value) is None:
errors.append(f"{path}: string does not match pattern {pat!r}")
except re.error:
# ignore invalid patterns in schema
pass
# object
if isinstance(value, dict):
props = schema.get("properties")
if props is None:
props = {}
if not isinstance(props, dict):
props = {}
required = schema.get("required")
if required is None:
required = []
if not isinstance(required, list):
required = []
required = [k for k in required if isinstance(k, str)]
for k in required:
if k not in value:
errors.append(f"{path}: missing required property '{k}'")
additional = schema.get("additionalProperties", True)
for k, v in value.items():
if k in props:
errors.extend(_validate_value_against_schema(v, props.get(k) or {}, f"{path}.{k}", depth + 1))
else:
if additional is False:
errors.append(f"{path}: unexpected property '{k}'")
elif isinstance(additional, dict):
errors.extend(_validate_value_against_schema(v, additional, f"{path}.{k}", depth + 1))
# array
if isinstance(value, list):
items = schema.get("items")
if isinstance(items, dict):
for i, v in enumerate(value):
errors.extend(_validate_value_against_schema(v, items, f"{path}[{i}]", depth + 1))
return errors
def validate_parsed_tools(parsed_tools: List[Dict[str, Any]], tools: List["Tool"]) -> Optional[str]:
"""Validate parsed tool calls against declared tools definitions.
Returns a single error string if invalid, else None.
"""
tools = tools or []
allowed = {t.function.name: (t.function.parameters or {}) for t in tools if t and t.function and t.function.name}
allowed_names = sorted(list(allowed.keys()))
for idx, call in enumerate(parsed_tools or []):
name = (call or {}).get("name")
args = (call or {}).get("args")
if not isinstance(name, str) or not name:
return f"Tool call #{idx + 1}: missing tool name"
if name not in allowed:
return (
f"Tool call #{idx + 1}: unknown tool '{name}'. "
f"Allowed tools: {allowed_names}"
)
if not isinstance(args, dict):
return f"Tool call #{idx + 1} '{name}': arguments must be a JSON object, got {_schema_type_name(args)}"
schema = allowed[name] or {}
errs = _validate_value_against_schema(args, schema, path=f"{name}")
if errs:
# Keep message short but actionable
preview = "; ".join(errs[:6])
more = f" (+{len(errs) - 6} more)" if len(errs) > 6 else ""
return f"Tool call #{idx + 1} '{name}': schema validation failed: {preview}{more}"
return None
async def attempt_fc_parse_with_retry(
content: str,
trigger_signal: str,
messages: List[Dict[str, Any]],
upstream_url: str,
headers: Dict[str, str],
model: str,
tools: List["Tool"],
timeout: int
) -> Optional[List[Dict[str, Any]]]:
"""
Attempt to parse function calls from content. If parsing fails and retry is enabled,
send error details back to the model for correction.
Returns parsed tool calls or None if parsing ultimately fails.
"""
def _parse_and_validate(current_content: str) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]:
parsed = parse_function_calls_xml(current_content, trigger_signal)
if not parsed:
return None, None
validation_error = validate_parsed_tools(parsed, tools)
if validation_error:
return None, validation_error
return parsed, None
if not app_config.features.enable_fc_error_retry:
parsed, _err = _parse_and_validate(content)
return parsed
max_attempts = app_config.features.fc_error_retry_max_attempts
current_content = content
current_messages = messages.copy()
for attempt in range(max_attempts):
parsed_tools, validation_error = _parse_and_validate(current_content)
if parsed_tools:
if attempt > 0:
logger.info(f"✅ Function call parsing succeeded on retry attempt {attempt + 1}")
return parsed_tools
# IMPORTANT: only treat this as a tool-call attempt if the trigger signal appears
# outside of blocks. Otherwise models that mention the trigger
# inside think can spuriously trigger retries.
if find_last_trigger_signal_outside_think(current_content, trigger_signal) == -1:
logger.debug("🔧 No trigger signal found outside <think> blocks; not a function call attempt")
return None
if attempt >= max_attempts - 1:
logger.warning(f"⚠️ Function call parsing failed after {max_attempts} attempts")
return None
# If parsing succeeded but tool/schema validation failed, report semantic errors.
error_details = validation_error or _diagnose_fc_parse_error(current_content, trigger_signal)
retry_prompt = get_fc_error_retry_prompt(current_content, error_details)
logger.info(f"🔄 Function call parsing failed, attempting retry {attempt + 2}/{max_attempts}")
logger.debug(f"🔧 Error details: {error_details}")
retry_messages = current_messages + [
{"role": "assistant", "content": current_content},
{"role": "user", "content": retry_prompt}
]
try:
retry_response = await http_client.post(
upstream_url,
json={"model": model, "messages": retry_messages, "stream": False},
headers=headers,
timeout=timeout
)
retry_response.raise_for_status()
retry_json = retry_response.json()
if retry_json.get("choices") and len(retry_json["choices"]) > 0:
current_content = retry_json["choices"][0].get("message", {}).get("content", "")
current_messages = retry_messages
logger.debug(f"🔧 Received retry response, length: {len(current_content)}")
else:
logger.warning(f"⚠️ Retry response has no valid choices")
return None
except Exception as e:
logger.error(f"❌ Retry request failed: {e}")
return None
return None
def _diagnose_fc_parse_error(content: str, trigger_signal: str) -> str:
"""Diagnose why function call parsing failed and return error description."""
errors = []
if trigger_signal not in content:
errors.append(f"Trigger signal '{trigger_signal[:30]}...' not found in response")
return "; ".join(errors)
cleaned = remove_think_blocks(content)
if "<function_calls>" not in cleaned:
errors.append("Missing <function_calls> tag after trigger signal")
elif "</function_calls>" not in cleaned:
errors.append("Missing closing </function_calls> tag")
if "<function_call>" not in cleaned:
errors.append("No <function_call> blocks found inside <function_calls>")
elif "</function_call>" not in cleaned:
errors.append("Missing closing </function_call> tag")
fc_match = re.search(r"<function_calls>([\s\S]*?)</function_calls>", cleaned)
if fc_match:
fc_content = fc_match.group(1)
if "<tool>" not in fc_content:
errors.append("Missing <tool> tag inside function_call")
if "<args_json>" not in fc_content and "<args>" not in fc_content:
errors.append("Missing <args_json> or <args> tag inside function_call")
args_json_match = re.search(r"<args_json>([\s\S]*?)</args_json>", fc_content)
if args_json_match:
args_content = args_json_match.group(1).strip()
cdata_match = re.search(r"<!\[CDATA\[([\s\S]*?)\]\]>", args_content)
json_to_parse = cdata_match.group(1) if cdata_match else args_content
try:
parsed = json.loads(json_to_parse)
if not isinstance(parsed, dict):
errors.append(f"args_json must be a JSON object, got {type(parsed).__name__}")
except json.JSONDecodeError as e:
errors.append(f"Invalid JSON in args_json: {str(e)}")
if not errors:
errors.append("XML structure appears correct but parsing failed for unknown reason")
return "; ".join(errors)
def format_tool_result_for_ai(tool_name: str, tool_arguments: str, result_content: str) -> str:
"""
Format tool call results for AI understanding with complete context.
Args:
tool_name: Name of the tool that was called
tool_arguments: Arguments passed to the tool (JSON string)
result_content: Execution result from the tool
Returns:
Formatted text for upstream model
"""
formatted_text = f"""Tool execution result:
- Tool name: {tool_name}
- Tool arguments: {tool_arguments}
- Execution result:
<tool_result>
{result_content}
</tool_result>"""
logger.debug(f"🔧 Formatted tool result for {tool_name}")
return formatted_text
def format_assistant_tool_calls_for_ai(tool_calls: List[Dict[str, Any]], trigger_signal: str) -> str:
"""Format assistant tool calls into AI-readable string format."""
logger.debug(f"🔧 Formatting assistant tool calls. Count: {len(tool_calls)}")
def _wrap_cdata(text: str) -> str:
# Avoid illegal ']]>' sequence inside CDATA by splitting.
safe = (text or "").replace("]]>", "]]]]><![CDATA[>")
return f"<![CDATA[{safe}]]>"
xml_calls_parts = []
for tool_call in tool_calls:
function_info = tool_call.get("function", {})
name = function_info.get("name", "")
arguments_val = function_info.get("arguments", "{}")
# Strict: assistant.tool_calls must carry JSON-object arguments (or a JSON string representing an object).
try:
if isinstance(arguments_val, dict):
args_dict = arguments_val
elif isinstance(arguments_val, str):
parsed = json.loads(arguments_val or "{}")
if not isinstance(parsed, dict):
raise ValueError(f"arguments must be a JSON object, got {type(parsed).__name__}")
args_dict = parsed
else:
raise ValueError(f"arguments must be a JSON object or JSON string, got {type(arguments_val).__name__}")
except Exception as e:
raise HTTPException(
status_code=400,
detail=f"Invalid assistant.tool_calls arguments for tool '{name}': {e}"
)
args_payload = json.dumps(args_dict, ensure_ascii=False)
xml_call = (
f"<function_call>\n"
f"<tool>{name}</tool>\n"
f"<args_json>{_wrap_cdata(args_payload)}</args_json>\n"
f"</function_call>"
)
xml_calls_parts.append(xml_call)
all_calls = "\n".join(xml_calls_parts)
final_str = f"{trigger_signal}\n<function_calls>\n{all_calls}\n</function_calls>"
logger.debug("🔧 Assistant tool calls formatted successfully.")
return final_str
def get_function_call_prompt_template(trigger_signal: str) -> str:
"""
Generate prompt template based on dynamic trigger signal
"""
custom_template = app_config.features.prompt_template
if custom_template:
logger.info("🔧 Using custom prompt template from configuration")
return custom_template.format(
trigger_signal=trigger_signal,
tools_list="{tools_list}"
)
return f"""
You have access to the following available tools to help solve problems:
{{tools_list}}
**IMPORTANT CONTEXT NOTES:**
1. You can call MULTIPLE tools in a single response if needed.
2. Even though you can call multiple tools, you MUST respect the user's later constraints and preferences (e.g., the user may request no tools, only one tool, or a specific tool/workflow).
3. The conversation context may already contain tool execution results from previous function calls. Review the conversation history carefully to avoid unnecessary duplicate tool calls.
4. When tool execution results are present in the context, they will be formatted with XML tags like <tool_result>...</tool_result> for easy identification.
5. This is the ONLY format you can use for tool calls, and any deviation will result in failure.
When you need to use tools, you **MUST** strictly follow this format. Do NOT include any extra text, explanations, or dialogue on the first and second lines of the tool call syntax:
1. When starting tool calls, begin on a new line with exactly:
{trigger_signal}
No leading or trailing spaces, output exactly as shown above. The trigger signal MUST be on its own line and appear only once. Do not output a trigger signal for each tool call.
2. Starting from the second line, **immediately** follow with the complete <function_calls> XML block.
3. For multiple tool calls, include multiple <function_call> blocks within the same <function_calls> wrapper, not separate blocks. Output the trigger signal only once, then one <function_calls> with all <function_call> children.
4. Do not add any text or explanation after the closing </function_calls> tag.
STRICT ARGUMENT KEY RULES:
- You MUST use parameter keys EXACTLY as defined (case- and punctuation-sensitive). Do NOT rename, add, or remove characters.
- If a key starts with a hyphen (e.g., "-i", "-C"), you MUST keep the leading hyphen in the JSON key. Never convert "-i" to "i" or "-C" to "C".
- The <tool> tag must contain the exact name of a tool from the list. Any other tool name is invalid.
- The <args_json> tag must contain a single JSON object with all required arguments for that tool.
- You MAY wrap the JSON content inside <![CDATA[...]]> to avoid XML escaping issues.
CORRECT Example (multiple tool calls):
...response content (optional)...
{trigger_signal}
<function_calls>
<function_call>
<tool>Grep</tool>
<args_json><![CDATA[{{"-i": true, "-C": 2, "path": "."}}]]></args_json>
</function_call>
<function_call>
<tool>search</tool>
<args_json><![CDATA[{{"keywords": ["Python Document", "how to use python"]}}]]></args_json>
</function_call>
</function_calls>
INCORRECT Example (extra text + wrong key names — DO NOT DO THIS):
...response content (optional)...
{trigger_signal}
I will call the tools for you.
<function_calls>
<function_call>
<tool>Grep</tool>
<args>
<i>true</i>
<C>2</C>
<path>.</path>
</args>
</function_call>
</function_calls>
INCORRECT Example (output non-XML format — DO NOT DO THIS):
...response content (optional)...
```json
{{"files":[{{"path":"system.py"}}]}}
```
Now please be ready to strictly follow the above specifications.
"""
class ToolFunction(BaseModel):
name: str
description: Optional[str] = None
parameters: Dict[str, Any]
class Tool(BaseModel):
type: Literal["function"]
function: ToolFunction
class Message(BaseModel):
role: str
content: Optional[str] = None
tool_calls: Optional[List[Dict[str, Any]]] = None
tool_call_id: Optional[str] = None
name: Optional[str] = None
class Config:
extra = "allow"
class ToolChoice(BaseModel):
type: Literal["function"]
function: Dict[str, str]
class ChatCompletionRequest(BaseModel):
model: str
messages: List[Dict[str, Any]]
tools: Optional[List[Tool]] = None
tool_choice: Optional[Union[str, ToolChoice]] = None
stream: Optional[bool] = False
stream_options: Optional[Dict[str, Any]] = None
temperature: Optional[float] = None
max_tokens: Optional[int] = None
top_p: Optional[float] = None
frequency_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
n: Optional[int] = None
stop: Optional[Union[str, List[str]]] = None
class Config:
extra = "allow"
def generate_function_prompt(tools: List[Tool], trigger_signal: str) -> tuple[str, str]:
"""
Generate injected system prompt based on tools definition in client request.
Returns: (prompt_content, trigger_signal)
Raises:
HTTPException: If tool schema validation fails (e.g., required keys not in properties)
"""
tools_list_str = []
for i, tool in enumerate(tools):
func = tool.function
name = func.name
description = func.description or ""
# Robustly read JSON Schema fields + validate basic types
schema: Dict[str, Any] = func.parameters or {}
props_raw = schema.get("properties", {})
if props_raw is None:
props_raw = {}
if not isinstance(props_raw, dict):
raise HTTPException(
status_code=400,
detail=f"Tool '{name}': 'properties' must be an object, got {type(props_raw).__name__}"
)
props: Dict[str, Any] = props_raw
required_raw = schema.get("required", [])
if required_raw is None:
required_raw = []
if not isinstance(required_raw, list):
raise HTTPException(
status_code=400,
detail=f"Tool '{name}': 'required' must be a list, got {type(required_raw).__name__}"
)
non_string_required = [k for k in required_raw if not isinstance(k, str)]
if non_string_required:
raise HTTPException(
status_code=400,
detail=f"Tool '{name}': 'required' entries must be strings, got {non_string_required}"
)
required_list: List[str] = required_raw
missing_keys = [key for key in required_list if key not in props]
if missing_keys:
raise HTTPException(
status_code=400,
detail=f"Tool '{name}': required parameters {missing_keys} are not defined in properties"
)
# Brief summary line: name (type)
params_summary = ", ".join([
f"{p_name} ({(p_info or {}).get('type', 'any')})" for p_name, p_info in props.items()
]) or "None"
# Build detailed parameter spec for prompt injection (default enabled)
detail_lines: List[str] = []
for p_name, p_info in props.items():
p_info = p_info or {}
p_type = p_info.get("type", "any")
is_required = "Yes" if p_name in required_list else "No"
p_desc = p_info.get("description")
enum_vals = p_info.get("enum")
default_val = p_info.get("default")
examples_val = p_info.get("examples") or p_info.get("example")
# Common constraints and hints
constraints: Dict[str, Any] = {}
for key in [
"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum",
"minLength", "maxLength", "pattern", "format",
"minItems", "maxItems", "uniqueItems"
]:
if key in p_info:
constraints[key] = p_info.get(key)
# Array item type hint
if p_type == "array":
items = p_info.get("items") or {}
if isinstance(items, dict):
itype = items.get("type")
if itype:
constraints["items.type"] = itype
# Compose pretty lines
detail_lines.append(f"- {p_name}:")
detail_lines.append(f" - type: {p_type}")
detail_lines.append(f" - required: {is_required}")
if p_desc:
detail_lines.append(f" - description: {p_desc}")
if enum_vals is not None:
try:
detail_lines.append(f" - enum: {json.dumps(enum_vals, ensure_ascii=False)}")
except Exception:
detail_lines.append(f" - enum: {enum_vals}")
if default_val is not None:
try:
detail_lines.append(f" - default: {json.dumps(default_val, ensure_ascii=False)}")
except Exception:
detail_lines.append(f" - default: {default_val}")
if examples_val is not None:
try:
detail_lines.append(f" - examples: {json.dumps(examples_val, ensure_ascii=False)}")
except Exception:
detail_lines.append(f" - examples: {examples_val}")
if constraints:
try:
detail_lines.append(f" - constraints: {json.dumps(constraints, ensure_ascii=False)}")
except Exception:
detail_lines.append(f" - constraints: {constraints}")
detail_block = "\n".join(detail_lines) if detail_lines else "(no parameter details)"
desc_block = f"```\n{description}\n```" if description else "None"
tools_list_str.append(
f"{i + 1}. <tool name=\"{name}\">\n"
f" Description:\n{desc_block}\n"
f" Parameters summary: {params_summary}\n"
f" Required parameters: {', '.join(required_list) if required_list else 'None'}\n"
f" Parameter details:\n{detail_block}"
)
prompt_template = get_function_call_prompt_template(trigger_signal)
prompt_content = prompt_template.replace("{tools_list}", "\n\n".join(tools_list_str))
return prompt_content, trigger_signal
def remove_think_blocks(text: str) -> str:
"""
Temporarily remove all <think>...</think> blocks for XML parsing
Supports nested think tags
Note: This function is only used for temporary parsing and does not affect the original content returned to the user
"""
while '<think>' in text and '</think>' in text:
start_pos = text.find('<think>')
if start_pos == -1:
break
pos = start_pos + 7
depth = 1
while pos < len(text) and depth > 0:
if text[pos:pos+7] == '<think>':
depth += 1
pos += 7
elif text[pos:pos+8] == '</think>':
depth -= 1
pos += 8
else:
pos += 1
if depth == 0:
text = text[:start_pos] + text[pos:]
else:
break
return text
def find_last_trigger_signal_outside_think(text: str, trigger_signal: str) -> int:
"""
Find the last occurrence position of trigger_signal that is NOT inside any <think>...</think> block.
Returns -1 if not found.
"""
if not text or not trigger_signal:
return -1
i = 0
think_depth = 0
last_pos = -1
while i < len(text):
if text.startswith("<think>", i):
think_depth += 1
i += 7
continue
if text.startswith("</think>", i):
think_depth = max(0, think_depth - 1)
i += 8
continue
if think_depth == 0 and text.startswith(trigger_signal, i):
last_pos = i
# Move forward by 1 to allow overlapping search (not expected, but safe)
i += 1
continue
i += 1
return last_pos
class StreamingFunctionCallDetector:
"""Enhanced streaming function call detector, supports dynamic trigger signals, avoids misjudgment within <think> tags
Core features:
1. Avoid triggering tool call detection within <think> blocks
2. Normally output <think> block content to the user
3. Supports nested think tags
"""
def __init__(self, trigger_signal: str):
self.trigger_signal = trigger_signal
self.reset()
def reset(self):
self.content_buffer = ""
self.state = "detecting" # detecting, tool_parsing