Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Net.Http;
using TelegramSearchBot.Service.AI.LLM;
using Xunit;

namespace TelegramSearchBot.LLM.Test.Service.AI.LLM {
public class OpencodeSessionHeadersTests {
private static HttpClient Client() => new HttpClient();

[Theory]
[InlineData("https://opencode.ai/zen/v1")]
[InlineData("https://opencode.ai/zen/v1/")]
[InlineData("https://www.opencode.ai/zen/v1")]
public void Apply_Opengateways_AddsSessionAndUserAgent(string gateway) {
using var client = Client();

OpencodeSessionHeaders.Apply(client, gateway, "tsb-123");

Assert.Equal("tsb-123", string.Join(",", client.DefaultRequestHeaders.GetValues("x-opencode-session")));
Assert.Equal("TelegramSearchBot/1.0", string.Join(",", client.DefaultRequestHeaders.GetValues("User-Agent")));
}

[Theory]
[InlineData("https://api.openai.com/v1")]
[InlineData("https://api.minimaxi.com/v1")]
[InlineData(null)]
[InlineData("")]
public void Apply_NonOpencodeGateways_AddsNothing(string gateway) {
using var client = Client();

OpencodeSessionHeaders.Apply(client, gateway, "tsb-123");

Assert.False(client.DefaultRequestHeaders.Contains("x-opencode-session"));
}

[Fact]
public void Apply_Twice_DoesNotDuplicateSessionHeader() {
using var client = Client();

OpencodeSessionHeaders.Apply(client, "https://opencode.ai/zen/v1", "tsb-1");
OpencodeSessionHeaders.Apply(client, "https://opencode.ai/zen/v1", "tsb-1");

Assert.Single(client.DefaultRequestHeaders.GetValues("x-opencode-session"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ private async IAsyncEnumerable<string> ExecWithResponsesApiAsync(

// --- Create Responses client ---
using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel, binding, $"tsb-{ChatId}");
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)),
Transport = new HttpClientPipelineTransport(httpClient),
Expand Down Expand Up @@ -543,6 +544,7 @@ public async IAsyncEnumerable<string> ResumeFromSnapshotAsync(
}

using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel, binding, $"tsb-{snapshot.ChatId}");
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)),
Transport = new HttpClientPipelineTransport(httpClient),
Expand Down Expand Up @@ -761,6 +763,7 @@ public async Task<float[]> GenerateEmbeddingsAsync(string text, string modelName
}

using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, endpoint);
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(endpoint),
Transport = new HttpClientPipelineTransport(httpClient),
Expand Down Expand Up @@ -835,6 +838,7 @@ public async Task<IEnumerable<string>> GetAllModels(LLMChannel channel) {
UseProxy = true
};
using var httpClient = new HttpClient(handler);
OpencodeSessionHeaders.Apply(httpClient, channel.Gateway);

var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(channel.Gateway),
Expand Down Expand Up @@ -865,6 +869,7 @@ public async Task<IEnumerable<string>> GetAllModels(LLMChannel channel, LLMApiBi
UseProxy = true
};
using var httpClient = new HttpClient(handler);
OpencodeSessionHeaders.Apply(httpClient, channel, binding);

