| | | 1 | | using System.Text.Json; |
| | | 2 | | |
| | | 3 | | using Microsoft.Extensions.AI; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr.Copilot; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// <see cref="AIFunction"/> that calls the Copilot MCP server's <c>web_search</c> tool. |
| | | 9 | | /// Returns a <see cref="WebSearchResult"/> containing the answer text, source |
| | | 10 | | /// citations, and the search queries that were performed. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <example> |
| | | 13 | | /// <code> |
| | | 14 | | /// var tools = CopilotToolSet.Create(new CopilotToolSetOptions { EnableWebSearch = true }); |
| | | 15 | | /// // Pass tools to an agent via IterativeLoopOptions.Tools |
| | | 16 | | /// </code> |
| | | 17 | | /// </example> |
| | | 18 | | public sealed class CopilotWebSearchFunction : AIFunction |
| | | 19 | | { |
| | | 20 | | private readonly CopilotMcpToolClient _mcpClient; |
| | | 21 | | |
| | 0 | 22 | | private static readonly JsonElement _schema = JsonDocument.Parse(""" |
| | 0 | 23 | | { |
| | 0 | 24 | | "type": "object", |
| | 0 | 25 | | "properties": { |
| | 0 | 26 | | "query": { |
| | 0 | 27 | | "type": "string", |
| | 0 | 28 | | "description": "A clear, specific question or prompt that requires up-to-date information from the w |
| | 0 | 29 | | } |
| | 0 | 30 | | }, |
| | 0 | 31 | | "required": ["query"] |
| | 0 | 32 | | } |
| | 0 | 33 | | """).RootElement.Clone(); |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Creates a new <see cref="CopilotWebSearchFunction"/> backed by the given MCP client. |
| | | 37 | | /// </summary> |
| | | 38 | | /// <param name="mcpClient">The MCP client used to call the Copilot web search endpoint.</param> |
| | 1 | 39 | | internal CopilotWebSearchFunction(CopilotMcpToolClient mcpClient) |
| | | 40 | | { |
| | 1 | 41 | | _mcpClient = mcpClient ?? throw new ArgumentNullException(nameof(mcpClient)); |
| | 1 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <inheritdoc /> |
| | 1 | 45 | | public override string Name => "web_search"; |
| | | 46 | | |
| | | 47 | | /// <inheritdoc /> |
| | | 48 | | public override string Description => |
| | 0 | 49 | | "Performs an AI-powered web search to provide intelligent, contextual answers with citations. " + |
| | 0 | 50 | | "Use when the query pertains to recent events, new developments, niche subjects, or when " + |
| | 0 | 51 | | "current factual information with verifiable sources is needed."; |
| | | 52 | | |
| | | 53 | | /// <inheritdoc /> |
| | 0 | 54 | | public override JsonElement JsonSchema => _schema; |
| | | 55 | | |
| | | 56 | | /// <inheritdoc /> |
| | | 57 | | protected override async ValueTask<object?> InvokeCoreAsync( |
| | | 58 | | AIFunctionArguments arguments, |
| | | 59 | | CancellationToken cancellationToken) |
| | | 60 | | { |
| | 0 | 61 | | var query = arguments.TryGetValue("query", out var queryValue) |
| | 0 | 62 | | ? queryValue?.ToString() |
| | 0 | 63 | | : null; |
| | | 64 | | |
| | 0 | 65 | | if (string.IsNullOrWhiteSpace(query)) |
| | | 66 | | { |
| | 0 | 67 | | return "Error: 'query' parameter is required."; |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | try |
| | | 71 | | { |
| | 0 | 72 | | var result = await _mcpClient.CallToolAsync( |
| | 0 | 73 | | "web_search", |
| | 0 | 74 | | new Dictionary<string, string> { ["query"] = query }, |
| | 0 | 75 | | "web_search", |
| | 0 | 76 | | cancellationToken).ConfigureAwait(false); |
| | | 77 | | |
| | 0 | 78 | | var searchResult = ParseSearchResult(result); |
| | 0 | 79 | | ThrowIfRateLimited(searchResult); |
| | 0 | 80 | | return searchResult; |
| | | 81 | | } |
| | 0 | 82 | | catch (CopilotRateLimitException) |
| | | 83 | | { |
| | 0 | 84 | | throw; |
| | | 85 | | } |
| | 0 | 86 | | catch (Exception ex) |
| | | 87 | | { |
| | 0 | 88 | | return $"Web search failed: {ex.Message}"; |
| | | 89 | | } |
| | 0 | 90 | | } |
| | | 91 | | |
| | | 92 | | internal static void ThrowIfRateLimited(WebSearchResult result) |
| | | 93 | | { |
| | 5 | 94 | | if (result.Text.StartsWith("Rate limit exceeded", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 95 | | result.Text.StartsWith("Too many requests", StringComparison.OrdinalIgnoreCase)) |
| | | 96 | | { |
| | | 97 | | // Only trigger for genuine rate-limit responses: these will have |
| | | 98 | | // no citations and no search queries. A real search result that |
| | | 99 | | // discusses rate limiting will have structured citation data. |
| | 3 | 100 | | if (result.Citations.Count == 0 && result.SearchQueries.Count == 0) |
| | | 101 | | { |
| | 3 | 102 | | var retryAfter = CopilotRateLimitException.ParseRetryAfterFromText(result.Text); |
| | 3 | 103 | | throw new CopilotRateLimitException( |
| | 3 | 104 | | $"Copilot web search rate limited: {result.Text}", |
| | 3 | 105 | | retryAfter); |
| | | 106 | | } |
| | | 107 | | } |
| | 2 | 108 | | } |
| | | 109 | | |
| | | 110 | | internal static WebSearchResult ParseSearchResult(string mcpResultText) |
| | | 111 | | { |
| | 16 | 112 | | string text = mcpResultText; |
| | 16 | 113 | | List<WebSearchCitation>? citations = null; |
| | 16 | 114 | | List<WebSearchQuery>? searchQueries = null; |
| | | 115 | | |
| | | 116 | | try |
| | | 117 | | { |
| | 16 | 118 | | using var doc = JsonDocument.Parse(mcpResultText); |
| | 12 | 119 | | var root = doc.RootElement; |
| | | 120 | | |
| | | 121 | | // Extract the answer text from text.value (preferred) or text as a |
| | | 122 | | // direct string (fallback). |
| | 12 | 123 | | if (root.TryGetProperty("text", out var textObj)) |
| | | 124 | | { |
| | 12 | 125 | | if (textObj.ValueKind == JsonValueKind.Object && |
| | 12 | 126 | | textObj.TryGetProperty("value", out var valueElement)) |
| | | 127 | | { |
| | 11 | 128 | | text = valueElement.GetString() ?? mcpResultText; |
| | | 129 | | |
| | | 130 | | // Parse text.annotations (citation data) |
| | 11 | 131 | | citations = ParseCitations(textObj); |
| | | 132 | | } |
| | 1 | 133 | | else if (textObj.ValueKind == JsonValueKind.String) |
| | | 134 | | { |
| | 1 | 135 | | text = textObj.GetString() ?? mcpResultText; |
| | | 136 | | } |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | // Fall back to root-level annotations if text.annotations was |
| | | 140 | | // absent or empty, in case the API shape evolves. |
| | 12 | 141 | | if ((citations is null || citations.Count == 0) && |
| | 12 | 142 | | root.TryGetProperty("annotations", out var rootAnnotations)) |
| | | 143 | | { |
| | 2 | 144 | | citations = ParseCitations(rootAnnotations); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | // Parse bing_searches |
| | 12 | 148 | | if (root.TryGetProperty("bing_searches", out var bingSearches) && |
| | 12 | 149 | | bingSearches.ValueKind == JsonValueKind.Array) |
| | | 150 | | { |
| | 4 | 151 | | searchQueries = ParseSearchQueries(bingSearches); |
| | | 152 | | } |
| | 12 | 153 | | } |
| | 4 | 154 | | catch (JsonException) |
| | | 155 | | { |
| | | 156 | | // Best-effort: return whatever we have so far. |
| | 4 | 157 | | } |
| | | 158 | | |
| | 16 | 159 | | return new WebSearchResult( |
| | 16 | 160 | | text, |
| | 16 | 161 | | citations?.AsReadOnly() ?? (IReadOnlyList<WebSearchCitation>)Array.Empty<WebSearchCitation>(), |
| | 16 | 162 | | searchQueries?.AsReadOnly() ?? (IReadOnlyList<WebSearchQuery>)Array.Empty<WebSearchQuery>()); |
| | | 163 | | } |
| | | 164 | | |
| | | 165 | | private static List<WebSearchCitation>? ParseCitations(JsonElement parent) |
| | | 166 | | { |
| | | 167 | | JsonElement annotations; |
| | 13 | 168 | | if (parent.ValueKind == JsonValueKind.Object) |
| | | 169 | | { |
| | 11 | 170 | | if (!parent.TryGetProperty("annotations", out annotations)) |
| | | 171 | | { |
| | 4 | 172 | | return null; |
| | | 173 | | } |
| | | 174 | | } |
| | 2 | 175 | | else if (parent.ValueKind == JsonValueKind.Array) |
| | | 176 | | { |
| | 1 | 177 | | annotations = parent; |
| | | 178 | | } |
| | | 179 | | else |
| | | 180 | | { |
| | 1 | 181 | | return null; |
| | | 182 | | } |
| | | 183 | | |
| | 8 | 184 | | if (annotations.ValueKind != JsonValueKind.Array) |
| | | 185 | | { |
| | 1 | 186 | | return null; |
| | | 187 | | } |
| | | 188 | | |
| | 7 | 189 | | var citations = new List<WebSearchCitation>(); |
| | 32 | 190 | | foreach (var ann in annotations.EnumerateArray()) |
| | | 191 | | { |
| | | 192 | | try |
| | | 193 | | { |
| | 9 | 194 | | if (!ann.TryGetProperty("url_citation", out var urlCitation)) |
| | | 195 | | { |
| | 1 | 196 | | continue; |
| | | 197 | | } |
| | | 198 | | |
| | 8 | 199 | | var title = urlCitation.TryGetProperty("title", out var t) |
| | 8 | 200 | | ? t.GetString() ?? "" |
| | 8 | 201 | | : ""; |
| | 8 | 202 | | var url = urlCitation.TryGetProperty("url", out var u) |
| | 8 | 203 | | ? u.GetString() ?? "" |
| | 8 | 204 | | : ""; |
| | 8 | 205 | | var startIndex = ann.TryGetProperty("start_index", out var si) |
| | 8 | 206 | | && si.ValueKind == JsonValueKind.Number |
| | 8 | 207 | | && si.TryGetInt32(out var siVal) |
| | 8 | 208 | | ? siVal |
| | 8 | 209 | | : 0; |
| | 8 | 210 | | var endIndex = ann.TryGetProperty("end_index", out var ei) |
| | 8 | 211 | | && ei.ValueKind == JsonValueKind.Number |
| | 8 | 212 | | && ei.TryGetInt32(out var eiVal) |
| | 8 | 213 | | ? eiVal |
| | 8 | 214 | | : 0; |
| | | 215 | | |
| | 8 | 216 | | citations.Add(new WebSearchCitation(title, url, startIndex, endIndex)); |
| | 8 | 217 | | } |
| | 0 | 218 | | catch (Exception ex) when (ex is JsonException or InvalidOperationException) |
| | | 219 | | { |
| | | 220 | | // Skip malformed individual citations. |
| | 0 | 221 | | } |
| | | 222 | | } |
| | | 223 | | |
| | 7 | 224 | | return citations; |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | private static List<WebSearchQuery>? ParseSearchQueries(JsonElement bingSearches) |
| | | 228 | | { |
| | 4 | 229 | | if (bingSearches.ValueKind != JsonValueKind.Array) |
| | | 230 | | { |
| | 0 | 231 | | return null; |
| | | 232 | | } |
| | | 233 | | |
| | 4 | 234 | | var queries = new List<WebSearchQuery>(); |
| | 18 | 235 | | foreach (var item in bingSearches.EnumerateArray()) |
| | | 236 | | { |
| | | 237 | | try |
| | | 238 | | { |
| | 5 | 239 | | var queryText = item.TryGetProperty("text", out var t) |
| | 5 | 240 | | ? t.GetString() ?? "" |
| | 5 | 241 | | : ""; |
| | 5 | 242 | | var url = item.TryGetProperty("url", out var u) |
| | 5 | 243 | | ? u.GetString() ?? "" |
| | 5 | 244 | | : ""; |
| | | 245 | | |
| | 5 | 246 | | queries.Add(new WebSearchQuery(queryText, url)); |
| | 5 | 247 | | } |
| | 0 | 248 | | catch (JsonException) |
| | | 249 | | { |
| | | 250 | | // Skip malformed individual search entries. |
| | 0 | 251 | | } |
| | | 252 | | } |
| | | 253 | | |
| | 4 | 254 | | return queries; |
| | | 255 | | } |
| | | 256 | | } |