From ee687806b2378998216d8833c898b1fffbfc5306 Mon Sep 17 00:00:00 2001 From: ModerRAS Date: Wed, 28 Oct 2026 11:53:12 +0800 Subject: [PATCH] =?UTF-8?q?feat(search):=20=E6=96=B0=E5=A2=9E=20DeepSeek?= =?UTF-8?q?=20Search=20=E7=BD=91=E9=A1=B5=E6=90=9C=E7=B4=A2=E9=80=82?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 DeepSeekSearchService/IDeepSeekSearchService,对接 POST /v1/tools/search (Bearer 鉴权,query/count/ori_question/localization/need_content), 含重试、429 退避与 Brave 风格一致的错误处理;Brave 保持不动 - 新增 DeepSeekSearchResult 模型(results/title/url/snippet/summary/ content/site_name/site_icon/date/authority/rerank_score) - 新增独立 BuiltInTool: deepseek_search_web - Env/Config 新增 DeepSeekSearchApiKey(与 BraveApiKey 并列,需单独配置) - McpToolHelper 为 DeepSeekSearchResult 增加与 Brave 类似的格式化输出 - 新增 DeepSeekSearchServiceTest(happy path/空 key/401/坏 JSON); Brave 与 DeepSeek 搜索测试共用 AgentEnvSerial 串行集合, 避免 TEST_ENV/静态 Env 并行竞态 - 文档:README_MCP 工具表 + README 配置示例 --- Docs/README_MCP.md | 1 + README.md | 1 + TelegramSearchBot.Common/Env.cs | 3 + .../Model/Tools/DeepSeekSearchResult.cs | 41 +++++ .../Service/AI/LLM/McpToolHelper.cs | 20 +++ .../Service/Tools/BraveSearchServiceTest.cs | 1 + .../Tools/DeepSeekSearchServiceTest.cs | 160 ++++++++++++++++++ .../Interface/Tools/IDeepSeekSearchService.cs | 8 + .../Service/Tools/DeepSeekSearchService.cs | 123 ++++++++++++++ 9 files changed, 358 insertions(+) create mode 100644 TelegramSearchBot.Common/Model/Tools/DeepSeekSearchResult.cs create mode 100644 TelegramSearchBot.Test/Service/Tools/DeepSeekSearchServiceTest.cs create mode 100644 TelegramSearchBot/Interface/Tools/IDeepSeekSearchService.cs create mode 100644 TelegramSearchBot/Service/Tools/DeepSeekSearchService.cs diff --git a/Docs/README_MCP.md b/Docs/README_MCP.md index bf812842..1c963a87 100644 --- a/Docs/README_MCP.md +++ b/Docs/README_MCP.md @@ -133,6 +133,7 @@ API 地址和 API Key 来自该模型关联的 LLM 渠道,因此可通过 `新 |---------|------|------| | `process_memory_command` | 在记忆图谱中执行操作 | `command`, `arguments` | | `search_web` | 使用 Brave Search API 进行网页搜索 | `query`, `page?`, `count?`, `country?`, `search_lang?` | +| `deepseek_search_web` | 使用 DeepSeek Search API 进行网页搜索 | `query`, `count?`, `ori_question?`, `localization?`, `need_content?` | | `extract_article` | 使用 Puppeteer 提取网页文章内容 | `url` | | `sequential_thinking` | 动态问题解决思考工具 | `input`, `next_thought_needed?`, `thought_number?`, `total_thoughts?`, ... | | `bash` | 执行 Shell 命令 | `command`, `working_directory?`, `timeout_ms?` | diff --git a/README.md b/README.md index d458fb8f..5624ce6f 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ "OLTPName": "", "LogLevel": "Verbose", "BraveApiKey": "", + "DeepSeekSearchApiKey": "", "EnableAccounting": false } ``` diff --git a/TelegramSearchBot.Common/Env.cs b/TelegramSearchBot.Common/Env.cs index 8492a8fa..18db7ade 100644 --- a/TelegramSearchBot.Common/Env.cs +++ b/TelegramSearchBot.Common/Env.cs @@ -46,6 +46,7 @@ static Env() { OLTPName = config.OLTPName; SerilogMinimumLevel = ResolveSerilogMinimumLevel(config.LogLevel); BraveApiKey = config.BraveApiKey; + DeepSeekSearchApiKey = config.DeepSeekSearchApiKey; EnableAccounting = config.EnableAccounting; EnableAutoUpdate = config.EnableAutoUpdate; UpdateBaseUrl = ResolveUpdateBaseUrl(config); @@ -150,6 +151,7 @@ private static string NormalizeBaseUrl(string? baseUrl, string fallback) { public static string OLTPName { get; set; } = null!; public static readonly LogEventLevel SerilogMinimumLevel; public static string BraveApiKey { get; set; } = null!; + public static string DeepSeekSearchApiKey { get; set; } = null!; public static bool EnableAccounting { get; set; } = false; public static int MaxToolCycles { get; set; } public static bool EnableLLMAgentProcess { get; set; } = false; @@ -315,6 +317,7 @@ public class Config { public string OLTPName { get; set; } = null!; public string LogLevel { get; set; } = "Verbose"; public string BraveApiKey { get; set; } = null!; + public string DeepSeekSearchApiKey { get; set; } = null!; public bool EnableAccounting { get; set; } = false; public int MaxToolCycles { get; set; } = 25; public bool EnableLLMAgentProcess { get; set; } = false; diff --git a/TelegramSearchBot.Common/Model/Tools/DeepSeekSearchResult.cs b/TelegramSearchBot.Common/Model/Tools/DeepSeekSearchResult.cs new file mode 100644 index 00000000..5689a41f --- /dev/null +++ b/TelegramSearchBot.Common/Model/Tools/DeepSeekSearchResult.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace TelegramSearchBot.Model.Tools { + public class DeepSeekSearchResult { + [JsonProperty("results")] + public List Results { get; set; } = []; + } + + public class DeepSeekSearchResultItem { + [JsonProperty("title")] + public string Title { get; set; } = null!; + + [JsonProperty("url")] + public string Url { get; set; } = null!; + + [JsonProperty("snippet")] + public string Snippet { get; set; } = null!; + + [JsonProperty("summary")] + public string Summary { get; set; } = null!; + + [JsonProperty("content")] + public string Content { get; set; } = null!; + + [JsonProperty("site_name")] + public string SiteName { get; set; } = null!; + + [JsonProperty("site_icon")] + public string SiteIcon { get; set; } = null!; + + [JsonProperty("date")] + public string Date { get; set; } = null!; + + [JsonProperty("authority")] + public int Authority { get; set; } + + [JsonProperty("rerank_score")] + public float RerankScore { get; set; } + } +} diff --git a/TelegramSearchBot.LLM/Service/AI/LLM/McpToolHelper.cs b/TelegramSearchBot.LLM/Service/AI/LLM/McpToolHelper.cs index b7857927..c1aab5ad 100644 --- a/TelegramSearchBot.LLM/Service/AI/LLM/McpToolHelper.cs +++ b/TelegramSearchBot.LLM/Service/AI/LLM/McpToolHelper.cs @@ -1177,6 +1177,26 @@ public static string ConvertToolResultToString(object toolResultObject) { sb.AppendLine($"--- End of {Math.Min(braveResult.Web.Results.Count, 5)} results ---"); } return sb.ToString(); + } else if (toolResultObject is DeepSeekSearchResult deepseekResult) { + var sb = new StringBuilder(); + sb.AppendLine("Search Results (DeepSeek):"); + if (deepseekResult.Results == null || !deepseekResult.Results.Any()) { + sb.AppendLine("No results found."); + } else { + int count = 1; + foreach (var item in deepseekResult.Results.Take(5)) // Limit to 5 results + { + sb.AppendLine($"{count}. Title: {item.Title}"); + var snippet = !string.IsNullOrWhiteSpace(item.Summary) ? item.Summary : item.Snippet; + if (!string.IsNullOrWhiteSpace(snippet)) { + sb.AppendLine($" Snippet: {snippet.Replace("\n", " ").Trim()}"); + } + sb.AppendLine($" Source: {item.Url}"); + count++; + } + sb.AppendLine($"--- End of {Math.Min(deepseekResult.Results.Count, 5)} results ---"); + } + return sb.ToString(); } else { try { return JsonConvert.SerializeObject(toolResultObject, Formatting.Indented, diff --git a/TelegramSearchBot.Test/Service/Tools/BraveSearchServiceTest.cs b/TelegramSearchBot.Test/Service/Tools/BraveSearchServiceTest.cs index 20e55521..6826c9a7 100644 --- a/TelegramSearchBot.Test/Service/Tools/BraveSearchServiceTest.cs +++ b/TelegramSearchBot.Test/Service/Tools/BraveSearchServiceTest.cs @@ -12,6 +12,7 @@ using Xunit; namespace TelegramSearchBot.Test.Service.Tools { + [Collection("AgentEnvSerial")] public class BraveSearchServiceTest { private const string ValidApiKey = "test-api-key"; private const string ValidResponseJson = @"{ diff --git a/TelegramSearchBot.Test/Service/Tools/DeepSeekSearchServiceTest.cs b/TelegramSearchBot.Test/Service/Tools/DeepSeekSearchServiceTest.cs new file mode 100644 index 00000000..9f00bc65 --- /dev/null +++ b/TelegramSearchBot.Test/Service/Tools/DeepSeekSearchServiceTest.cs @@ -0,0 +1,160 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Moq; +using Moq.Protected; +using TelegramSearchBot.Common; +using TelegramSearchBot.Service.Tools; +using Xunit; + +namespace TelegramSearchBot.Test.Service.Tools { + [Collection("AgentEnvSerial")] + public class DeepSeekSearchServiceTest { + private const string ValidApiKey = "test-api-key"; + private const string ValidResponseJson = @"{ + ""results"": [ + { + ""rerank_score"": 2.4, + ""title"": ""Test Result"", + ""url"": ""https://example.com"", + ""snippet"": ""Test snippet"", + ""summary"": ""Test summary"", + ""content"": ""Test content"", + ""site_name"": ""Example"", + ""site_icon"": ""https://example.com/favicon.ico"", + ""date"": ""2026-06-01T00:00:00+00:00"", + ""authority"": 3 + } + ] + }"; + + [Fact] + public async Task SearchWebByDeepSeek_WithValidResponse_ParsesCorrectly() { + // Arrange + var httpClientFactory = CreateHttpClientFactoryMock(HttpStatusCode.OK, ValidResponseJson); + var service = new DeepSeekSearchService(httpClientFactory.Object); + + // 通过反射设置Env.DeepSeekSearchApiKey + var apiKeyProperty = typeof(Env).GetProperty("DeepSeekSearchApiKey"); + var originalValue = apiKeyProperty.GetValue(null); + apiKeyProperty.SetValue(null, ValidApiKey ?? string.Empty); + + // 设置TEST_ENV环境变量,模拟测试环境 + string originalTestEnv = Environment.GetEnvironmentVariable("TEST_ENV"); + Environment.SetEnvironmentVariable("TEST_ENV", "true"); + + try { + // Act + var result = await service.SearchWebByDeepSeek("test query"); + + // Assert + Assert.NotNull(result); + Assert.Single(result.Results); + Assert.Equal("Test Result", result.Results[0].Title); + Assert.Equal("https://example.com", result.Results[0].Url); + Assert.Equal("Test snippet", result.Results[0].Snippet); + Assert.Equal("Test summary", result.Results[0].Summary); + } finally { + // 恢复原始值 + apiKeyProperty.SetValue(null, originalValue); + if (originalTestEnv != null) { + Environment.SetEnvironmentVariable("TEST_ENV", originalTestEnv); + } else { + Environment.SetEnvironmentVariable("TEST_ENV", null); + } + } + } + + [Fact] + public async Task SearchWebByDeepSeek_WithUnauthorizedResponse_ThrowsInvalidOperationException() { + // Arrange + var httpClientFactory = CreateHttpClientFactoryMock(HttpStatusCode.Unauthorized, ""); + var service = new DeepSeekSearchService(httpClientFactory.Object); + + // 通过反射设置Env.DeepSeekSearchApiKey + var apiKeyProperty = typeof(Env).GetProperty("DeepSeekSearchApiKey"); + var originalValue = apiKeyProperty.GetValue(null); + apiKeyProperty.SetValue(null, ValidApiKey ?? string.Empty); + + try { + // Act & Assert + await Assert.ThrowsAsync(() => service.SearchWebByDeepSeek("test query")); + } finally { + // 恢复原始值 + apiKeyProperty.SetValue(null, originalValue); + } + } + + [Fact] + public async Task SearchWebByDeepSeek_WithInvalidJson_ThrowsInvalidOperationException() { + // Arrange + var invalidJson = "{ invalid json }"; + var httpClientFactory = CreateHttpClientFactoryMock(HttpStatusCode.OK, invalidJson); + var service = new DeepSeekSearchService(httpClientFactory.Object); + + // 通过反射设置Env.DeepSeekSearchApiKey + var apiKeyProperty = typeof(Env).GetProperty("DeepSeekSearchApiKey"); + var originalValue = apiKeyProperty.GetValue(null); + apiKeyProperty.SetValue(null, ValidApiKey ?? string.Empty); + + try { + // Act & Assert + await Assert.ThrowsAsync(() => service.SearchWebByDeepSeek("test query")); + } finally { + // 恢复原始值 + apiKeyProperty.SetValue(null, originalValue); + } + } + + [Fact] + public async Task SearchWebByDeepSeek_WithEmptyApiKey_ThrowsInvalidOperationException() { + // Arrange + var httpClientFactory = CreateHttpClientFactoryMock(HttpStatusCode.OK, ValidResponseJson); + var service = new DeepSeekSearchService(httpClientFactory.Object); + + // 通过反射设置Env.DeepSeekSearchApiKey为空 + var apiKeyProperty = typeof(Env).GetProperty("DeepSeekSearchApiKey"); + var originalValue = apiKeyProperty.GetValue(null); + apiKeyProperty.SetValue(null, ""); + + // 设置TEST_ENV环境变量为空,模拟非测试环境 + string originalTestEnv = Environment.GetEnvironmentVariable("TEST_ENV"); + Environment.SetEnvironmentVariable("TEST_ENV", null); + + try { + // Act & Assert + await Assert.ThrowsAsync(() => service.SearchWebByDeepSeek("test query")); + } finally { + // 恢复原始值 + apiKeyProperty.SetValue(null, originalValue); + if (originalTestEnv != null) { + Environment.SetEnvironmentVariable("TEST_ENV", originalTestEnv); + } else { + Environment.SetEnvironmentVariable("TEST_ENV", null); + } + } + } + + private Mock CreateHttpClientFactoryMock(HttpStatusCode statusCode, string content) { + var handlerMock = new Mock(); + handlerMock.Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny()) + .ReturnsAsync(new HttpResponseMessage { + StatusCode = statusCode, + Content = new StringContent(content) + }); + + var httpClient = new HttpClient(handlerMock.Object); + var httpClientFactoryMock = new Mock(); + httpClientFactoryMock.Setup(f => f.CreateClient(It.IsAny())) + .Returns(httpClient); + + return httpClientFactoryMock; + } + } +} diff --git a/TelegramSearchBot/Interface/Tools/IDeepSeekSearchService.cs b/TelegramSearchBot/Interface/Tools/IDeepSeekSearchService.cs new file mode 100644 index 00000000..52120510 --- /dev/null +++ b/TelegramSearchBot/Interface/Tools/IDeepSeekSearchService.cs @@ -0,0 +1,8 @@ +using System.Threading.Tasks; +using TelegramSearchBot.Model.Tools; + +namespace TelegramSearchBot.Interface.Tools { + public interface IDeepSeekSearchService { + Task SearchWebByDeepSeek(string query, int count = 5, string oriQuestion = "", string localization = "", bool needContent = false); + } +} diff --git a/TelegramSearchBot/Service/Tools/DeepSeekSearchService.cs b/TelegramSearchBot/Service/Tools/DeepSeekSearchService.cs new file mode 100644 index 00000000..60acaabd --- /dev/null +++ b/TelegramSearchBot/Service/Tools/DeepSeekSearchService.cs @@ -0,0 +1,123 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; +using Newtonsoft.Json; +using TelegramSearchBot.Attributes; +using TelegramSearchBot.Common; +using TelegramSearchBot.Interface.Tools; +using TelegramSearchBot.Model.Tools; +using TelegramSearchBot.Service.AI.LLM; // For McpToolHelper + +namespace TelegramSearchBot.Service.Tools { + [Injectable(Microsoft.Extensions.DependencyInjection.ServiceLifetime.Transient)] + public class DeepSeekSearchService : IDeepSeekSearchService { + private const string SearchEndpoint = "https://api.deepseek.com/v1/tools/search"; + private const int DefaultTimeoutSeconds = 10; + + private readonly HttpClient _httpClient; + private readonly string _apiKey; + + public DeepSeekSearchService(IHttpClientFactory httpClientFactory) { + _httpClient = httpClientFactory.CreateClient(); + _httpClient.Timeout = TimeSpan.FromSeconds(DefaultTimeoutSeconds); + _apiKey = Env.DeepSeekSearchApiKey ?? string.Empty; + } + + [BuiltInTool("Searches the web using DeepSeek Search API. Returns web search results with titles, snippets, summaries, and URLs.", Name = "deepseek_search_web")] + public async Task SearchWebByDeepSeek( + [BuiltInParameter("The search query string, 1-128 characters (e.g., 'weather in Tokyo', 'DeepSeek V4 release notes').")] string query, + [BuiltInParameter("Number of search results (e.g., 5, 10). Defaults to 5, maximum is 50.", IsRequired = false)] int count = 5, + [BuiltInParameter("The original user question for better result relevance. Optional.", IsRequired = false)] string oriQuestion = "", + [BuiltInParameter("An optional IP address used to localize search results. Optional.", IsRequired = false)] string localization = "", + [BuiltInParameter("Whether to return page content in results. Defaults to false.", IsRequired = false)] bool needContent = false) { + const int maxRetries = 3; + const int delayMs = 1000; + + // 验证API密钥 + // 注意:在测试环境中,我们允许空的API密钥,但在实际使用中应该配置API密钥 + if (string.IsNullOrEmpty(_apiKey) && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEST_ENV"))) { + throw new InvalidOperationException("DeepSeek Search API key is not configured"); + } + + // 验证参数 + if (string.IsNullOrWhiteSpace(query)) { + throw new ArgumentException("Query cannot be null or empty", nameof(query)); + } + + var trimmedQuery = query.Trim(); + if (trimmedQuery.Length > 128) { + throw new ArgumentException("Query cannot exceed 128 characters", nameof(query)); + } + + if (count <= 0 || count > 50) { + throw new ArgumentException("Count must be between 1 and 50", nameof(count)); + } + + var requestBody = new { + query = trimmedQuery, + count = count, + ori_question = oriQuestion ?? string.Empty, + localization = localization ?? string.Empty, + need_content = needContent, + }; + var jsonBody = JsonConvert.SerializeObject(requestBody); + + for (int retry = 0; retry <= maxRetries; retry++) { + try { + using var request = new HttpRequestMessage(HttpMethod.Post, SearchEndpoint); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); + request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); + + var response = await _httpClient.SendAsync(request); + + // 处理不同的HTTP状态码 + switch (response.StatusCode) { + case HttpStatusCode.OK: + // 解析响应 + var json = await response.Content.ReadAsStringAsync(); + var result = JsonConvert.DeserializeObject(json); + return result; + case HttpStatusCode.Unauthorized: + throw new InvalidOperationException("DeepSeek Search API key is invalid or missing"); + case HttpStatusCode.TooManyRequests: + if (retry < maxRetries) { + // 等待后重试 + await Task.Delay(delayMs * ( retry + 1 )); // 指数退避 + continue; + } + throw new InvalidOperationException("DeepSeek Search API rate limit exceeded"); + case HttpStatusCode.BadRequest: + var badRequestContent = await response.Content.ReadAsStringAsync(); + throw new InvalidOperationException($"DeepSeek Search API bad request - invalid parameters: {badRequestContent}"); + default: + var errorContent = await response.Content.ReadAsStringAsync(); + throw new InvalidOperationException($"DeepSeek Search API error: {response.StatusCode} - {errorContent}"); + } + } catch (HttpRequestException ex) { + if (retry < maxRetries) { + // 等待后重试 + await Task.Delay(delayMs * ( retry + 1 )); // 指数退避 + continue; + } + throw new InvalidOperationException($"Network error while calling DeepSeek Search API: {ex.Message}", ex); + } catch (TaskCanceledException ex) { + if (retry < maxRetries) { + // 等待后重试 + await Task.Delay(delayMs * ( retry + 1 )); // 指数退避 + continue; + } + throw new InvalidOperationException("Request timeout while calling DeepSeek Search API", ex); + } catch (JsonException ex) { + // JSON解析错误不重试 + throw new InvalidOperationException($"Error parsing DeepSeek Search API response: {ex.Message}", ex); + } + } + + return null; // 这行不会执行,仅为编译器满意 + } + } +}