var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(LlmBindingSupport.ResolveEndpoint(channel, binding)),
Expand All @@ -888,6 +893,7 @@ public async Task<bool> IsHealthyAsync(LLMChannel channel, LLMApiBinding binding

public async Task<IEnumerable<ModelWithCapabilities>> GetAllModelsWithCapabilities(LLMChannel channel) {
using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel.Gateway);

try {
var internalApiUrl = channel.Gateway.TrimEnd('/') + "/dashboard/onboarding/models";
Expand Down Expand Up @@ -939,6 +945,7 @@ public async Task<string> AnalyzeImageAsync(string photoPath, string modelName,
}

using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel, binding);

// For image analysis, use Chat Completions API (vision support is more mature)
var clientOptions = new OpenAIClientOptions {
Expand Down
8 changes: 8 additions & 0 deletions TelegramSearchBot.LLM/Service/AI/LLM/OpenAIService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ public virtual async Task<IEnumerable<string>> GetAllModels(LLMChannel channel)
};

using var httpClient = new HttpClient(handler);
OpencodeSessionHeaders.Apply(httpClient, channel.Gateway);

// --- Client Setup ---
var clientOptions = new OpenAIClientOptions {
Expand Down Expand Up @@ -352,6 +353,7 @@ private async Task<IEnumerable<string>> GetGenericOpenAICompatibleModels(LLMChan
if (!string.IsNullOrEmpty(apiKey)) {
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
}
OpencodeSessionHeaders.Apply(httpClient, channel, binding);

// 构建模型列表 URL,确保路径正确
var gatewayBase = NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding)).TrimEnd('/');
Expand Down Expand Up @@ -483,6 +485,7 @@ public virtual async Task<IEnumerable<ModelWithCapabilities>> GetAllModelsWithCa
// 尝试使用OpenAI内部API获取模型能力信息
var internalApiUrl = channel.Gateway.TrimEnd('/') + "/dashboard/onboarding/models";
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {channel.ApiKey}");
OpencodeSessionHeaders.Apply(httpClient, channel.Gateway);

var response = await httpClient.GetAsync(internalApiUrl);
if (response.IsSuccessStatusCode) {
Expand Down Expand Up @@ -1221,6 +1224,7 @@ private async IAsyncEnumerable<string> ExecWithNativeToolCallingAsync(
excludeDynamicTail: true);

using var client = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{ChatId}");
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))),
Transport = new HttpClientPipelineTransport(client),
Expand Down Expand Up @@ -1516,6 +1520,7 @@ private async IAsyncEnumerable<string> ExecWithXmlToolCallingAsync(
excludeDynamicTail: true);

using var client = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{ChatId}");
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))),
Transport = new HttpClientPipelineTransport(client),
Expand Down Expand Up @@ -1696,6 +1701,7 @@ public async IAsyncEnumerable<string> ResumeFromSnapshotAsync(LlmContinuationSna
excludeDynamicTail: false);

using var client = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(client, channel, binding, $"tsb-{snapshot.ChatId}");
var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))),
Transport = new HttpClientPipelineTransport(client),
Expand Down Expand Up @@ -2005,6 +2011,7 @@ public async Task<float[]> GenerateEmbeddingsAsync(string text, string modelName
}

using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel, binding);

var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, endpoint)),
Expand Down Expand Up @@ -2118,6 +2125,7 @@ public async Task<string> AnalyzeImageAsync(string photoPath, string modelName,
}

using var httpClient = _httpClientFactory.CreateClient();
OpencodeSessionHeaders.Apply(httpClient, channel, binding);

var clientOptions = new OpenAIClientOptions {
Endpoint = new Uri(NormalizeOpenAIEndpoint(channel, LlmBindingSupport.ResolveEndpoint(channel, binding))),
Expand Down
32 changes: 32 additions & 0 deletions TelegramSearchBot.LLM/Service/AI/LLM/OpencodeSessionHeaders.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Net.Http;
using TelegramSearchBot.Model.AI;
using TelegramSearchBot.Model.Data;

namespace TelegramSearchBot.Service.AI.LLM {
/// <summary>
/// OpenCode Go requires a stable `x-opencode-session` per conversation for every request.
/// https://opencode.ai/docs/go/#where-can-i-use-it
/// </summary>
internal static class OpencodeSessionHeaders {
internal const string GlobalSessionId = "tsb-global";

// ponytail: session id is derived from ChatId (stable per conversation); switch to real
// session keys only if opencode ever requires stricter per-thread routing.
internal static void Apply(HttpClient httpClient, string gateway, string sessionId = GlobalSessionId) {
if (httpClient == null ||
string.IsNullOrWhiteSpace(gateway) ||
!gateway.Contains("opencode", StringComparison.OrdinalIgnoreCase)) {
return;
}

httpClient.DefaultRequestHeaders.Remove("x-opencode-session");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("x-opencode-session", sessionId);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "TelegramSearchBot/1.0");
}

// 检测用实际请求 endpoint(binding 优先,回退 channel.Gateway)。
internal static void Apply(HttpClient httpClient, LLMChannel channel, LLMApiBinding binding, string sessionId = GlobalSessionId)
=> Apply(httpClient, LlmBindingSupport.ResolveEndpoint(channel, binding), sessionId);
}
}
Loading