File: history_embeddings_provider.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (266 lines) | stat: -rw-r--r-- 10,484 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "history_embeddings_provider.h"

#include <algorithm>
#include <optional>
#include <string>
#include <vector>

#include "base/check.h"
#include "base/functional/bind.h"
#include "base/i18n/time_formatting.h"
#include "base/strings/utf_string_conversions.h"
#include "components/history_clusters/core/history_clusters_util.h"
#include "components/history_embeddings/history_embeddings_features.h"
#include "components/history_embeddings/history_embeddings_service.h"
#include "components/omnibox/browser/autocomplete_enums.h"
#include "components/omnibox/browser/autocomplete_input.h"
#include "components/omnibox/browser/autocomplete_match.h"
#include "components/omnibox/browser/autocomplete_match_classification.h"
#include "components/omnibox/browser/autocomplete_provider.h"
#include "components/omnibox/browser/autocomplete_provider_client.h"
#include "components/omnibox/browser/keyword_provider.h"
#include "components/omnibox/browser/omnibox_triggered_feature_service.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"

namespace {
// The max relevance a history embedding match will receive.
constexpr int kMaxRelevance = 1000;

// Whether the received `status` is expected to be the last or there should be
// more updates..
bool IsAnswerDone(history_embeddings::ComputeAnswerStatus status) {
  switch (status) {
    case history_embeddings::ComputeAnswerStatus::kUnspecified:
    case history_embeddings::ComputeAnswerStatus::kLoading:
      return false;
    case history_embeddings::ComputeAnswerStatus::kSuccess:
    case history_embeddings::ComputeAnswerStatus::kUnanswerable:
    case history_embeddings::ComputeAnswerStatus::kModelUnavailable:
    case history_embeddings::ComputeAnswerStatus::kExecutionFailure:
    case history_embeddings::ComputeAnswerStatus::kExecutionCancelled:
    case history_embeddings::ComputeAnswerStatus::kFiltered:
      return true;
  }
}
}  // namespace

HistoryEmbeddingsProvider::HistoryEmbeddingsProvider(
    AutocompleteProviderClient* client,
    AutocompleteProviderListener* listener)
    : HistoryProvider(AutocompleteProvider::TYPE_HISTORY_EMBEDDINGS, client) {
  AddListener(listener);
}

HistoryEmbeddingsProvider::~HistoryEmbeddingsProvider() = default;

void HistoryEmbeddingsProvider::Start(const AutocompleteInput& input,
                                      bool minimal_changes) {
  done_ = true;
  matches_.clear();

  if (input.omit_asynchronous_matches())
    return;

  if (!client()->IsHistoryEmbeddingsEnabled()) {
    return;
  }

  // Remove the keyword from input if we're in keyword mode for a starter pack
  // engine.
  const auto [adjusted_input, starter_pack_engine] =
      AdjustInputForStarterPackKeyword(input,
                                       client()->GetTemplateURLService());
  input_ = adjusted_input;
  starter_pack_engine_ = starter_pack_engine;

  int num_terms =
      history_embeddings::CountWords(base::UTF16ToUTF8(input_.text()));
  if (num_terms < history_embeddings::GetFeatureParameters()
                      .search_query_minimum_word_count) {
    return;
  }

  history_embeddings::HistoryEmbeddingsService* service =
      client()->GetHistoryEmbeddingsService();
  CHECK(service);
  done_ = false;
  client()->GetOmniboxTriggeredFeatureService()->FeatureTriggered(
      metrics::OmniboxEventProto_Feature_HISTORY_EMBEDDINGS_FEATURE);
  service->Search(
      nullptr, base::UTF16ToUTF8(input_.text()), {}, provider_max_matches_,
      /*skip_answering=*/false,
      base::BindRepeating(&HistoryEmbeddingsProvider::OnReceivedSearchResult,
                          weak_factory_.GetWeakPtr()));
}

void HistoryEmbeddingsProvider::Stop(AutocompleteStopReason stop_reason) {
  // TODO(crbug.com/364303536): Ignore the stop timer since we know answers take
  //   longer than 1500ms to generate.
  if (stop_reason == AutocompleteStopReason::kInactivity) {
    return;
  }

  // Erase the abandoned placeholder answer.
  if (!done_) {
    size_t erased_count = std::erase_if(matches_, [&](const auto& match) {
      return match.type == AutocompleteMatchType::HISTORY_EMBEDDINGS_ANSWER;
    });
    CHECK_LE(erased_count, 1u);
    if (erased_count)
      NotifyListeners(!matches_.empty());
  }

  AutocompleteProvider::Stop(stop_reason);

  // TODO(b/333770460): Once `HistoryEmbeddingsService` has a stop API, we
  //   should call it here.
}

void HistoryEmbeddingsProvider::OnReceivedSearchResult(
    history_embeddings::SearchResult search_result) {
  // Check `done_` in case the stop timer fired or the user closed the omnibox
  // before `Search()` completed. Check `last_search_input_` in case this is the
  // result for an earlier `Search()` request; there's usually 2 requests
  // ongoing as the user types.
  if (done_ || search_result.query != base::UTF16ToUTF8(input_.text()))
    return;

  // `OnReceivedSearchResult()` can be called multiple times per `Search()`
  // request. Clear `matches_``to avoid aggregating duplicates.
  matches_.clear();

  if (search_result.scored_url_rows.empty())
    return;

  for (const history_embeddings::ScoredUrlRow& scored_url_row :
       search_result.scored_url_rows) {
    matches_.push_back(CreateMatch(scored_url_row));
  }

  bool answers_enabled =
      history_embeddings::GetFeatureParameters().answers_in_omnibox_scoped &&
      input_.InKeywordMode();
  if (answers_enabled) {
    auto optional_match = CreateAnswerMatch(
        search_result.answerer_result,
        search_result.scored_url_rows[search_result.AnswerIndex()],
        matches_[search_result.AnswerIndex()]);
    if (optional_match)
      matches_.push_back(optional_match.value());
  }

  done_ =
      !answers_enabled || IsAnswerDone(search_result.answerer_result.status);
  NotifyListeners(!matches_.empty());
}

