addQueryChunk method

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

Implementation

Future<void> addQueryChunk(Message message, [bool noTool = false, bool prefix = 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();

    // Create tools prompt message for both storage and session
    final toolsPromptMessage = Message(
      text: toolsPrompt,
      isUser: true,
    );

    // Send to session
    await session.addQueryChunk(toolsPromptMessage);

    // Store in _prefixes for replay
    _prefixes.add(toolsPromptMessage);
  } 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 message in history
  _fullHistory.add(messageToSend);
  // If this is a prefix message, add to _prefixes
  if (prefix) {
    _prefixes.add(message);
  } else {
    _modelHistory.add(message);
  }

  if (message.hasImage) {
    _currentTokens += 257;
  }
}