fix: truncate context logic

This commit is contained in:
2026-09-30 15:01:28 +02:00
parent a59e4286ad
commit 5fc6fda804
15 changed files with 238 additions and 126 deletions
+18 -17
View File
@@ -112,10 +112,12 @@ void WebFetchTool::completeJob(Job* job, QJsonObject result) {
void WebFetchTool::execute(
const QString& toolCallId,
const QJsonObject& args,
int outputBudgetChars,
std::function<void(const QJsonObject&)> done) {
auto* job = new Job;
job->done = std::move(done);
job->toolCallId = toolCallId;
job->budgetChars = outputBudgetChars;
m_jobs.append(job);
auto fail = [this, job](const QString& message) {
@@ -248,23 +250,24 @@ void WebFetchTool::execute(
const QString savedPath = saveToFile(*job, content, mime);
QString output = content;
const int budget = inlineBudgetChars();
int budget = inlineBudgetChars();
if (job->budgetChars > 0) budget = qMin(budget, job->budgetChars);
if (content.size() > budget) {
output = content.left(budget);
const QString note = QStringLiteral(
"\n\n[... truncated: showing %1 of %2 characters")
.arg(budget)
.arg(content.size());
const QString note =
QStringLiteral(
"\n\n[... truncated: showing %1 of %2 characters")
.arg(budget)
.arg(content.size());
if (!savedPath.isEmpty())
output += note +
QStringLiteral(
". The full content is saved to %1; use "
"the readfile tool to read the rest.")
.arg(savedPath);
output += note + QStringLiteral(
". The full content is saved to %1; use "
"the readfile tool to read the rest.")
.arg(savedPath);
else
output += note + QStringLiteral(
". The remaining content is not "
"available.");
". The remaining content is not "
"available.");
}
completeJob(job, makeOutput(output));
});
@@ -273,14 +276,13 @@ void WebFetchTool::execute(
QString WebFetchTool::saveToFile(
const Job& job, const QString& content, const QString& mime) const {
QDir dir(StoragePath);
if (!dir.exists() && !dir.mkpath(QStringLiteral(".")))
return QString();
if (!dir.exists() && !dir.mkpath(QStringLiteral("."))) return QString();
QString fileName;
fileName.reserve(job.toolCallId.size());
for (const QChar& c : job.toolCallId)
fileName += (c.isLetterOrNumber() || c == QLatin1Char('-') ||
c == QLatin1Char('_'))
c == QLatin1Char('_'))
? c
: QLatin1Char('_');
if (fileName.isEmpty()) fileName = QStringLiteral("fetch");
@@ -293,8 +295,7 @@ QString WebFetchTool::saveToFile(
else if (mime.contains(QLatin1String("xml")))
extension = QStringLiteral("xml");
const QString path =
dir.filePath(fileName + QLatin1Char('.') + extension);
const QString path = dir.filePath(fileName + QLatin1Char('.') + extension);
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
return QString();