From b95f3a520251253559ae49ef578d96bae499ebe5 Mon Sep 17 00:00:00 2001 From: Riccardo Roveri Date: Wed, 19 Aug 2026 18:14:03 +0200 Subject: [PATCH] fix(providers): use copy-on-write instead of deepcopy in NVIDIA prepare_messages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the unresolved review comment on #30674 — avoid deep-copying the whole conversation (including large tool outputs and attachments) to sanitize two top-level keys on a handful of tool-role messages. Switches to a shallow outer-list copy + shallow per-message dict copy, applied only to messages that actually carry name/tool_name. Matches the copy-on-write pattern already used by the shared sanitizer in agent/transports/chat_completions.py and by QwenProfile.prepare_messages(). The needs_sanitize early-return path is preserved unchanged so the existing identity check (prepare_messages returns the original list object when nothing needs sanitizing) continues to hold. --- plugins/model-providers/nvidia/__init__.py | 25 ++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/plugins/model-providers/nvidia/__init__.py b/plugins/model-providers/nvidia/__init__.py index a9e8c7382f..1175693692 100644 --- a/plugins/model-providers/nvidia/__init__.py +++ b/plugins/model-providers/nvidia/__init__.py @@ -1,6 +1,5 @@ """NVIDIA NIM provider profile.""" -import copy from typing import Any from providers import register_provider @@ -20,11 +19,25 @@ class NvidiaProviderProfile(ProviderProfile): if not needs_sanitize: return messages - sanitized = copy.deepcopy(messages) - for msg in sanitized: - if isinstance(msg, dict) and msg.get("role") == "tool": - msg.pop("name", None) - msg.pop("tool_name", None) + # Copy-on-write: shallow outer-list copy, then a shallow dict copy + # only for the role:"tool" messages that actually need a field + # dropped. Avoids recursively deep-copying every message's content + # (including large tool outputs and attachments) for a turn that + # only ever needs to touch two top-level keys on a handful of + # messages. Matches the pattern already used by the shared + # sanitizer in agent/transports/chat_completions.py and by + # QwenProfile.prepare_messages(). + sanitized = list(messages) + for idx, msg in enumerate(messages): + if ( + isinstance(msg, dict) + and msg.get("role") == "tool" + and ("name" in msg or "tool_name" in msg) + ): + msg_copy = dict(msg) + msg_copy.pop("name", None) + msg_copy.pop("tool_name", None) + sanitized[idx] = msg_copy return sanitized