forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBingTextSearch.cs
More file actions
289 lines (245 loc) · 13.8 KB
/
BingTextSearch.cs
File metadata and controls
289 lines (245 loc) · 13.8 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel.Data;
using Microsoft.SemanticKernel.Http;
namespace Microsoft.SemanticKernel.Plugins.Web.Bing;
/// <summary>
/// A Bing Text Search implementation that can be used to perform searches using the Bing Web Search API.
/// </summary>
#pragma warning disable CS0618 // ITextSearch is obsolete - this class provides backward compatibility
public sealed class BingTextSearch : ITextSearch
#pragma warning restore CS0618
{
/// <summary>
/// Create an instance of the <see cref="BingTextSearch"/> with API key authentication.
/// </summary>
/// <param name="apiKey">The API key credential used to authenticate requests against the Search service.</param>
/// <param name="options">Options used when creating this instance of <see cref="BingTextSearch"/>.</param>
public BingTextSearch(string apiKey, BingTextSearchOptions? options = null)
{
Verify.NotNullOrWhiteSpace(apiKey);
this._apiKey = apiKey;
this._uri = options?.Endpoint ?? new Uri(DefaultUri);
this._logger = options?.LoggerFactory?.CreateLogger(typeof(BingTextSearch)) ?? NullLogger.Instance;
this._httpClient = options?.HttpClient ?? HttpClientProvider.GetHttpClient();
this._httpClient.DefaultRequestHeaders.Add("User-Agent", HttpHeaderConstant.Values.UserAgent);
this._httpClient.DefaultRequestHeaders.Add(HttpHeaderConstant.Names.SemanticKernelVersion, HttpHeaderConstant.Values.GetAssemblyVersion(typeof(BingTextSearch)));
this._stringMapper = options?.StringMapper ?? s_defaultStringMapper;
this._resultMapper = options?.ResultMapper ?? s_defaultResultMapper;
}
/// <inheritdoc/>
public async Task<KernelSearchResults<string>> SearchAsync(string query, TextSearchOptions? searchOptions = null, CancellationToken cancellationToken = default)
{
searchOptions ??= new TextSearchOptions();
BingSearchResponse<BingWebPage>? searchResponse = await this.ExecuteSearchAsync(query, searchOptions, cancellationToken).ConfigureAwait(false);
long? totalCount = searchOptions.IncludeTotalCount ? searchResponse?.WebPages?.TotalEstimatedMatches : null;
return new KernelSearchResults<string>(this.GetResultsAsStringAsync(searchResponse, cancellationToken), totalCount, GetResultsMetadata(searchResponse));
}
/// <inheritdoc/>
public async Task<KernelSearchResults<TextSearchResult>> GetTextSearchResultsAsync(string query, TextSearchOptions? searchOptions = null, CancellationToken cancellationToken = default)
{
searchOptions ??= new TextSearchOptions();
BingSearchResponse<BingWebPage>? searchResponse = await this.ExecuteSearchAsync(query, searchOptions, cancellationToken).ConfigureAwait(false);
long? totalCount = searchOptions.IncludeTotalCount ? searchResponse?.WebPages?.TotalEstimatedMatches : null;
return new KernelSearchResults<TextSearchResult>(this.GetResultsAsTextSearchResultAsync(searchResponse, cancellationToken), totalCount, GetResultsMetadata(searchResponse));
}
/// <inheritdoc/>
public async Task<KernelSearchResults<object>> GetSearchResultsAsync(string query, TextSearchOptions? searchOptions = null, CancellationToken cancellationToken = default)
{
searchOptions ??= new TextSearchOptions();
BingSearchResponse<BingWebPage>? searchResponse = await this.ExecuteSearchAsync(query, searchOptions, cancellationToken).ConfigureAwait(false);
long? totalCount = searchOptions.IncludeTotalCount ? searchResponse?.WebPages?.TotalEstimatedMatches : null;
return new KernelSearchResults<object>(this.GetResultsAsWebPageAsync(searchResponse, cancellationToken), totalCount, GetResultsMetadata(searchResponse));
}
#region private
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly string? _apiKey;
private readonly Uri? _uri = null;
private readonly ITextSearchStringMapper _stringMapper;
private readonly ITextSearchResultMapper _resultMapper;
private static readonly ITextSearchStringMapper s_defaultStringMapper = new DefaultTextSearchStringMapper();
private static readonly ITextSearchResultMapper s_defaultResultMapper = new DefaultTextSearchResultMapper();
// See https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/reference/query-parameters
private static readonly string[] s_queryParameters = ["answerCount", "cc", "freshness", "mkt", "promote", "responseFilter", "safeSearch", "setLang", "textDecorations", "textFormat"];
private static readonly string[] s_advancedSearchKeywords = ["contains", "ext", "filetype", "inanchor", "inbody", "intitle", "ip", "language", "loc", "location", "prefer", "site", "feed", "hasfeed", "url"];
private const string DefaultUri = "https://api.bing.microsoft.com/v7.0/search";
/// <summary>
/// Execute a Bing search query and return the results.
/// </summary>
/// <param name="query">What to search for.</param>
/// <param name="searchOptions">Search options.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
private async Task<BingSearchResponse<BingWebPage>?> ExecuteSearchAsync(string query, TextSearchOptions searchOptions, CancellationToken cancellationToken = default)
{
using HttpResponseMessage response = await this.SendGetRequestAsync(query, searchOptions, cancellationToken).ConfigureAwait(false);
this._logger.LogDebug("Response received: {StatusCode}", response.StatusCode);
string json = await response.Content.ReadAsStringWithExceptionMappingAsync(cancellationToken).ConfigureAwait(false);
// Sensitive data, logging as trace, disabled by default
this._logger.LogTrace("Response content received: {Data}", json);
return JsonSerializer.Deserialize<BingSearchResponse<BingWebPage>>(json);
}
/// <summary>
/// Sends a GET request to the specified URI.
/// </summary>
/// <param name="query">The query string.</param>
/// <param name="searchOptions">The search options.</param>
/// <param name="cancellationToken">A cancellation token to cancel the request.</param>
/// <returns>A <see cref="HttpResponseMessage"/> representing the response from the request.</returns>
private async Task<HttpResponseMessage> SendGetRequestAsync(string query, TextSearchOptions searchOptions, CancellationToken cancellationToken = default)
{
if (searchOptions.Top is <= 0 or > 50)
{
throw new ArgumentOutOfRangeException(nameof(searchOptions), searchOptions, $"{nameof(searchOptions)} count value must be greater than 0 and have a maximum value of 50.");
}
Uri uri = new($"{this._uri}?q={BuildQuery(query, searchOptions)}");
using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
if (!string.IsNullOrEmpty(this._apiKey))
{
httpRequestMessage.Headers.Add("Ocp-Apim-Subscription-Key", this._apiKey);
}
return await this._httpClient.SendWithSuccessCheckAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return the search results as instances of <see cref="BingWebPage"/>.
/// </summary>
/// <param name="searchResponse">Response containing the web pages matching the query.</param>
/// <param name="cancellationToken">Cancellation token</param>
private async IAsyncEnumerable<object> GetResultsAsWebPageAsync(BingSearchResponse<BingWebPage>? searchResponse, [EnumeratorCancellation] CancellationToken cancellationToken)
{
if (searchResponse is null || searchResponse.WebPages is null || searchResponse.WebPages.Value is null)
{
yield break;
}
foreach (var webPage in searchResponse.WebPages.Value)
{
yield return webPage;
await Task.Yield();
}
}
/// <summary>
/// Return the search results as instances of <see cref="TextSearchResult"/>.
/// </summary>
/// <param name="searchResponse">Response containing the web pages matching the query.</param>
/// <param name="cancellationToken">Cancellation token</param>
private async IAsyncEnumerable<TextSearchResult> GetResultsAsTextSearchResultAsync(BingSearchResponse<BingWebPage>? searchResponse, [EnumeratorCancellation] CancellationToken cancellationToken)
{
if (searchResponse is null || searchResponse.WebPages is null || searchResponse.WebPages.Value is null)
{
yield break;
}
foreach (var webPage in searchResponse.WebPages.Value)
{
yield return this._resultMapper.MapFromResultToTextSearchResult(webPage);
await Task.Yield();
}
}
/// <summary>
/// Return the search results as instances of <see cref="TextSearchResult"/>.
/// </summary>
/// <param name="searchResponse">Response containing the web pages matching the query.</param>
/// <param name="cancellationToken">Cancellation token</param>
private async IAsyncEnumerable<string> GetResultsAsStringAsync(BingSearchResponse<BingWebPage>? searchResponse, [EnumeratorCancellation] CancellationToken cancellationToken)
{
if (searchResponse is null || searchResponse.WebPages is null || searchResponse.WebPages.Value is null)
{
yield break;
}
foreach (var webPage in searchResponse.WebPages.Value)
{
yield return this._stringMapper.MapFromResultToString(webPage);
await Task.Yield();
}
}
/// <summary>
/// Return the results metadata.
/// </summary>
/// <param name="searchResponse">Response containing the documents matching the query.</param>
private static Dictionary<string, object?>? GetResultsMetadata(BingSearchResponse<BingWebPage>? searchResponse)
{
return new Dictionary<string, object?>()
{
{ "AlteredQuery", searchResponse?.QueryContext?.AlteredQuery },
};
}
/// <summary>
/// Default implementation which maps from a <see cref="BingWebPage"/> to a <see cref="string"/>
/// </summary>
private sealed class DefaultTextSearchStringMapper : ITextSearchStringMapper
{
/// <inheritdoc />
public string MapFromResultToString(object result)
{
if (result is not BingWebPage webPage)
{
throw new ArgumentException("Result must be a BingWebPage", nameof(result));
}
return webPage.Snippet ?? string.Empty;
}
}
/// <summary>
/// Default implementation which maps from a <see cref="BingWebPage"/> to a <see cref="TextSearchResult"/>
/// </summary>
private sealed class DefaultTextSearchResultMapper : ITextSearchResultMapper
{
/// <inheritdoc />
public TextSearchResult MapFromResultToTextSearchResult(object result)
{
if (result is not BingWebPage webPage)
{
throw new ArgumentException("Result must be a BingWebPage", nameof(result));
}
return new TextSearchResult(webPage.Snippet ?? string.Empty) { Name = webPage.Name, Link = webPage.Url };
}
}
#pragma warning disable CS0618 // FilterClause is obsolete
/// <summary>
/// Build a query string from the <see cref="TextSearchOptions"/>
/// </summary>
/// <param name="query">The query.</param>
/// <param name="searchOptions">The search options.</param>
private static string BuildQuery(string query, TextSearchOptions searchOptions)
{
StringBuilder fullQuery = new();
fullQuery.Append(Uri.EscapeDataString(query.Trim()));
StringBuilder queryParams = new();
if (searchOptions.Filter is not null)
{
var filterClauses = searchOptions.Filter.FilterClauses;
foreach (var filterClause in filterClauses)
{
if (filterClause is EqualToFilterClause equalityFilterClause)
{
if (s_advancedSearchKeywords.Contains(equalityFilterClause.FieldName, StringComparer.OrdinalIgnoreCase) && equalityFilterClause.Value is not null)
{
fullQuery.Append($"+{equalityFilterClause.FieldName}%3A").Append(Uri.EscapeDataString(equalityFilterClause.Value.ToString()!));
}
else if (s_queryParameters.Contains(equalityFilterClause.FieldName, StringComparer.OrdinalIgnoreCase) && equalityFilterClause.Value is not null)
{
string? queryParam = s_queryParameters.FirstOrDefault(s => s.Equals(equalityFilterClause.FieldName, StringComparison.OrdinalIgnoreCase));
queryParams.Append('&').Append(queryParam!).Append('=').Append(Uri.EscapeDataString(equalityFilterClause.Value.ToString()!));
}
else
{
throw new ArgumentException($"Unknown equality filter clause field name '{equalityFilterClause.FieldName}', must be one of {string.Join(",", s_queryParameters)},{string.Join(",", s_advancedSearchKeywords)}", nameof(searchOptions));
}
}
}
}
fullQuery.Append($"&count={searchOptions.Top}&offset={searchOptions.Skip}{queryParams}");
return fullQuery.ToString();
}
#pragma warning restore CS0618 // FilterClause is obsolete
#endregion
}