| | | 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> |
| | 3 | 39 | | internal CopilotWebSearchFunction(CopilotMcpToolClient mcpClient) |
| | | 40 | | { |
| | 3 | 41 | | _mcpClient = mcpClient ?? throw new ArgumentNullException(nameof(mcpClient)); |
| | 3 | 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 | | { |
| | 2 | 61 | | var query = arguments.TryGetValue("query", out var queryValue) |
| | 2 | 62 | | ? queryValue?.ToString() |
| | 2 | 63 | | : null; |
| | | 64 | | |
| | 2 | 65 | | if (string.IsNullOrWhiteSpace(query)) |
| | | 66 | | { |
| | 0 | 67 | | return "Error: 'query' parameter is required."; |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | try |
| | | 71 | | { |
| | 2 | 72 | | var result = await _mcpClient.CallToolAsync( |
| | 2 | 73 | | "web_search", |
| | 2 | 74 | | new Dictionary<string, string> { ["query"] = query }, |
| | 2 | 75 | | "web_search", |
| | 2 | 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 | | } |
| | 2 | 86 | | catch (CopilotAuthException) |
| | | 87 | | { |
| | 2 | 88 | | throw; |
| | | 89 | | } |
| | 0 | 90 | | catch (Exception ex) |
| | | 91 | | { |
| | 0 | 92 | | return $"Web search failed: {ex.Message}"; |
| | | 93 | | } |
| | 0 | 94 | | } |
| | | 95 | | |
| | | 96 | | internal static void ThrowIfRateLimited(WebSearchResult result) |
| | | 97 | | { |
| | 5 | 98 | | if (result.Text.StartsWith("Rate limit exceeded", StringComparison.OrdinalIgnoreCase) || |
| | 5 | 99 | | result.Text.StartsWith("Too many requests", StringComparison.OrdinalIgnoreCase)) |
| | | 100 | | { |
| | | 101 | | // Only trigger for genuine rate-limit responses: these will have |
| | | 102 | | // no citations and no search queries. A real search result that |
| | | 103 | | // discusses rate limiting will have structured citation data. |
| | 3 | 104 | | if (result.Citations.Count == 0 && result.SearchQueries.Count == 0) |
| | | 105 | | { |
| | 3 | 106 | | var retryAfter = CopilotRateLimitException.ParseRetryAfterFromText(result.Text); |
| | 3 | 107 | | throw new CopilotRateLimitException( |
| | 3 | 108 | | $"Copilot web search rate limited: {result.Text}", |
| | 3 | 109 | | retryAfter); |
| | | 110 | | } |
| | | 111 | | } |
| | 2 | 112 | | } |
| | | 113 | | |
| | | 114 | | internal static WebSearchResult ParseSearchResult(string mcpResultText) |
| | | 115 | | { |
| | 16 | 116 | | string text = mcpResultText; |
| | 16 | 117 | | List<WebSearchCitation>? citations = null; |
| | 16 | 118 | | List<WebSearchQuery>? searchQueries = null; |
| | | 119 | | |
| | | 120 | | try |
| | | 121 | | { |
| | 16 | 122 | | using var doc = JsonDocument.Parse(mcpResultText); |
| | 12 | 123 | | var root = doc.RootElement; |
| | | 124 | | |
| | | 125 | | // Extract the answer text from text.value (preferred) or text as a |
| | | 126 | | // direct string (fallback). |
| | 12 | 127 | | if (root.TryGetProperty("text", out var textObj)) |
| | | 128 | | { |
| | 12 | 129 | | if (textObj.ValueKind == JsonValueKind.Object && |
| | 12 | 130 | | textObj.TryGetProperty("value", out var valueElement)) |
| | | 131 | | { |
| | 11 | 132 | | text = valueElement.GetString() ?? mcpResultText; |
| | | 133 | | |
| | | 134 | | // Parse text.annotations (citation data) |
| | 11 | 135 | | citations = ParseCitations(textObj); |
| | | 136 | | } |
| | 1 | 137 | | else if (textObj.ValueKind == JsonValueKind.String) |
| | | 138 | | { |
| | 1 | 139 | | text = textObj.GetString() ?? mcpResultText; |
| | | 140 | | } |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | // Fall back to root-level annotations if text.annotations was |
| | | 144 | | // absent or empty, in case the API shape evolves. |
| | 12 | 145 | | if ((citations is null || citations.Count == 0) && |
| | 12 | 146 | | root.TryGetProperty("annotations", out var rootAnnotations)) |
| | | 147 | | { |
| | 2 | 148 | | citations = ParseCitations(rootAnnotations); |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | // Parse bing_searches |
| | 12 | 152 | | if (root.TryGetProperty("bing_searches", out var bingSearches) && |
| | 12 | 153 | | bingSearches.ValueKind == JsonValueKind.Array) |
| | | 154 | | { |
| | 4 | 155 | | searchQueries = ParseSearchQueries(bingSearches); |
| | | 156 | | } |
| | 12 | 157 | | } |
| | 4 | 158 | | catch (JsonException) |
| | | 159 | | { |
| | | 160 | | // Best-effort: return whatever we have so far. |
| | 4 | 161 | | } |
| | | 162 | | |
| | 16 | 163 | | return new WebSearchResult( |
| | 16 | 164 | | text, |
| | 16 | 165 | | citations?.AsReadOnly() ?? (IReadOnlyList<WebSearchCitation>)Array.Empty<WebSearchCitation>(), |
| | 16 | 166 | | searchQueries?.AsReadOnly() ?? (IReadOnlyList<WebSearchQuery>)Array.Empty<WebSearchQuery>()); |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private static List<WebSearchCitation>? ParseCitations(JsonElement parent) |
| | | 170 | | { |
| | | 171 | | JsonElement annotations; |
| | 13 | 172 | | if (parent.ValueKind == JsonValueKind.Object) |
| | | 173 | | { |
| | 11 | 174 | | if (!parent.TryGetProperty("annotations", out annotations)) |
| | | 175 | | { |
| | 4 | 176 | | return null; |
| | | 177 | | } |
| | | 178 | | } |
| | 2 | 179 | | else if (parent.ValueKind == JsonValueKind.Array) |
| | | 180 | | { |
| | 1 | 181 | | annotations = parent; |
| | | 182 | | } |
| | | 183 | | else |
| | | 184 | | { |
| | 1 | 185 | | return null; |
| | | 186 | | } |
| | | 187 | | |
| | 8 | 188 | | if (annotations.ValueKind != JsonValueKind.Array) |
| | | 189 | | { |
| | 1 | 190 | | return null; |
| | | 191 | | } |
| | | 192 | | |
| | 7 | 193 | | var citations = new List<WebSearchCitation>(); |
| | 32 | 194 | | foreach (var ann in annotations.EnumerateArray()) |
| | | 195 | | { |
| | | 196 | | try |
| | | 197 | | { |
| | 9 | 198 | | if (!ann.TryGetProperty("url_citation", out var urlCitation)) |
| | | 199 | | { |
| | 1 | 200 | | continue; |
| | | 201 | | } |
| | | 202 | | |
| | 8 | 203 | | var title = urlCitation.TryGetProperty("title", out var t) |
| | 8 | 204 | | ? t.GetString() ?? "" |
| | 8 | 205 | | : ""; |
| | 8 | 206 | | var url = urlCitation.TryGetProperty("url", out var u) |
| | 8 | 207 | | ? u.GetString() ?? "" |
| | 8 | 208 | | : ""; |
| | 8 | 209 | | var startIndex = ann.TryGetProperty("start_index", out var si) |
| | 8 | 210 | | && si.ValueKind == JsonValueKind.Number |
| | 8 | 211 | | && si.TryGetInt32(out var siVal) |
| | 8 | 212 | | ? siVal |
| | 8 | 213 | | : 0; |
| | 8 | 214 | | var endIndex = ann.TryGetProperty("end_index", out var ei) |
| | 8 | 215 | | && ei.ValueKind == JsonValueKind.Number |
| | 8 | 216 | | && ei.TryGetInt32(out var eiVal) |
| | 8 | 217 | | ? eiVal |
| | 8 | 218 | | : 0; |
| | | 219 | | |
| | 8 | 220 | | citations.Add(new WebSearchCitation(title, url, startIndex, endIndex)); |
| | 8 | 221 | | } |
| | 0 | 222 | | catch (Exception ex) when (ex is JsonException or InvalidOperationException) |
| | | 223 | | { |
| | | 224 | | // Skip malformed individual citations. |
| | 0 | 225 | | } |
| | | 226 | | } |
| | | 227 | | |
| | 7 | 228 | | return citations; |
| | | 229 | | } |
| | | 230 | | |
| | | 231 | | private static List<WebSearchQuery>? ParseSearchQueries(JsonElement bingSearches) |
| | | 232 | | { |
| | 4 | 233 | | if (bingSearches.ValueKind != JsonValueKind.Array) |
| | | 234 | | { |
| | 0 | 235 | | return null; |
| | | 236 | | } |
| | | 237 | | |
| | 4 | 238 | | var queries = new List<WebSearchQuery>(); |
| | 18 | 239 | | foreach (var item in bingSearches.EnumerateArray()) |
| | | 240 | | { |
| | | 241 | | try |
| | | 242 | | { |
| | 5 | 243 | | var queryText = item.TryGetProperty("text", out var t) |
| | 5 | 244 | | ? t.GetString() ?? "" |
| | 5 | 245 | | : ""; |
| | 5 | 246 | | var url = item.TryGetProperty("url", out var u) |
| | 5 | 247 | | ? u.GetString() ?? "" |
| | 5 | 248 | | : ""; |
| | | 249 | | |
| | 5 | 250 | | queries.Add(new WebSearchQuery(queryText, url)); |
| | 5 | 251 | | } |
| | 0 | 252 | | catch (JsonException) |
| | | 253 | | { |
| | | 254 | | // Skip malformed individual search entries. |
| | 0 | 255 | | } |
| | | 256 | | } |
| | | 257 | | |
| | 4 | 258 | | return queries; |
| | | 259 | | } |
| | | 260 | | } |