jwadow commited on
Commit
2aa4eaf
·
1 Parent(s): e687d2a

fix: add Cline support - sanitize tool schemas and handle empty descriptions

Browse files
kiro_gateway/converters.py CHANGED
@@ -507,6 +507,57 @@ def build_kiro_payload(
507
  return payload
508
 
509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  def _build_user_input_context(
511
  request_data: ChatCompletionRequest,
512
  current_message: ChatMessage,
@@ -536,11 +587,21 @@ def _build_user_input_context(
536
  tools_list = []
537
  for tool in tools_to_use:
538
  if tool.type == "function":
 
 
 
 
 
 
 
 
 
 
539
  tools_list.append({
540
  "toolSpecification": {
541
  "name": tool.function.name,
542
- "description": tool.function.description or "",
543
- "inputSchema": {"json": tool.function.parameters or {}}
544
  }
545
  })
546
  if tools_list:
 
507
  return payload
508
 
509
 
510
+ def _sanitize_json_schema(schema: Optional[Dict[str, Any]]) -> Dict[str, Any]:
511
+ """
512
+ Очищает JSON Schema от полей, которые Kiro API не принимает.
513
+
514
+ Kiro API возвращает ошибку 400 "Improperly formed request" если:
515
+ - required является пустым массивом []
516
+ - additionalProperties присутствует в схеме
517
+
518
+ Эта функция рекурсивно обрабатывает схему и удаляет проблемные поля.
519
+
520
+ Args:
521
+ schema: JSON Schema для очистки
522
+
523
+ Returns:
524
+ Очищенная копия схемы
525
+ """
526
+ if not schema:
527
+ return {}
528
+
529
+ # Создаём копию чтобы не мутировать оригинал
530
+ result = {}
531
+
532
+ for key, value in schema.items():
533
+ # Пропускаем пустые required массивы
534
+ if key == "required" and isinstance(value, list) and len(value) == 0:
535
+ continue
536
+
537
+ # Пропускаем additionalProperties - Kiro API его не поддерживает
538
+ if key == "additionalProperties":
539
+ continue
540
+
541
+ # Рекурсивно обрабатываем вложенные объекты
542
+ if key == "properties" and isinstance(value, dict):
543
+ result[key] = {
544
+ prop_name: _sanitize_json_schema(prop_value) if isinstance(prop_value, dict) else prop_value
545
+ for prop_name, prop_value in value.items()
546
+ }
547
+ elif isinstance(value, dict):
548
+ result[key] = _sanitize_json_schema(value)
549
+ elif isinstance(value, list):
550
+ # Обрабатываем списки (например, anyOf, oneOf)
551
+ result[key] = [
552
+ _sanitize_json_schema(item) if isinstance(item, dict) else item
553
+ for item in value
554
+ ]
555
+ else:
556
+ result[key] = value
557
+
558
+ return result
559
+
560
+
561
  def _build_user_input_context(
562
  request_data: ChatCompletionRequest,
563
  current_message: ChatMessage,
 
587
  tools_list = []
588
  for tool in tools_to_use:
589
  if tool.type == "function":
590
+ # Очищаем parameters от полей, которые Kiro API не принимает
591
+ sanitized_params = _sanitize_json_schema(tool.function.parameters)
592
+
593
+ # Kiro API требует непустое description
594
+ # Если description пустое или None, используем placeholder
595
+ description = tool.function.description
596
+ if not description or not description.strip():
597
+ description = f"Tool: {tool.function.name}"
598
+ logger.debug(f"Tool '{tool.function.name}' has empty description, using placeholder")
599
+
600
  tools_list.append({
601
  "toolSpecification": {
602
  "name": tool.function.name,
603
+ "description": description,
604
+ "inputSchema": {"json": sanitized_params}
605
  }
606
  })
607
  if tools_list:
tests/README.md CHANGED
@@ -516,7 +516,7 @@ Unit-тесты для **DebugLogger** (отладочное логирован
516
 
517
  ### `tests/unit/test_converters.py`
518
 
519
- Unit-тесты для конвертеров **OpenAI <-> Kiro**. **50 тестов.**
520
 
521
  #### `TestExtractTextContent`
522
 
@@ -650,11 +650,85 @@ Unit-тесты для конвертеров **OpenAI <-> Kiro**. **50 тест
650
  - **Что он делает**: Проверяет обработку None description
651
  - **Цель**: Убедиться, что None description не вызывает ошибок
652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  #### `TestBuildUserInputContext`
654
 
655
  - **`test_builds_tools_context()`**: Проверяет построение контекста с tools
656
  - **`test_returns_empty_for_no_tools()`**: Проверяет возврат пустого контекста без tools
657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  #### `TestBuildKiroPayload`
659
 
660
  - **`test_builds_simple_payload()`**: Проверяет построение простого payload
 
516
 
517
  ### `tests/unit/test_converters.py`
518
 
519
+ Unit-тесты для конвертеров **OpenAI <-> Kiro**. **68 тестов.**
520
 
521
  #### `TestExtractTextContent`
522
 
 
650
  - **Что он делает**: Проверяет обработку None description
651
  - **Цель**: Убедиться, что None description не вызывает ошибок
652
 
653
+ #### `TestSanitizeJsonSchema`
654
+
655
+ Тесты для функции `_sanitize_json_schema`, которая очищает JSON Schema от полей, не поддерживаемых Kiro API.
656
+
657
+ - **`test_returns_empty_dict_for_none()`**:
658
+ - **Что он делает**: Проверяет обработку None
659
+ - **Цель**: Убедиться, что None возвращает пустой словарь
660
+
661
+ - **`test_returns_empty_dict_for_empty_dict()`**:
662
+ - **Что он делает**: Проверяет обработку пустого словаря
663
+ - **Цель**: Убедиться, что пустой словарь возвращается как есть
664
+
665
+ - **`test_removes_empty_required_array()`**:
666
+ - **Что он делает**: Проверяет удаление пустого required массива
667
+ - **Цель**: Убедиться, что `required: []` удаляется из schema (критический тест для бага Cline)
668
+
669
+ - **`test_preserves_non_empty_required_array()`**:
670
+ - **Что он делает**: Проверяет сохранение непустого required массива
671
+ - **Цель**: Убедиться, что required с элементами сохраняется
672
+
673
+ - **`test_removes_additional_properties()`**:
674
+ - **Что он делает**: Проверяет удаление additionalProperties
675
+ - **Цель**: Убедиться, что additionalProperties удаляется из schema
676
+
677
+ - **`test_removes_both_empty_required_and_additional_properties()`**:
678
+ - **Что он делает**: Проверяет удаление обоих проблемных полей
679
+ - **Цель**: Убедиться, что оба поля удаляются одновременно (реальный сценарий от Cline)
680
+
681
+ - **`test_recursively_sanitizes_nested_properties()`**:
682
+ - **Что он делает**: Проверяет рекурсивную очистку вложенных properties
683
+ - **Цель**: Убедиться, что вложенные schema также очищаются
684
+
685
+ - **`test_recursively_sanitizes_dict_values()`**:
686
+ - **Что он делает**: Проверяет рекурсивную очистку dict значений
687
+ - **Цель**: Убедиться, что любые вложенные dict очищаются
688
+
689
+ - **`test_sanitizes_items_in_lists()`**:
690
+ - **Что он делает**: Проверяет очистку элементов в списках (anyOf, oneOf)
691
+ - **Цель**: Убедиться, что элементы списков также очищаются
692
+
693
+ - **`test_preserves_non_dict_list_items()`**:
694
+ - **Что он делает**: Проверяет сохранение не-dict элементов в списках
695
+ - **Цель**: Убедиться, что строки и другие типы в списках сохраняются
696
+
697
+ - **`test_complex_real_world_schema()`**:
698
+ - **Что он делает**: Проверяет очистку реальной сложной schema от Cline
699
+ - **Цель**: Убедиться, что реальные schema обрабатываются корректно
700
+
701
  #### `TestBuildUserInputContext`
702
 
703
  - **`test_builds_tools_context()`**: Проверяет построение контекста с tools
704
  - **`test_returns_empty_for_no_tools()`**: Проверяет возврат пустого контекста без tools
705
 
706
+ **Новые тесты для placeholder пустых descriptions (исправление бага Cline):**
707
+
708
+ - **`test_empty_description_replaced_with_placeholder()`**:
709
+ - **Что он делает**: Проверяет замену пустого description на placeholder
710
+ - **Цель**: Убедиться, что пустой description заменяется на "Tool: {name}" (критический тест для бага Cline с focus_chain)
711
+
712
+ - **`test_whitespace_only_description_replaced_with_placeholder()`**:
713
+ - **Что он делает**: Проверяет замену description из пробелов на placeholder
714
+ - **Цель**: Убедиться, что description с только пробелами заменяется
715
+
716
+ - **`test_none_description_replaced_with_placeholder()`**:
717
+ - **Что он делает**: Проверяет замену None description на placeholder
718
+ - **Цель**: Убедиться, что None description заменяется на "Tool: {name}"
719
+
720
+ - **`test_non_empty_description_preserved()`**:
721
+ - **Что он делает**: Проверяет сохранение непустого description
722
+ - **Цель**: Убедиться, что нормальный description не изменяется
723
+
724
+ - **`test_sanitizes_tool_parameters()`**:
725
+ - **Что он делает**: Проверяет очистку parameters от проблемных полей
726
+ - **Цель**: Убедиться, что _sanitize_json_schema применяется к parameters
727
+
728
+ - **`test_mixed_tools_with_empty_and_normal_descriptions()`**:
729
+ - **Что он делает**: Проверяет обработку смешанного списка tools
730
+ - **Цель**: Убедиться, что пустые descriptions заменяются, а нормальные сохраняются (реальный сценарий от Cline)
731
+
732
  #### `TestBuildKiroPayload`
733
 
734
  - **`test_builds_simple_payload()`**: Проверяет построение простого payload
tests/unit/test_converters.py CHANGED
@@ -17,7 +17,8 @@ from kiro_gateway.converters import (
17
  process_tools_with_long_descriptions,
18
  _extract_tool_results,
19
  _extract_tool_uses,
20
- _build_user_input_context
 
21
  )
22
  from kiro_gateway.models import ChatMessage, ChatCompletionRequest, Tool, ToolFunction
23
 
@@ -981,6 +982,253 @@ class TestProcessToolsWithLongDescriptions:
981
  assert doc == ""
982
 
983
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
984
  class TestBuildUserInputContext:
985
  """Тесты функции _build_user_input_context."""
986
 
@@ -1029,6 +1277,206 @@ class TestBuildUserInputContext:
1029
 
1030
  print(f"Сравниваем результат: Ожидалось {{}}, Получено {result}")
1031
  assert result == {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
 
1033
 
1034
  class TestBuildKiroPayloadToolCallsIntegration:
 
17
  process_tools_with_long_descriptions,
18
  _extract_tool_results,
19
  _extract_tool_uses,
20
+ _build_user_input_context,
21
+ _sanitize_json_schema
22
  )
23
  from kiro_gateway.models import ChatMessage, ChatCompletionRequest, Tool, ToolFunction
24
 
 
982
  assert doc == ""
983
 
984
 
985
+ class TestSanitizeJsonSchema:
986
+ """
987
+ Тесты функции _sanitize_json_schema.
988
+
989
+ Эта функция очищает JSON Schema от полей, которые Kiro API не принимает:
990
+ - Пустые required массивы []
991
+ - additionalProperties
992
+ """
993
+
994
+ def test_returns_empty_dict_for_none(self):
995
+ """
996
+ Что он делает: Проверяет обработку None.
997
+ Цель: Убедиться, что None возвращает пустой словарь.
998
+ """
999
+ print("Настройка: None schema...")
1000
+
1001
+ print("Действие: Очистка schema...")
1002
+ result = _sanitize_json_schema(None)
1003
+
1004
+ print(f"Сравниваем результат: Ожидалось {{}}, Получено {result}")
1005
+ assert result == {}
1006
+
1007
+ def test_returns_empty_dict_for_empty_dict(self):
1008
+ """
1009
+ Что он делает: Проверяет обработку пустого словаря.
1010
+ Цель: Убедиться, что пустой словарь возвращается как есть.
1011
+ """
1012
+ print("Настройка: Пустой словарь...")
1013
+
1014
+ print("Действие: Очистка schema...")
1015
+ result = _sanitize_json_schema({})
1016
+
1017
+ print(f"Сравниваем результат: Ожидалось {{}}, Получено {result}")
1018
+ assert result == {}
1019
+
1020
+ def test_removes_empty_required_array(self):
1021
+ """
1022
+ Что он делает: Проверяет удаление пустого required массива.
1023
+ Цель: Убедиться, что required: [] удаляется из schema.
1024
+
1025
+ Это критический тест для бага Cline, где tools с required: []
1026
+ вызывали ошибку 400 "Improperly formed request" от Kiro API.
1027
+ """
1028
+ print("Настройка: Schema с пустым required...")
1029
+ schema = {
1030
+ "type": "object",
1031
+ "properties": {},
1032
+ "required": []
1033
+ }
1034
+
1035
+ print("Действие: Очистка schema...")
1036
+ result = _sanitize_json_schema(schema)
1037
+
1038
+ print(f"Результат: {result}")
1039
+ print("Проверяем, что required удалён...")
1040
+ assert "required" not in result
1041
+ assert result["type"] == "object"
1042
+ assert result["properties"] == {}
1043
+
1044
+ def test_preserves_non_empty_required_array(self):
1045
+ """
1046
+ Что он делает: Проверяет сохранение непустого required массива.
1047
+ Цель: Убедиться, что required с элементами сохраняется.
1048
+ """
1049
+ print("Настройка: Schema с непустым required...")
1050
+ schema = {
1051
+ "type": "object",
1052
+ "properties": {
1053
+ "location": {"type": "string"}
1054
+ },
1055
+ "required": ["location"]
1056
+ }
1057
+
1058
+ print("Действие: Очистка schema...")
1059
+ result = _sanitize_json_schema(schema)
1060
+
1061
+ print(f"Результат: {result}")
1062
+ print("Проверяем, что required сохранён...")
1063
+ assert "required" in result
1064
+ assert result["required"] == ["location"]
1065
+
1066
+ def test_removes_additional_properties(self):
1067
+ """
1068
+ Что он делает: Проверяет удаление additionalProperties.
1069
+ Цель: Убедиться, что additionalProperties удаляется из schema.
1070
+
1071
+ Kiro API не поддерживает additionalProperties в JSON Schema.
1072
+ """
1073
+ print("Настройка: Schema с additionalProperties...")
1074
+ schema = {
1075
+ "type": "object",
1076
+ "properties": {},
1077
+ "additionalProperties": False
1078
+ }
1079
+
1080
+ print("Действие: Очистка schema...")
1081
+ result = _sanitize_json_schema(schema)
1082
+
1083
+ print(f"Результат: {result}")
1084
+ print("Проверяем, что additionalProperties удалён...")
1085
+ assert "additionalProperties" not in result
1086
+ assert result["type"] == "object"
1087
+
1088
+ def test_removes_both_empty_required_and_additional_properties(self):
1089
+ """
1090
+ Что он делает: Проверяет удаление обоих проблемных полей.
1091
+ Цель: Убедиться, что оба ��оля удаляются одновременно.
1092
+
1093
+ Это реальный сценарий от Cline, где tools имели оба поля.
1094
+ """
1095
+ print("Настройка: Schema с обоими проблемными полями...")
1096
+ schema = {
1097
+ "type": "object",
1098
+ "properties": {},
1099
+ "required": [],
1100
+ "additionalProperties": False
1101
+ }
1102
+
1103
+ print("Действие: Очистка schema...")
1104
+ result = _sanitize_json_schema(schema)
1105
+
1106
+ print(f"Результат: {result}")
1107
+ print("Проверяем, что оба поля удалены...")
1108
+ assert "required" not in result
1109
+ assert "additionalProperties" not in result
1110
+ assert result == {"type": "object", "properties": {}}
1111
+
1112
+ def test_recursively_sanitizes_nested_properties(self):
1113
+ """
1114
+ Что он делает: Проверяет рекурсивную очистку вложенных properties.
1115
+ Цель: Убедиться, что вложенные schema также очищаются.
1116
+ """
1117
+ print("Настройка: Schema с вложенными properties...")
1118
+ schema = {
1119
+ "type": "object",
1120
+ "properties": {
1121
+ "nested": {
1122
+ "type": "object",
1123
+ "properties": {},
1124
+ "required": [],
1125
+ "additionalProperties": False
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ print("Действие: Очистка schema...")
1131
+ result = _sanitize_json_schema(schema)
1132
+
1133
+ print(f"Результат: {result}")
1134
+ print("Проверяем вложенный объект...")
1135
+ nested = result["properties"]["nested"]
1136
+ assert "required" not in nested
1137
+ assert "additionalProperties" not in nested
1138
+
1139
+ def test_recursively_sanitizes_dict_values(self):
1140
+ """
1141
+ Что он делает: Проверяет рекурсивную очистку dict значений.
1142
+ Цель: Убедиться, что любые вложенные dict очищаются.
1143
+ """
1144
+ print("Настройка: Schema с вложенным dict...")
1145
+ schema = {
1146
+ "type": "object",
1147
+ "items": {
1148
+ "type": "string",
1149
+ "additionalProperties": True
1150
+ }
1151
+ }
1152
+
1153
+ print("Действие: Очистка schema...")
1154
+ result = _sanitize_json_schema(schema)
1155
+
1156
+ print(f"Результат: {result}")
1157
+ print("Проверяем вложенный items...")
1158
+ assert "additionalProperties" not in result["items"]
1159
+ assert result["items"]["type"] == "string"
1160
+
1161
+ def test_sanitizes_items_in_lists(self):
1162
+ """
1163
+ Что он делает: Проверяет очистку элементов в списках (anyOf, oneOf).
1164
+ Цель: Убедиться, что элементы списков также очищаются.
1165
+ """
1166
+ print("Настройка: Schema с anyOf...")
1167
+ schema = {
1168
+ "anyOf": [
1169
+ {"type": "string", "additionalProperties": False},
1170
+ {"type": "number", "required": []}
1171
+ ]
1172
+ }
1173
+
1174
+ print("Действие: Очистка schema...")
1175
+ result = _sanitize_json_schema(schema)
1176
+
1177
+ print(f"Результат: {result}")
1178
+ print("Проверяем элементы anyOf...")
1179
+ assert "additionalProperties" not in result["anyOf"][0]
1180
+ assert "required" not in result["anyOf"][1]
1181
+
1182
+ def test_preserves_non_dict_list_items(self):
1183
+ """
1184
+ Что он делает: Проверяет сохранение не-dict элементов в списках.
1185
+ Цель: Убедиться, что строки и другие типы в списках сохраняются.
1186
+ """
1187
+ print("Настройка: Schema с enum...")
1188
+ schema = {
1189
+ "type": "string",
1190
+ "enum": ["value1", "value2", "value3"]
1191
+ }
1192
+
1193
+ print("Действие: Очистка schema...")
1194
+ result = _sanitize_json_schema(schema)
1195
+
1196
+ print(f"Результат: {result}")
1197
+ print("Проверяем enum сохранён...")
1198
+ assert result["enum"] == ["value1", "value2", "value3"]
1199
+
1200
+ def test_complex_real_world_schema(self):
1201
+ """
1202
+ Что он делает: Проверяет очистку реальной сложной schema от Cline.
1203
+ Цель: Убедиться, что реальные schema обрабатываются корректно.
1204
+ """
1205
+ print("Настройка: Реальная schema от Cline...")
1206
+ schema = {
1207
+ "type": "object",
1208
+ "properties": {
1209
+ "question": {
1210
+ "type": "string",
1211
+ "description": "The question to ask"
1212
+ },
1213
+ "options": {
1214
+ "type": "string",
1215
+ "description": "Array of options"
1216
+ }
1217
+ },
1218
+ "required": ["question", "options"],
1219
+ "additionalProperties": False
1220
+ }
1221
+
1222
+ print("Действие: Очистка schema...")
1223
+ result = _sanitize_json_schema(schema)
1224
+
1225
+ print(f"Результат: {result}")
1226
+ print("Проверяем результат...")
1227
+ assert "additionalProperties" not in result
1228
+ assert result["required"] == ["question", "options"] # Непустой required сохраняется
1229
+ assert result["properties"]["question"]["type"] == "string"
1230
+
1231
+
1232
  class TestBuildUserInputContext:
1233
  """Тесты функции _build_user_input_context."""
1234
 
 
1277
 
1278
  print(f"Сравниваем результат: Ожидалось {{}}, Получено {result}")
1279
  assert result == {}
1280
+
1281
+ def test_empty_description_replaced_with_placeholder(self):
1282
+ """
1283
+ Что он делает: Проверяет замену пустого description на placeholder.
1284
+ Цель: Убедиться, что пустой description заменяется на "Tool: {name}".
1285
+
1286
+ Это критический тест для бага Cline, где tool focus_chain имел
1287
+ пустой description "", что вызывало ошибку 400 от Kiro API.
1288
+ """
1289
+ print("Настройка: Tool с пустым description...")
1290
+ request = ChatCompletionRequest(
1291
+ model="claude-sonnet-4",
1292
+ messages=[ChatMessage(role="user", content="Hello")],
1293
+ tools=[Tool(
1294
+ type="function",
1295
+ function=ToolFunction(
1296
+ name="focus_chain",
1297
+ description="",
1298
+ parameters={"type": "object", "properties": {}}
1299
+ )
1300
+ )]
1301
+ )
1302
+ current_msg = ChatMessage(role="user", content="Hello")
1303
+
1304
+ print("Действие: Построение контекста...")
1305
+ result = _build_user_input_context(request, current_msg)
1306
+
1307
+ print(f"Результат: {result}")
1308
+ print("Проверяем, что description заменён на placeholder...")
1309
+ tool_spec = result["tools"][0]["toolSpecification"]
1310
+ assert tool_spec["description"] == "Tool: focus_chain"
1311
+
1312
+ def test_whitespace_only_description_replaced_with_placeholder(self):
1313
+ """
1314
+ Что он делает: Проверяет замену description из пробелов на placeholder.
1315
+ Цель: Убедиться, что description с только пробелами заменяется.
1316
+ """
1317
+ print("Настройка: Tool с description из пробелов...")
1318
+ request = ChatCompletionRequest(
1319
+ model="claude-sonnet-4",
1320
+ messages=[ChatMessage(role="user", content="Hello")],
1321
+ tools=[Tool(
1322
+ type="function",
1323
+ function=ToolFunction(
1324
+ name="whitespace_tool",
1325
+ description=" ",
1326
+ parameters={}
1327
+ )
1328
+ )]
1329
+ )
1330
+ current_msg = ChatMessage(role="user", content="Hello")
1331
+
1332
+ print("Действие: Построение контекста...")
1333
+ result = _build_user_input_context(request, current_msg)
1334
+
1335
+ print(f"Результат: {result}")
1336
+ print("Проверяем, что description заменён на placeholder...")
1337
+ tool_spec = result["tools"][0]["toolSpecification"]
1338
+ assert tool_spec["description"] == "Tool: whitespace_tool"
1339
+
1340
+ def test_none_description_replaced_with_placeholder(self):
1341
+ """
1342
+ Что он делает: Проверяет замену None description на placeholder.
1343
+ Цель: Убедиться, что None description заменяется на "Tool: {name}".
1344
+ """
1345
+ print("Настройка: Tool с None description...")
1346
+ request = ChatCompletionRequest(
1347
+ model="claude-sonnet-4",
1348
+ messages=[ChatMessage(role="user", content="Hello")],
1349
+ tools=[Tool(
1350
+ type="function",
1351
+ function=ToolFunction(
1352
+ name="none_desc_tool",
1353
+ description=None,
1354
+ parameters={}
1355
+ )
1356
+ )]
1357
+ )
1358
+ current_msg = ChatMessage(role="user", content="Hello")
1359
+
1360
+ print("Действие: Построение контекста...")
1361
+ result = _build_user_input_context(request, current_msg)
1362
+
1363
+ print(f"Результат: {result}")
1364
+ print("Проверяем, что description заменён на placeholder...")
1365
+ tool_spec = result["tools"][0]["toolSpecification"]
1366
+ assert tool_spec["description"] == "Tool: none_desc_tool"
1367
+
1368
+ def test_non_empty_description_preserved(self):
1369
+ """
1370
+ Что он делает: Проверяет сохранение непустого description.
1371
+ Цель: Убедиться, что нормальный description не изменяется.
1372
+ """
1373
+ print("Настройка: Tool с нормальным description...")
1374
+ request = ChatCompletionRequest(
1375
+ model="claude-sonnet-4",
1376
+ messages=[ChatMessage(role="user", content="Hello")],
1377
+ tools=[Tool(
1378
+ type="function",
1379
+ function=ToolFunction(
1380
+ name="get_weather",
1381
+ description="Get weather for a location",
1382
+ parameters={}
1383
+ )
1384
+ )]
1385
+ )
1386
+ current_msg = ChatMessage(role="user", content="Hello")
1387
+
1388
+ print("Действие: Построение контекста...")
1389
+ result = _build_user_input_context(request, current_msg)
1390
+
1391
+ print(f"Результат: {result}")
1392
+ print("Проверяем, что description сохранён...")
1393
+ tool_spec = result["tools"][0]["toolSpecification"]
1394
+ assert tool_spec["description"] == "Get weather for a location"
1395
+
1396
+ def test_sanitizes_tool_parameters(self):
1397
+ """
1398
+ Что он делает: Проверяет очистку parameters от проблемных полей.
1399
+ Цель: Убедиться, что _sanitize_json_schema применяется к parameters.
1400
+ """
1401
+ print("Настройка: Tool с проблемными parameters...")
1402
+ request = ChatCompletionRequest(
1403
+ model="claude-sonnet-4",
1404
+ messages=[ChatMessage(role="user", content="Hello")],
1405
+ tools=[Tool(
1406
+ type="function",
1407
+ function=ToolFunction(
1408
+ name="test_tool",
1409
+ description="Test tool",
1410
+ parameters={
1411
+ "type": "object",
1412
+ "properties": {},
1413
+ "required": [],
1414
+ "additionalProperties": False
1415
+ }
1416
+ )
1417
+ )]
1418
+ )
1419
+ current_msg = ChatMessage(role="user", content="Hello")
1420
+
1421
+ print("Действие: Построение контекста...")
1422
+ result = _build_user_input_context(request, current_msg)
1423
+
1424
+ print(f"Результат: {result}")
1425
+ print("Проверяем, что parameters очищены...")
1426
+ input_schema = result["tools"][0]["toolSpecification"]["inputSchema"]["json"]
1427
+ assert "required" not in input_schema
1428
+ assert "additionalProperties" not in input_schema
1429
+
1430
+ def test_mixed_tools_with_empty_and_normal_descriptions(self):
1431
+ """
1432
+ Что он делает: Проверяет обработку смешанного списка tools.
1433
+ Цель: Убедиться, что пустые descriptions заменяются, а нормальные сохраняются.
1434
+
1435
+ Это реальный сценарий от Cline, где большинство tools имеют
1436
+ нормальные descriptions, но focus_chain имеет пустой.
1437
+ """
1438
+ print("Настройка: Смешанный список tools...")
1439
+ request = ChatCompletionRequest(
1440
+ model="claude-sonnet-4",
1441
+ messages=[ChatMessage(role="user", content="Hello")],
1442
+ tools=[
1443
+ Tool(
1444
+ type="function",
1445
+ function=ToolFunction(
1446
+ name="read_file",
1447
+ description="Read contents of a file",
1448
+ parameters={}
1449
+ )
1450
+ ),
1451
+ Tool(
1452
+ type="function",
1453
+ function=ToolFunction(
1454
+ name="focus_chain",
1455
+ description="",
1456
+ parameters={}
1457
+ )
1458
+ ),
1459
+ Tool(
1460
+ type="function",
1461
+ function=ToolFunction(
1462
+ name="write_file",
1463
+ description="Write content to a file",
1464
+ parameters={}
1465
+ )
1466
+ )
1467
+ ]
1468
+ )
1469
+ current_msg = ChatMessage(role="user", content="Hello")
1470
+
1471
+ print("Действие: Построение контекста...")
1472
+ result = _build_user_input_context(request, current_msg)
1473
+
1474
+ print(f"Результат: {result}")
1475
+ print("Проверяем descriptions...")
1476
+ tools = result["tools"]
1477
+ assert tools[0]["toolSpecification"]["description"] == "Read contents of a file"
1478
+ assert tools[1]["toolSpecification"]["description"] == "Tool: focus_chain"
1479
+ assert tools[2]["toolSpecification"]["description"] == "Write content to a file"
1480
 
1481
 
1482
  class TestBuildKiroPayloadToolCallsIntegration: