claude_converter.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. import json
  2. import uuid
  3. import time
  4. import logging
  5. from datetime import datetime
  6. from typing import List, Dict, Any, Optional, Union
  7. try:
  8. from .claude_types import ClaudeRequest, ClaudeMessage, ClaudeTool
  9. except ImportError:
  10. # Fallback for dynamic loading where relative import might fail
  11. # We assume claude_types is available in sys.modules or we can import it directly if in same dir
  12. import sys
  13. if "v2.claude_types" in sys.modules:
  14. from v2.claude_types import ClaudeRequest, ClaudeMessage, ClaudeTool
  15. else:
  16. # Try absolute import assuming v2 is in path or current dir
  17. try:
  18. from claude_types import ClaudeRequest, ClaudeMessage, ClaudeTool
  19. except ImportError:
  20. # Last resort: if loaded via importlib in app.py, we might need to rely on app.py injecting it
  21. # But app.py loads this module.
  22. pass
  23. logger = logging.getLogger(__name__)
  24. THINKING_HINT = "<antml:thinking_mode>interleaved</antml:thinking_mode><antml:max_thinking_length>16000</antml:max_thinking_length>"
  25. THINKING_START_TAG = "<thinking>"
  26. THINKING_END_TAG = "</thinking>"
  27. def _wrap_thinking_content(thinking_text: str) -> str:
  28. """Wrap thinking text with the XML tag expected by Amazon Q."""
  29. return f"{THINKING_START_TAG}{thinking_text}{THINKING_END_TAG}"
  30. def is_thinking_mode_enabled(thinking_cfg: Optional[Any]) -> bool:
  31. """Detect whether the client enabled thinking mode."""
  32. if thinking_cfg is None:
  33. return False
  34. if isinstance(thinking_cfg, bool):
  35. return thinking_cfg
  36. if isinstance(thinking_cfg, str):
  37. return thinking_cfg.lower() == "enabled"
  38. if isinstance(thinking_cfg, dict):
  39. type_val = str(thinking_cfg.get("type", "")).lower()
  40. if type_val == "enabled":
  41. return True
  42. enabled_flag = thinking_cfg.get("enabled")
  43. if isinstance(enabled_flag, bool):
  44. return enabled_flag
  45. budget = thinking_cfg.get("budget_tokens")
  46. if isinstance(budget, (int, float)) and budget > 0:
  47. return True
  48. return False
  49. def _append_thinking_hint(text: str, hint: str = THINKING_HINT) -> str:
  50. """Append the special hint once to the end of the text."""
  51. text = text or ""
  52. normalized = text.rstrip()
  53. if normalized.endswith(hint):
  54. return text
  55. if not text:
  56. return hint
  57. separator = "" if text.endswith(("\n", "\r")) else "\n"
  58. return f"{text}{separator}{hint}"
  59. def get_current_timestamp() -> str:
  60. """Get current timestamp in Amazon Q format."""
  61. now = datetime.now().astimezone()
  62. weekday = now.strftime("%A")
  63. iso_time = now.isoformat(timespec='milliseconds')
  64. return f"{weekday}, {iso_time}"
  65. def _process_tool_result_block(block: Dict[str, Any]) -> Dict[str, Any]:
  66. """Convert Claude tool_result block to Amazon Q format."""
  67. tool_use_id = block.get("tool_use_id")
  68. raw_c = block.get("content", [])
  69. aq_content = []
  70. if isinstance(raw_c, str):
  71. aq_content = [{"text": raw_c}]
  72. elif isinstance(raw_c, list):
  73. for item in raw_c:
  74. if isinstance(item, dict):
  75. if item.get("type") == "text":
  76. aq_content.append({"text": item.get("text", "")})
  77. elif "text" in item:
  78. aq_content.append({"text": item["text"]})
  79. elif isinstance(item, str):
  80. aq_content.append({"text": item})
  81. # Handle empty content
  82. if not any(i.get("text", "").strip() for i in aq_content):
  83. if block.get("status") != "error" and not block.get("is_error"):
  84. aq_content = [{"text": "Command executed successfully"}]
  85. else:
  86. aq_content = [{"text": "Tool use was cancelled by the user"}]
  87. # Determine status from both 'status' field and 'is_error' flag
  88. status = block.get("status")
  89. if not status:
  90. status = "error" if block.get("is_error") else "success"
  91. return {
  92. "toolUseId": tool_use_id,
  93. "content": aq_content,
  94. "status": status
  95. }
  96. def map_model_name(claude_model: str) -> str:
  97. """Map Claude model name to Amazon Q model ID.
  98. Accepts both short names (e.g., claude-sonnet-4) and canonical names
  99. (e.g., claude-sonnet-4-20250514).
  100. """
  101. DEFAULT_MODEL = "claude-sonnet-4.5"
  102. # Available models in the service (with KIRO_CLI origin)
  103. VALID_MODELS = {"auto", "claude-sonnet-4", "claude-sonnet-4.5", "claude-haiku-4.5", "claude-opus-4.5"}
  104. # Mapping from canonical names to short names
  105. CANONICAL_TO_SHORT = {
  106. "claude-sonnet-4-20250514": "claude-sonnet-4",
  107. "claude-sonnet-4-5-20250929": "claude-sonnet-4.5",
  108. "claude-haiku-4-5-20251001": "claude-haiku-4.5",
  109. # Amazon Q supports Opus with KIRO_CLI origin
  110. "claude-opus-4-5-20251101": "claude-opus-4.5",
  111. # Legacy Claude 3.5 Sonnet models
  112. "claude-3-5-sonnet-20241022": "claude-sonnet-4.5",
  113. "claude-3-5-sonnet-20240620": "claude-sonnet-4.5",
  114. }
  115. model_lower = claude_model.lower()
  116. # Check if it's a valid short name (but not "auto" which Amazon Q doesn't accept)
  117. if model_lower in VALID_MODELS and model_lower != "auto":
  118. return model_lower
  119. # Check if it's a canonical name
  120. if model_lower in CANONICAL_TO_SHORT:
  121. return CANONICAL_TO_SHORT[model_lower]
  122. # Unknown model - log warning and return default
  123. logger.warning(f"Unknown model '{claude_model}', falling back to default model '{DEFAULT_MODEL}'")
  124. return DEFAULT_MODEL
  125. def extract_text_from_content(content: Union[str, List[Dict[str, Any]]]) -> str:
  126. """Extract text from Claude content."""
  127. if isinstance(content, str):
  128. return content
  129. elif isinstance(content, list):
  130. parts = []
  131. for block in content:
  132. if isinstance(block, dict):
  133. block_type = block.get("type")
  134. if block_type == "text":
  135. parts.append(block.get("text", ""))
  136. elif block_type == "thinking":
  137. parts.append(_wrap_thinking_content(block.get("thinking", "")))
  138. return "\n".join(parts)
  139. return ""
  140. def extract_images_from_content(content: Union[str, List[Dict[str, Any]]]) -> Optional[List[Dict[str, Any]]]:
  141. """Extract images from Claude content and convert to Amazon Q format."""
  142. if not isinstance(content, list):
  143. return None
  144. images = []
  145. for block in content:
  146. if isinstance(block, dict) and block.get("type") == "image":
  147. source = block.get("source", {})
  148. if source.get("type") == "base64":
  149. media_type = source.get("media_type", "image/png")
  150. fmt = media_type.split("/")[-1] if "/" in media_type else "png"
  151. images.append({
  152. "format": fmt,
  153. "source": {
  154. "bytes": source.get("data", "")
  155. }
  156. })
  157. return images if images else None
  158. def convert_tool(tool: ClaudeTool) -> Dict[str, Any]:
  159. """Convert Claude tool to Amazon Q tool."""
  160. desc = tool.description or ""
  161. if len(desc) > 10240:
  162. desc = desc[:10100] + "\n\n...(Full description provided in TOOL DOCUMENTATION section)"
  163. return {
  164. "toolSpecification": {
  165. "name": tool.name,
  166. "description": desc,
  167. "inputSchema": {"json": tool.input_schema}
  168. }
  169. }
  170. def _merge_tool_result_into_dict(tool_results_by_id: Dict[str, Dict[str, Any]], tool_result: Dict[str, Any]) -> None:
  171. """
  172. Merge a tool_result into the deduplicated dict.
  173. If toolUseId already exists, merge the content arrays.
  174. Args:
  175. tool_results_by_id: Dict mapping toolUseId to tool_result
  176. tool_result: The tool_result to merge
  177. """
  178. tool_use_id = tool_result.get("toolUseId")
  179. if not tool_use_id:
  180. return
  181. if tool_use_id in tool_results_by_id:
  182. # Merge content arrays
  183. existing = tool_results_by_id[tool_use_id]
  184. existing_content = existing.get("content", [])
  185. new_content = tool_result.get("content", [])
  186. # Deduplicate content by text value
  187. existing_texts = {item.get("text", "") for item in existing_content if isinstance(item, dict)}
  188. for item in new_content:
  189. if isinstance(item, dict):
  190. text = item.get("text", "")
  191. if text and text not in existing_texts:
  192. existing_content.append(item)
  193. existing_texts.add(text)
  194. existing["content"] = existing_content
  195. # If any result has error status, keep error
  196. if tool_result.get("status") == "error":
  197. existing["status"] = "error"
  198. logger.debug(f"Merged duplicate toolUseId {tool_use_id}")
  199. else:
  200. # New toolUseId, add to dict
  201. tool_results_by_id[tool_use_id] = tool_result.copy()
  202. def merge_user_messages(messages: List[Dict[str, Any]], hint: str = THINKING_HINT) -> Dict[str, Any]:
  203. """Merge consecutive user messages, keeping only the last 2 messages' images.
  204. IMPORTANT: This function properly merges toolResults from all messages to prevent
  205. losing tool execution history, which would cause infinite loops.
  206. Key fix: Deduplicate toolResults by toolUseId to prevent duplicate tool_result
  207. entries that cause the model to repeatedly respond to the same user message.
  208. When merging messages that contain thinking hints, removes duplicate hints and
  209. ensures only one hint appears at the end of the merged content.
  210. Args:
  211. messages: List of user messages to merge
  212. hint: The thinking hint string to deduplicate
  213. """
  214. if not messages:
  215. return {}
  216. all_contents = []
  217. base_context = None
  218. base_origin = None
  219. base_model = None
  220. all_images = []
  221. # Use dict to deduplicate toolResults by toolUseId
  222. tool_results_by_id: Dict[str, Dict[str, Any]] = {}
  223. for msg in messages:
  224. content = msg.get("content", "")
  225. msg_ctx = msg.get("userInputMessageContext", {})
  226. # Initialize base context from first message
  227. if base_context is None:
  228. base_context = msg_ctx.copy() if msg_ctx else {}
  229. # Remove toolResults from base to merge them separately
  230. if "toolResults" in base_context:
  231. for tr in base_context.pop("toolResults"):
  232. _merge_tool_result_into_dict(tool_results_by_id, tr)
  233. else:
  234. # Collect toolResults from subsequent messages
  235. if "toolResults" in msg_ctx:
  236. for tr in msg_ctx["toolResults"]:
  237. _merge_tool_result_into_dict(tool_results_by_id, tr)
  238. if base_origin is None:
  239. base_origin = msg.get("origin", "KIRO_CLI")
  240. if base_model is None:
  241. base_model = msg.get("modelId")
  242. # Remove thinking hint from individual message content to avoid duplication
  243. # The hint will be added once at the end of the merged content
  244. if content:
  245. content_cleaned = content.replace(hint, "").strip()
  246. if content_cleaned:
  247. all_contents.append(content_cleaned)
  248. # Collect images from each message
  249. msg_images = msg.get("images")
  250. if msg_images:
  251. all_images.append(msg_images)
  252. # Merge content and ensure thinking hint appears only once at the end
  253. merged_content = "\n\n".join(all_contents)
  254. # Check if any of the original messages had the hint (indicating thinking was enabled)
  255. had_thinking_hint = any(hint in msg.get("content", "") for msg in messages)
  256. if had_thinking_hint:
  257. merged_content = _append_thinking_hint(merged_content, hint)
  258. result = {
  259. "content": merged_content,
  260. "userInputMessageContext": base_context or {},
  261. "origin": base_origin or "KIRO_CLI",
  262. "modelId": base_model
  263. }
  264. # Add deduplicated toolResults if any
  265. if tool_results_by_id:
  266. result["userInputMessageContext"]["toolResults"] = list(tool_results_by_id.values())
  267. # Only keep images from the last 2 messages that have images
  268. if all_images:
  269. kept_images = []
  270. for img_list in all_images[-2:]: # Take last 2 messages' images
  271. kept_images.extend(img_list)
  272. if kept_images:
  273. result["images"] = kept_images
  274. return result
  275. def _reorder_tool_results_by_tool_uses(tool_results: List[Dict[str, Any]], tool_use_order: List[str]) -> List[Dict[str, Any]]:
  276. """Reorder tool_results to match the order of tool_uses from the preceding assistant message.
  277. This is critical for preventing model confusion when parallel tool calls return results
  278. in a different order than they were called.
  279. Args:
  280. tool_results: List of tool_result dicts with toolUseId
  281. tool_use_order: List of toolUseIds in the order they appeared in the assistant message
  282. Returns:
  283. Reordered list of tool_results
  284. """
  285. if not tool_use_order or not tool_results:
  286. return tool_results
  287. result_by_id = {r["toolUseId"]: r for r in tool_results}
  288. ordered_results = []
  289. # Add results in the order of tool_uses
  290. for tool_use_id in tool_use_order:
  291. if tool_use_id in result_by_id:
  292. ordered_results.append(result_by_id.pop(tool_use_id))
  293. # Add any remaining results not in the original order (shouldn't happen normally)
  294. ordered_results.extend(result_by_id.values())
  295. return ordered_results
  296. def process_history(messages: List[ClaudeMessage], thinking_enabled: bool = False, hint: str = THINKING_HINT) -> List[Dict[str, Any]]:
  297. """Process history messages to match Amazon Q format (alternating user/assistant).
  298. Dual-mode detection:
  299. - If messages already alternate correctly (no consecutive user/assistant), skip merging
  300. - If messages have consecutive same-role messages, apply merge logic
  301. Key fix: Track tool_use order from assistant messages and reorder tool_results in user
  302. messages to match. This prevents model confusion when parallel tool calls return results
  303. in a different order than they were called.
  304. """
  305. history = []
  306. seen_tool_use_ids = set() # Track tool_use IDs in assistant messages
  307. last_tool_use_order = [] # Track order of tool_uses from the last assistant message
  308. raw_history = []
  309. # First pass: convert individual messages
  310. for msg in messages:
  311. if msg.role == "user":
  312. content = msg.content
  313. text_content = ""
  314. tool_results = None
  315. images = extract_images_from_content(content)
  316. should_append_hint = thinking_enabled
  317. if isinstance(content, list):
  318. text_parts = []
  319. for block in content:
  320. if isinstance(block, dict):
  321. btype = block.get("type")
  322. if btype == "text":
  323. text_parts.append(block.get("text", ""))
  324. elif btype == "thinking":
  325. text_parts.append(_wrap_thinking_content(block.get("thinking", "")))
  326. elif btype == "tool_result":
  327. tool_use_id = block.get("tool_use_id")
  328. if tool_results is None:
  329. tool_results = []
  330. result = _process_tool_result_block(block)
  331. # Merge if exists within this message
  332. existing = next((r for r in tool_results if r["toolUseId"] == result["toolUseId"]), None)
  333. if existing:
  334. existing["content"].extend(result["content"])
  335. if result["status"] == "error":
  336. existing["status"] = "error"
  337. else:
  338. tool_results.append(result)
  339. text_content = "\n".join(text_parts)
  340. else:
  341. text_content = extract_text_from_content(content)
  342. if should_append_hint:
  343. text_content = _append_thinking_hint(text_content, hint)
  344. # Reorder tool_results to match the order of tool_uses from the preceding assistant message
  345. if tool_results and last_tool_use_order:
  346. tool_results = _reorder_tool_results_by_tool_uses(tool_results, last_tool_use_order)
  347. logger.info(f"Reordered {len(tool_results)} tool_results to match tool_uses order")
  348. user_ctx = {
  349. "envState": {
  350. "operatingSystem": "macos",
  351. "currentWorkingDirectory": "/"
  352. }
  353. }
  354. if tool_results:
  355. user_ctx["toolResults"] = tool_results
  356. u_msg = {
  357. "content": text_content,
  358. "userInputMessageContext": user_ctx,
  359. "origin": "KIRO_CLI"
  360. }
  361. if images:
  362. u_msg["images"] = images
  363. raw_history.append({"userInputMessage": u_msg})
  364. elif msg.role == "assistant":
  365. content = msg.content
  366. text_content = extract_text_from_content(content)
  367. entry = {
  368. "assistantResponseMessage": {
  369. "messageId": str(uuid.uuid4()),
  370. "content": text_content
  371. }
  372. }
  373. # Track tool_use order for reordering tool_results in the next user message
  374. last_tool_use_order = []
  375. if isinstance(content, list):
  376. tool_uses = []
  377. for block in content:
  378. if isinstance(block, dict) and block.get("type") == "tool_use":
  379. tid = block.get("id")
  380. if tid and tid not in seen_tool_use_ids:
  381. seen_tool_use_ids.add(tid)
  382. last_tool_use_order.append(tid) # Track order
  383. tool_uses.append({
  384. "toolUseId": tid,
  385. "name": block.get("name"),
  386. "input": block.get("input", {})
  387. })
  388. if tool_uses:
  389. entry["assistantResponseMessage"]["toolUses"] = tool_uses
  390. raw_history.append(entry)
  391. # Dual-mode detection: check if messages already alternate correctly
  392. has_consecutive_same_role = False
  393. prev_role = None
  394. for item in raw_history:
  395. current_role = "user" if "userInputMessage" in item else "assistant"
  396. if prev_role == current_role:
  397. has_consecutive_same_role = True
  398. break
  399. prev_role = current_role
  400. # If messages already alternate, skip merging (fast path)
  401. if not has_consecutive_same_role:
  402. logger.info("Messages already alternate correctly, skipping merge logic")
  403. return raw_history
  404. # Second pass: merge consecutive user messages (only if needed)
  405. logger.info("Detected consecutive same-role messages, applying merge logic")
  406. pending_user_msgs = []
  407. for item in raw_history:
  408. if "userInputMessage" in item:
  409. user_msg = item["userInputMessage"]
  410. has_tool_results = bool(
  411. user_msg.get("userInputMessageContext", {}).get("toolResults")
  412. )
  413. if has_tool_results:
  414. if pending_user_msgs:
  415. merged = merge_user_messages(pending_user_msgs, hint)
  416. history.append({"userInputMessage": merged})
  417. pending_user_msgs = []
  418. history.append(item)
  419. else:
  420. pending_user_msgs.append(user_msg)
  421. elif "assistantResponseMessage" in item:
  422. if pending_user_msgs:
  423. merged = merge_user_messages(pending_user_msgs, hint)
  424. history.append({"userInputMessage": merged})
  425. pending_user_msgs = []
  426. history.append(item)
  427. if pending_user_msgs:
  428. merged = merge_user_messages(pending_user_msgs, hint)
  429. history.append({"userInputMessage": merged})
  430. return history
  431. def _validate_history_alternation(history: List[Dict[str, Any]]) -> None:
  432. """Validate that history messages alternate correctly (user-assistant-user-assistant...).
  433. This prevents infinite loops caused by malformed message ordering where tool_result
  434. ends up above the user message, causing the model to keep executing the same instruction.
  435. Raises:
  436. ValueError: If messages don't alternate properly
  437. """
  438. if not history:
  439. return
  440. prev_role = None
  441. for idx, item in enumerate(history):
  442. if "userInputMessage" in item:
  443. current_role = "user"
  444. elif "assistantResponseMessage" in item:
  445. current_role = "assistant"
  446. else:
  447. continue
  448. if prev_role == current_role:
  449. raise ValueError(
  450. f"Message {idx} violates alternation rule: consecutive {current_role} messages. "
  451. f"This may indicate malformed message ordering that could cause infinite loops."
  452. )
  453. prev_role = current_role
  454. def _detect_tool_call_loop(messages: List[ClaudeMessage], threshold: int = 3) -> Optional[str]:
  455. """Detect if the same tool is being called repeatedly (potential infinite loop).
  456. Only triggers if:
  457. 1. Same tool called N times with same input
  458. 2. All calls are in CONSECUTIVE assistant messages (no user messages between them)
  459. """
  460. recent_tool_calls = []
  461. consecutive_count = 0
  462. last_tool_call = None
  463. for msg in messages[-10:]: # Check last 10 messages
  464. if msg.role == "assistant" and isinstance(msg.content, list):
  465. for block in msg.content:
  466. if isinstance(block, dict) and block.get("type") == "tool_use":
  467. tool_name = block.get("name")
  468. tool_input = json.dumps(block.get("input", {}), sort_keys=True)
  469. current_call = (tool_name, tool_input)
  470. if current_call == last_tool_call:
  471. consecutive_count += 1
  472. else:
  473. consecutive_count = 1
  474. last_tool_call = current_call
  475. recent_tool_calls.append(current_call)
  476. elif msg.role == "user":
  477. # User message breaks the consecutive chain
  478. consecutive_count = 0
  479. last_tool_call = None
  480. # Only trigger if we have consecutive identical calls
  481. if consecutive_count >= threshold:
  482. return f"Detected infinite loop: tool '{last_tool_call[0]}' called {consecutive_count} times consecutively with same input"
  483. return None
  484. def convert_claude_to_amazonq_request(req: ClaudeRequest, conversation_id: Optional[str] = None) -> Dict[str, Any]:
  485. """Convert ClaudeRequest to Amazon Q request body."""
  486. if conversation_id is None:
  487. conversation_id = str(uuid.uuid4())
  488. # Detect infinite tool call loops
  489. loop_error = _detect_tool_call_loop(req.messages, threshold=3)
  490. if loop_error:
  491. raise ValueError(loop_error)
  492. thinking_enabled = is_thinking_mode_enabled(getattr(req, "thinking", None))
  493. # 1. Tools
  494. aq_tools = []
  495. long_desc_tools = []
  496. if req.tools:
  497. for t in req.tools:
  498. if t.description and len(t.description) > 10240:
  499. long_desc_tools.append({"name": t.name, "full_description": t.description})
  500. aq_tools.append(convert_tool(t))
  501. # 2. Current Message (last user message)
  502. last_msg = req.messages[-1] if req.messages else None
  503. prompt_content = ""
  504. tool_results = None
  505. has_tool_result = False
  506. images = None
  507. if last_msg and last_msg.role == "user":
  508. content = last_msg.content
  509. images = extract_images_from_content(content)
  510. if isinstance(content, list):
  511. text_parts = []
  512. for block in content:
  513. if isinstance(block, dict):
  514. btype = block.get("type")
  515. if btype == "text":
  516. text_parts.append(block.get("text", ""))
  517. elif btype == "thinking":
  518. text_parts.append(_wrap_thinking_content(block.get("thinking", "")))
  519. elif btype == "tool_result":
  520. has_tool_result = True
  521. if tool_results is None:
  522. tool_results = []
  523. result = _process_tool_result_block(block)
  524. # Merge if exists
  525. existing = next((r for r in tool_results if r["toolUseId"] == result["toolUseId"]), None)
  526. if existing:
  527. existing["content"].extend(result["content"])
  528. if result["status"] == "error":
  529. existing["status"] = "error"
  530. else:
  531. tool_results.append(result)
  532. prompt_content = "\n".join(text_parts)
  533. else:
  534. prompt_content = extract_text_from_content(content)
  535. # Get tool_use order from the last assistant message for reordering current message's tool_results
  536. last_tool_use_order = []
  537. if len(req.messages) >= 2:
  538. # Find the last assistant message before the current user message
  539. for i in range(len(req.messages) - 2, -1, -1):
  540. if req.messages[i].role == "assistant":
  541. assistant_content = req.messages[i].content
  542. if isinstance(assistant_content, list):
  543. for block in assistant_content:
  544. if isinstance(block, dict) and block.get("type") == "tool_use":
  545. tid = block.get("id")
  546. if tid:
  547. last_tool_use_order.append(tid)
  548. break
  549. # Reorder tool_results to match the order of tool_uses from the preceding assistant message
  550. if tool_results and last_tool_use_order:
  551. tool_results = _reorder_tool_results_by_tool_uses(tool_results, last_tool_use_order)
  552. logger.info(f"Reordered {len(tool_results)} current message tool_results to match tool_uses order")
  553. # 3. Context
  554. user_ctx = {
  555. "envState": {
  556. "operatingSystem": "macos",
  557. "currentWorkingDirectory": "/"
  558. }
  559. }
  560. if aq_tools:
  561. user_ctx["tools"] = aq_tools
  562. if tool_results:
  563. user_ctx["toolResults"] = tool_results
  564. # 4. Format Content
  565. formatted_content = ""
  566. if has_tool_result and not prompt_content:
  567. formatted_content = ""
  568. else:
  569. formatted_content = (
  570. "--- CONTEXT ENTRY BEGIN ---\n"
  571. f"Current time: {get_current_timestamp()}\n"
  572. "--- CONTEXT ENTRY END ---\n\n"
  573. "--- USER MESSAGE BEGIN ---\n"
  574. f"{prompt_content}\n"
  575. "--- USER MESSAGE END ---"
  576. )
  577. if long_desc_tools:
  578. docs = []
  579. for info in long_desc_tools:
  580. docs.append(f"Tool: {info['name']}\nFull Description:\n{info['full_description']}\n")
  581. formatted_content = (
  582. "--- TOOL DOCUMENTATION BEGIN ---\n"
  583. f"{''.join(docs)}"
  584. "--- TOOL DOCUMENTATION END ---\n\n"
  585. f"{formatted_content}"
  586. )
  587. if req.system and formatted_content:
  588. sys_text = ""
  589. if isinstance(req.system, str):
  590. sys_text = req.system
  591. elif isinstance(req.system, list):
  592. parts = []
  593. for b in req.system:
  594. if isinstance(b, dict) and b.get("type") == "text":
  595. parts.append(b.get("text", ""))
  596. sys_text = "\n".join(parts)
  597. if sys_text:
  598. formatted_content = (
  599. "--- SYSTEM PROMPT BEGIN ---\n"
  600. f"{sys_text}\n"
  601. "--- SYSTEM PROMPT END ---\n\n"
  602. f"{formatted_content}"
  603. )
  604. # Append thinking hint at the very end, outside all structured blocks
  605. if thinking_enabled:
  606. formatted_content = _append_thinking_hint(formatted_content)
  607. # 5. Model
  608. model_id = map_model_name(req.model)
  609. # 6. User Input Message
  610. user_input_msg = {
  611. "content": formatted_content,
  612. "userInputMessageContext": user_ctx,
  613. "origin": "KIRO_CLI",
  614. "modelId": model_id
  615. }
  616. if images:
  617. user_input_msg["images"] = images
  618. # 7. History
  619. history_msgs = req.messages[:-1] if len(req.messages) > 1 else []
  620. aq_history = process_history(history_msgs, thinking_enabled=thinking_enabled, hint=THINKING_HINT)
  621. # Validate history alternation to prevent infinite loops
  622. _validate_history_alternation(aq_history)
  623. # 8. Final Body
  624. return {
  625. "conversationState": {
  626. "conversationId": conversation_id,
  627. "history": aq_history,
  628. "currentMessage": {
  629. "userInputMessage": user_input_msg
  630. },
  631. "chatTriggerType": "MANUAL"
  632. }
  633. }