addQueryChunk method

Future<void> addQueryChunk(
  1. Message message, [
  2. bool noTool = false
])

Implementation

Future<void> addQueryChunk(Message message, [bool noTool = false]) async {
  var messageToSend = message;

  // Only add tools prompt for the first user text message (not a tool response)
  // and only if the model supports function calls.
  // Gemma 4 is exempt: SDK renders <|tool>declaration:...<tool|> from
  // tools_json passed at conversation creation, so a Dart-side prompt
  // injection would double-wrap the tools.
  if (message.isUser &&
      message.type == MessageType.text &&
      !_toolsInstructionSent &&
      tools.isNotEmpty &&
      !noTool &&
      supportsFunctionCalls &&
      toolChoice != ToolChoice.none &&
      modelType != ModelType.gemma4) {
    _toolsInstructionSent = true;
    final toolsPrompt = createToolsPrompt();

    // For FunctionGemma, manually construct the full prompt with turn markers
    // because tools prompt already has developer turn markers
    if (modelType == ModelType.functionGemma) {
      final newText =
          '$toolsPrompt$startTurn$userPrefix\n${messageToSend.text}\n$endTurn\n$startTurn$modelPrefix\n';
      messageToSend = messageToSend.copyWith(text: newText);
    } else {
      final newText = '$toolsPrompt\n${messageToSend.text}';
      messageToSend = messageToSend.copyWith(text: newText);
    }
  } else if (!supportsFunctionCalls && tools.isNotEmpty && !noTool) {
    // Log warning if model doesn't support function calls but tools are provided
    debugPrint(
        'WARNING: Model does not support function calls, but tools were provided. Tools will be ignored.');
  }

  // Qwen3: append /no_think to suppress thinking at model level when not requested
  if (!isThinking && modelType == ModelType.qwen3 && message.isUser) {
    messageToSend =
        messageToSend.copyWith(text: '${messageToSend.text} /no_think');
  }

  // --- DETAILED LOGGING ---
  final historyForLogging = _modelHistory.map((m) => m.text).join('\n');
  debugPrint('--- Sending to Native ---');
  debugPrint('History:\n$historyForLogging');
  debugPrint('Current Message:\n${messageToSend.text}');
  debugPrint('-------------------------');
  // --- END LOGGING ---

  await session.addQueryChunk(messageToSend);

  // Store original message in _modelHistory (not messageToSend) so that
  // _recreateSessionWithReducedChunks replay does not double-apply transformations
  // (e.g. systemInstruction prepend, tools prompt) when the session is recreated.
  _fullHistory.add(messageToSend);
  _modelHistory.add(message);
}