Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Docs/README_MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?` |
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"OLTPName": "",
"LogLevel": "Verbose",
"BraveApiKey": "",
"DeepSeekSearchApiKey": "",
"EnableAccounting": false
}
```
Expand Down
3 changes: 3 additions & 0 deletions TelegramSearchBot.Common/Env.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
41 changes: 41 additions & 0 deletions TelegramSearchBot.Common/Model/Tools/DeepSeekSearchResult.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Collections.Generic;
using Newtonsoft.Json;

namespace TelegramSearchBot.Model.Tools {
public class DeepSeekSearchResult {
[JsonProperty("results")]
public List<DeepSeekSearchResultItem> 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; }
}
}
20 changes: 20 additions & 0 deletions TelegramSearchBot.LLM/Service/AI/LLM/McpToolHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = @"{
Expand Down
160 changes: 160 additions & 0 deletions TelegramSearchBot.Test/Service/Tools/DeepSeekSearchServiceTest.cs
Original file line number Diff line number Diff line change
@@ -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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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<IHttpClientFactory> CreateHttpClientFactoryMock(HttpStatusCode statusCode, string content) {
var handlerMock = new Mock<HttpMessageHandler>();
handlerMock.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage {
StatusCode = statusCode,
Content = new StringContent(content)
});

var httpClient = new HttpClient(handlerMock.Object);
var httpClientFactoryMock = new Mock<IHttpClientFactory>();
httpClientFactoryMock.Setup(f => f.CreateClient(It.IsAny<string>()))
.Returns(httpClient);

return httpClientFactoryMock;
}
}
}
8 changes: 8 additions & 0 deletions TelegramSearchBot/Interface/Tools/IDeepSeekSearchService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System.Threading.Tasks;
using TelegramSearchBot.Model.Tools;

namespace TelegramSearchBot.Interface.Tools {
public interface IDeepSeekSearchService {
Task<DeepSeekSearchResult> SearchWebByDeepSeek(string query, int count = 5, string oriQuestion = "", string localization = "", bool needContent = false);
}
}
Loading
Loading