* @brief Handles end-of-stream: either continue with tool results or end the turn. */
| 895 | * @brief Handles end-of-stream: either continue with tool results or end the turn. |
| 896 | */ |
| 897 | void AI::Conversation::onReplyFinished() |
| 898 | { |
| 899 | m_streamFlushTimer->stop(); |
| 900 | if (m_streamDirty) |
| 901 | flushPendingStreamUpdate(); |
| 902 | |
| 903 | if (m_cancelled) { |
| 904 | teardownReply(); |
| 905 | setBusy(false); |
| 906 | return; |
| 907 | } |
| 908 | |
| 909 | if (!m_assistantText.isEmpty() || !m_pendingToolUseBlocks.isEmpty()) { |
| 910 | QJsonArray content; |
| 911 | for (const auto& tb : m_pendingThinkingBlocks) |
| 912 | content.append(tb); |
| 913 | |
| 914 | if (!m_assistantText.isEmpty()) { |
| 915 | QJsonObject text; |
| 916 | text[QStringLiteral("type")] = QStringLiteral("text"); |
| 917 | text[QStringLiteral("text")] = m_assistantText; |
| 918 | content.append(text); |
| 919 | } |
| 920 | for (const auto& tu : m_pendingToolUseBlocks) |
| 921 | content.append(tu); |
| 922 | |
| 923 | QJsonObject assistant; |
| 924 | assistant[QStringLiteral("role")] = QStringLiteral("assistant"); |
| 925 | assistant[QStringLiteral("content")] = content; |
| 926 | m_history.append(assistant); |
| 927 | } |
| 928 | |
| 929 | if (m_assistantIndex >= 0 && m_assistantIndex < m_uiMessages.size()) { |
| 930 | auto map = m_uiMessages.at(m_assistantIndex).toMap(); |
| 931 | map.insert(QStringLiteral("streaming"), false); |
| 932 | |
| 933 | const auto finalText = map.value(QStringLiteral("text")).toString(); |
| 934 | map.insert(QStringLiteral("text"), rewriteHelpLinks(finalText)); |
| 935 | |
| 936 | const auto rowText = map.value(QStringLiteral("text")).toString(); |
| 937 | const auto rowCalls = map.value(QStringLiteral("toolCalls")).toList(); |
| 938 | if (rowText.isEmpty() && rowCalls.isEmpty()) { |
| 939 | map.insert(QStringLiteral("text"), |
| 940 | tr("(The model returned an empty response. Try " |
| 941 | "rephrasing, switching to a different model, or " |
| 942 | "checking that the request is allowed by the " |
| 943 | "provider's safety filters.)")); |
| 944 | } |
| 945 | |
| 946 | m_uiMessages[m_assistantIndex] = map; |
| 947 | Q_EMIT messagesChanged(); |
| 948 | } |
| 949 | |
| 950 | m_pendingThinkingBlocks = QJsonArray(); |
| 951 | m_pendingToolUseBlocks = QJsonArray(); |
| 952 | m_assistantText.clear(); |
| 953 | m_assistantThinking.clear(); |
| 954 | m_assistantIndex = -1; |