Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
564a070
refactor(llm): shared LlmToolLoop + ILlmTurnSource; migrate Anthropic…
ModerRAS Sep 10, 2026
766972a
refactor(llm): migrate OpenAIService (3 loops -> shared LlmToolLoop)
ModerRAS Sep 10, 2026
8c27c25
refactor(llm): migrate OllamaService and GeminiService to shared LlmT…
ModerRAS Sep 10, 2026
4ee5488
refactor(llm): migrate OpenAIResponsesService to shared LlmToolLoop
ModerRAS Sep 10, 2026
41cd7e9
feat(llm): built-in provider catalog with 预制渠道 command (presets prefi…
ModerRAS Sep 10, 2026
3b72824
test(llm): unit tests for shared LlmToolLoop (text protocol, native p…
ModerRAS Sep 10, 2026
9f597df
docs: document 预制渠道 command in Bot_Commands_User_Guide
ModerRAS Sep 10, 2026
c16738d
chore: ignore .pi agent session state
ModerRAS Sep 10, 2026
fb29ba8
feat(llm): opencode go/zen presets; shared LlmHistoryQueryService ske…
ModerRAS Sep 10, 2026
fad9c57
docs: rewrite strategy for LLM module refactor (big-bang, data migrat…
ModerRAS Sep 10, 2026
0690d0d
refactor(llm): normalized LlmMessage model, shared history projector+…
ModerRAS Sep 10, 2026
a9e2547
refactor(llm): extract OpenAiChatTransport to Transports/ (step 1 of …
ModerRAS Sep 11, 2026
2e23d7b
refactor(llm): extract AnthropicMessagesTransport to Transports/
ModerRAS Sep 11, 2026
dc5c0eb
refactor(llm): extract OpenAIResponsesTransport to Transports/
ModerRAS Sep 11, 2026
6cbe2fb
refactor(llm): extract GeminiTransport and OllamaTransport to Transpo…
ModerRAS Sep 11, 2026
fd38e23
refactor(llm): replace ILLMService/ILLMFactory/LLMFactory with ILlmPr…
ModerRAS Sep 11, 2026
b7ee57f
refactor(llm): remove dead GetChatHistory/IsSameSender legacy history…
ModerRAS Sep 11, 2026
95190e9
refactor(llm): unify ModelCapabilityService and LlmServiceProxy provi…
ModerRAS Sep 11, 2026
3710dc4
docs(plan): add Phase 4.5 provider-class elimination plan with target…
ModerRAS Sep 11, 2026
99b7052
feat(llm): add LlmChatRunner + per-transport Create factories (S1+S2 …
ModerRAS Sep 12, 2026
1fd6458
refactor(llm): Anthropic ExecWithHistoryAsync delegates to LlmChatRunner
ModerRAS Sep 12, 2026
6aa4a34
refactor(llm): OpenAIResponses ExecWithHistoryAsync delegates to LlmC…
ModerRAS Sep 12, 2026
9193fe3
refactor(llm): Gemini ExecWithHistoryAsync delegates to LlmChatRunner
ModerRAS Sep 12, 2026
a9e6003
refactor(llm): Ollama ExecWithHistoryAsync delegates to LlmChatRunner…
ModerRAS Sep 12, 2026
78aa845
feat(llm): capability interfaces ILlmModelCatalog/ILlmEmbeddings/ILlm…
ModerRAS Sep 12, 2026
e6356f7
refactor(llm): switch EditLLMConfHelper and ModelCapabilityService to…
ModerRAS Sep 12, 2026
46f553c
refactor(llm): facade message-path routes through LlmHistoryQueryServ…
ModerRAS Sep 12, 2026
6e12fb3
refactor(llm): runner RunFromSnapshotAsync; facade + LlmServiceProxy …
ModerRAS Sep 12, 2026
74beac2
refactor(llm)! delete ILlmProvider + 5 service classes; ProviderApi/{…
ModerRAS Sep 12, 2026
391b699
docs(plan): mark Phase 4.5 complete (CI green)
ModerRAS Sep 12, 2026
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
739 changes: 371 additions & 368 deletions .gitignore

Large diffs are not rendered by default.

393 changes: 393 additions & 0 deletions Docs/Agent_Architecture_Refactor_Plan.md

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions Docs/Bot_Commands_User_Guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,13 @@

* **LLM渠道配置** (在群组中由全局管理员发送,会触发交互式配置流程)
* **说明**: 以下指令用于管理LLM API渠道。它们会启动一个多步骤的对话流程(状态机),机器人会依次询问配置所需的各项信息。请按照机器人的提示逐步回复。
* **预制渠道**:从内置 Provider 预设目录一步创建渠道(Anthropic、OpenAI Chat/Responses、Gemini、MiniMax、Ollama、LM Studio、DeepSeek、Moonshot 等常见提供商已预置默认地址与默认模型列表)。交互流程:
1. 管理员发送: `预制渠道`
2. 机器人回复: 预设列表(含默认地址与默认模型)
3. 管理员发送预设编号
4. 机器人回复: `请输入 <预设名> 的 API Key(本地/免 Key 服务发送 - 跳过):`
5. 管理员发送 API Key(或 `-`)
6. 机器人回复: `渠道创建成功(ID: x)`,并自动预置默认模型;自定义 endpoint / 模型仍可用 `新建渠道` / `添加模型` 修改。
* **例如,使用 `新建渠道` 指令的交互流程可能如下:**
1. 管理员发送: `新建渠道`
2. 机器人回复: `请输入渠道的名称`
Expand Down
100 changes: 100 additions & 0 deletions TelegramSearchBot.Common/Model/AI/Llm/LlmMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Text.Json;

namespace TelegramSearchBot.Model.AI {
/// <summary>Normalized message role across all API dialects.</summary>
public enum LlmRole {
System = 0,
User = 1,
Assistant = 2,
Tool = 3
}

/// <summary>A normalized tool call initiated by an assistant message.</summary>
public sealed class LlmToolCall {
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string ArgumentsJson { get; set; } = "{}";

/// <summary>Arguments as string dict (the canonical form used by McpToolHelper).</summary>
public Dictionary<string, string> ParseArguments() {
if (string.IsNullOrWhiteSpace(ArgumentsJson)) {
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
try {
return JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(ArgumentsJson)
?.ToDictionary(kv => kv.Key, kv => kv.Value.ToString())
?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
} catch (Exception) {
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
}
}

/// <summary>Tool result appended after a tool call (mirrors assistant tool_calls by id).</summary>
public sealed class LlmToolResult {
public string ToolCallId { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Result { get; set; } = string.Empty;
public bool IsError { get; set; }
}

/// <summary>
/// The single normalized message representation used end to end: history projection,
/// agent loop state, transport requests, and continuation snapshots (schema v2).
/// Replaces per-provider history types and their serialize/deserialize pairs.
/// </summary>
public sealed class LlmMessage {
public LlmRole Role { get; set; }
/// <summary>Text content. For Tool-role messages this is the tool result text.</summary>
public string? Text { get; set; }
/// <summary>Reasoning/thinking content for assistant messages (thinking-mode models).</summary>
public string? Thinking { get; set; }
/// <summary>Tool calls initiated by this assistant message (null otherwise).</summary>
public List<LlmToolCall>? ToolCalls { get; set; }
/// <summary>Tool call id for Tool-role messages.</summary>
public string? ToolCallId { get; set; }
/// <summary>PNG image bytes for user visual input (vision-capable transports only).</summary>
public byte[]? ImagePng { get; set; }
public string? ImageMediaType { get; set; }
/// <summary>Tool-role only: whether the tool execution failed.</summary>
public bool IsToolError { get; set; }

public static LlmMessage System(string text) => new() { Role = LlmRole.System, Text = text };
public static LlmMessage User(string text, byte[]? imagePng = null, string? imageMediaType = null)
=> new() { Role = LlmRole.User, Text = text, ImagePng = imagePng, ImageMediaType = imageMediaType };
public static LlmMessage Assistant(string? text, string? thinking = null, List<LlmToolCall>? toolCalls = null)
=> new() { Role = LlmRole.Assistant, Text = text, Thinking = thinking, ToolCalls = toolCalls };
public static LlmMessage ToolResult(string toolCallId, string name, string result, bool isError = false)
=> new() { Role = LlmRole.Tool, ToolCallId = toolCallId, Thinking = name, Text = result, IsToolError = isError };
}

/// <summary>Normalized tool definition advertised to the model.</summary>
public sealed class LlmToolSpec {
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
/// <summary>JSON schema for parameters (provider-neutral).</summary>
public string ParametersJson { get; set; } = "{}";
public bool StrictSchema { get; set; }
}

/// <summary>Result of one assistant turn after streaming completed.</summary>
public sealed class LlmTurnResult {
/// <summary>Full turn text (not trimmed).</summary>
public string Text { get; set; } = string.Empty;
/// <summary>Reasoning/thinking content, when the provider streams it.</summary>
public string Reasoning { get; set; } = string.Empty;
/// <summary>Native tool calls, empty for text-protocol sources and pure-text turns.</summary>
public List<LlmToolCall> ToolCalls { get; set; } = new();
/// <summary>
/// Native protocol: tool call metadata was malformed and the transport already appended a
/// self-correction message to its history; the loop must continue without executing tools.
/// </summary>
public bool MalformedToolCall { get; set; }
/// <summary>Provider-specific usage observation for prompt-caching telemetry (opaque).</summary>
public object? UsageObservation { get; set; }
/// <summary>True when at least one delta arrived during the turn.</summary>
public bool StreamedAny { get; set; }
}
}
10 changes: 10 additions & 0 deletions TelegramSearchBot.Common/Model/AI/Llm/LlmTurnModels.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using TelegramSearchBot.Model.AI;

namespace TelegramSearchBot.Model.AI {
/// <summary>Events streamed by a transport turn. Always terminates with TurnCompleted.</summary>
public abstract record LlmStreamEvent {
public sealed record TextDelta(string Delta) : LlmStreamEvent;
public sealed record ThinkingDelta(string Delta) : LlmStreamEvent;
public sealed record TurnCompleted(LlmTurnResult Turn) : LlmStreamEvent;
}
}
11 changes: 9 additions & 2 deletions TelegramSearchBot.Common/Model/AI/LlmContinuationSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,16 @@ public string SchemaVersion {
public int ChannelId { get; set; }

/// <summary>
/// Serialized conversation history (all messages including system, user, assistant, tool results)
/// Schema v1 (legacy): per-provider serialized history. Kept for deserializing old snapshots;
/// obsolete snapshots expire via TTL and are not migrated.
/// </summary>
public List<SerializedChatMessage> ProviderHistory { get; set; } = [];
public List<SerializedChatMessage>? ProviderHistory { get; set; }

/// <summary>
/// Schema v2: normalized conversation history (all messages including system, user,
/// assistant with tool calls, tool results). The single snapshot format going forward.
/// </summary>
public List<LlmMessage>? NormalizedHistory { get; set; }

/// <summary>
/// The last accumulated content that was displayed to the user
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class AgentProcessToolRegistrationTests {
public void BuildServices_RegistersResponsesApiExecutor() {
using var provider = BuildAgentServices();

Assert.NotNull(provider.GetService<OpenAIResponsesService>());
Assert.NotNull(provider.GetService<ResponsesModelApi>());
}

private static ServiceProvider BuildAgentServices() {
Expand Down
Loading
Loading