AutocompleteMatch HistoryEmbeddingsProvider::CreateMatch(
    const history_embeddings::ScoredUrlRow& scored_url_row) {
  AutocompleteMatch match(
      this, std::min(scored_url_row.scored_url.score, 1.f) * kMaxRelevance,
      client()->AllowDeletingBrowserHistory(),
      AutocompleteMatchType::HISTORY_EMBEDDINGS);
  match.destination_url = scored_url_row.row.url();

  match.description =
      AutocompleteMatch::SanitizeString(scored_url_row.row.title());
  match.description_class = ClassifyTermMatches(
      FindTermMatches(input_.text(), match.description),
      match.description.size(), ACMatchClassification::MATCH,
      ACMatchClassification::NONE);

  match.contents = base::UTF8ToUTF16(scored_url_row.row.url().spec());
  match.contents_class = ClassifyTermMatches(
      FindTermMatches(input_.text(), match.contents), match.contents.size(),
      ACMatchClassification::MATCH | ACMatchClassification::URL,
      ACMatchClassification::URL);

  if (starter_pack_engine_) {
    match.keyword = starter_pack_engine_->keyword();
    match.transition = ui::PAGE_TRANSITION_KEYWORD;
  }

  match.RecordAdditionalInfo("passages", scored_url_row.GetBestPassage());

  return match;
}

std::optional<AutocompleteMatch> HistoryEmbeddingsProvider::CreateAnswerMatch(
    const history_embeddings::AnswererResult& answerer_result,
    const history_embeddings::ScoredUrlRow& scored_url_row,
    const AutocompleteMatch& match) {
  // If the match is outscored and not shown, then the answer shouldn't show
  // either.
  int score = std::max(match.relevance - 1, 1);

  switch (answerer_result.status) {
    case history_embeddings::ComputeAnswerStatus::kUnspecified:
    case history_embeddings::ComputeAnswerStatus::kUnanswerable:
    case history_embeddings::ComputeAnswerStatus::kFiltered:
    case history_embeddings::ComputeAnswerStatus::kExecutionCancelled:
    case history_embeddings::ComputeAnswerStatus::kModelUnavailable:
      return std::nullopt;

    case history_embeddings::ComputeAnswerStatus::kLoading: {
      AutocompleteMatch answer_match = CreateAnswerMatchHelper(
          score,
          l10n_util::GetStringUTF16(
              IDS_HISTORY_EMBEDDINGS_ANSWER_LOADING_HEADING),
          u"");
      answer_match.history_embeddings_answer_header_loading = true;
      return answer_match;
    }

    case history_embeddings::ComputeAnswerStatus::kSuccess: {
      AutocompleteMatch answer_match = CreateAnswerMatchHelper(
          score,
          l10n_util::GetStringUTF16(IDS_HISTORY_EMBEDDINGS_ANSWER_HEADING),
          AutocompleteMatch::SanitizeString(
              base::UTF8ToUTF16(answerer_result.answer.text())));
      answer_match.destination_url =
          GURL{"chrome://history/?q=" + answerer_result.query};
      std::u16string source = history_clusters::ComputeURLForDisplay(
          scored_url_row.row.url(), history_embeddings::GetFeatureParameters()
                                        .trim_after_host_in_results);
      answer_match.contents = AutocompleteMatch::SanitizeString(
          source + u"  •  " +
          l10n_util::GetStringFUTF16(
              IDS_HISTORY_EMBEDDINGS_ANSWER_SOURCE_VISIT_DATE_LABEL,
              base::TimeFormatShortDate(scored_url_row.row.last_visit())));
      answer_match.contents_class = {{0, ACMatchClassification::DIM}};
      return answer_match;
    }

    case history_embeddings::ComputeAnswerStatus::kExecutionFailure:
      return CreateAnswerMatchHelper(
          score,
          l10n_util::GetStringUTF16(IDS_HISTORY_EMBEDDINGS_ANSWER_HEADING),
          l10n_util::GetStringUTF16(
              IDS_HISTORY_EMBEDDINGS_ANSWERER_ERROR_TRY_AGAIN));
  }
}

AutocompleteMatch HistoryEmbeddingsProvider::CreateAnswerMatchHelper(
    int score,
    const std::u16string& history_embeddings_answer_header_text,
    const std::u16string& description) {
  AutocompleteMatch match(this, score, /*deletable=*/false,
                          AutocompleteMatchType::HISTORY_EMBEDDINGS_ANSWER);
  match.history_embeddings_answer_header_text =
      history_embeddings_answer_header_text;
  match.description = description;
  if (!description.empty())
    match.description_class = {{0, ACMatchClassification::NONE}};
  match.RecordAdditionalInfo("history_embeddings_answer_header_text",
                             history_embeddings_answer_header_text);
  if (starter_pack_engine_) {
    match.keyword = starter_pack_engine_->keyword();
    match.transition = ui::PAGE_TRANSITION_KEYWORD;
  }
  return match;
}