復制
┌───────────────┐ ┌─────────────┐
│ 主界面UI │?─────?│ 會話管理模塊 │
└───────┬───────┘ └──────┬──────┘│ │▼ ▼
┌───────────────┐ ┌─────────────┐
│ API通信模塊 │ │ 文件存儲模塊 │
└───────┬───────┘ └───────┬─────┘│ │▼ ▼
┌───────────────────────────────┐
│ SiliconFlow API │
└───────────────────────────────┘用戶操作流程:
1. 新建會話 → 生成sessionID → 創建空todu文件
2. 輸入問題 → 調用API → 解析響應 → 更新todu
3. 切換會話 → 加載對應todu文件 → 刷新界面
二、核心模塊分工
1.1.界面交互模塊
- 負責控件事件處理
- 管理界面狀態刷新
- 提供用戶輸入驗證
1.2.會話管理模塊
- 維護會話列表和當前會話狀態
- 處理會話切換時的數據加載/保存
- 生成唯一sessionID
1.3.API通信模塊
- 構造符合規范的請求報文
- 處理API響應和錯誤碼
- 結果解析和數據結構轉換
1.4.文件存儲模塊
- 管理todu目錄的文件存儲
- 實現JSON格式的序列化/反序列化
- 文件變更監控和自動保存
三、主要類實現代碼(精簡版)
- 1.會話管理核心類
csharp復制
public class SessionManager
{private string _currentSessionId;private readonly string _workspacePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "todu");public void InitWorkspace(){if (!Directory.Exists(_workspacePath))Directory.CreateDirectory(_workspacePath);}public string CreateNewSession(){var sessionId = Guid.NewGuid().ToString("N");File.WriteAllText(GetSessionFilePath(sessionId), "[]");return sessionId;}public void SwitchSession(string sessionId){_currentSessionId = sessionId;if (!File.Exists(GetSessionFilePath(sessionId)))throw new FileNotFoundException("Session file missing");}public List<TodoItem> GetCurrentTodos(){return JsonConvert.DeserializeObject<List<TodoItem>>(File.ReadAllText(GetSessionFilePath(_currentSessionId)));}private string GetSessionFilePath(string sessionId) => Path.Combine(_workspacePath, $"{sessionId}.json");
}
2.API通信處理類
csharp復制
public class TodoApiClient
{private const string ApiEndpoint = "https://api.siliconflow.cn/v1/chat/completions";public async Task<List<TodoItem>> GenerateTodosAsync(string question){using var client = new HttpClient();client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "[YOUR_API_KEY]");var request = new{model = "deepseek-ai/DeepSeek-V3",messages = new[] {new { role = "user", content = $"請根據以下問題生成規范的待辦事項列表:{question}。按JSON數組格式返回" }},response_format = new { type = "json_object" }};var response = await client.PostAsync(ApiEndpoint, new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"));var responseObj = JObject.Parse(await response.Content.ReadAsStringAsync());return ParseTodoJson(responseObj["choices"][0]["message"]["content"].ToString());}private List<TodoItem> ParseTodoJson(string json){// 示例響應格式:{ "todos": [{...}] }return JObject.Parse(json)["todos"]?.Select(t => new TodoItem {Id = Guid.NewGuid(),Content = t["content"].ToString(),Created = DateTime.Now}).ToList() ?? new List<TodoItem>();}
}
3.文件存儲服務
csharp復制
public class TodoFileManager
{private FileSystemWatcher _watcher;public void SetupFileWatcher(Action<string> onChange){_watcher = new FileSystemWatcher{Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "todu"),Filter = "*.json",NotifyFilter = NotifyFilters.LastWrite};_watcher.Changed += (s, e) => onChange(e.Name.Replace(".json", ""));_watcher.EnableRaisingEvents = true;}public void SaveTodos(string sessionId, List<TodoItem> todos){var json = JsonConvert.SerializeObject(todos, Formatting.Indented);File.WriteAllText(GetFilePath(sessionId), json, Encoding.UTF8);}private string GetFilePath(string sessionId) => Path.Combine("todu", $"{sessionId}.json");
}
4.窗口界面關鍵代碼(Windows Forms)
csharp復制
public partial class MainForm : Form
{private SessionManager _sessionManager = new SessionManager();private TodoApiClient _apiClient = new TodoApiClient();private BindingList<TodoItem> _currentTodos = new BindingList<TodoItem>();public MainForm(){InitializeComponent();_sessionManager.InitWorkspace();lstSessions.DisplayMember = "Key";lstSessions.ValueMember = "Value";todoListBox.DataSource = _currentTodos;todoListBox.DisplayMember = "Content";}// 新建會話按鈕private void btnNewSession_Click(object sender, EventArgs e){var sessionId = _sessionManager.CreateNewSession();lstSessions.Items.Add(new KeyValuePair<string, string>($"會話 {lstSessions.Items.Count+1}", sessionId));}// 發送提問按鈕private async void btnSend_Click(object sender, EventArgs e){var todos = await _apiClient.GenerateTodosAsync(txtInput.Text);_currentTodos.Clear();foreach(var item in todos)_currentTodos.Add(item);_sessionManager.SaveCurrentTodos(_currentTodos.ToList());}// 切換會話選擇private void lstSessions_SelectedIndexChanged(object sender, EventArgs e){if(lstSessions.SelectedItem is KeyValuePair<string, string> selected){_sessionManager.SwitchSession(selected.Value);_currentTodos = new BindingList<TodoItem>(_sessionManager.GetCurrentTodos());todoListBox.DataSource = _currentTodos;}}
}
5.擴展功能建議
csharp復制
// 增加會話元數據存儲
public class SessionMetadata
{public string SessionId { get; set; }public string Title { get; set; }public DateTime LastModified { get; set; }
}// 在SessionManager中添加
public void SaveSessionMetadata(SessionMetadata meta)
{var path = Path.Combine(_workspacePath, "_sessions.json");var list = File.Exists(path) ? JsonConvert.DeserializeObject<List<SessionMetadata>>(File.ReadAllText(path)) : new List<SessionMetadata>();if(list.Any(m => m.SessionId == meta.SessionId))list.RemoveAll(m => m.SessionId == meta.SessionId);list.Add(meta);File.WriteAllText(path, JsonConvert.SerializeObject(list));
}
TODO項狀態管理擴展
csharp復制
public class TodoItem
{public Guid Id { get; set; }public string Content { get; set; }public bool IsCompleted { get; set; }public DateTime Created { get; set; }public DateTime? CompletedDate { get; set; }
}// 在界面中添加狀態切換
private void todoListBox_MouseDoubleClick(object sender, MouseEventArgs e)
{if(todoListBox.SelectedItem is TodoItem item){item.IsCompleted = !item.IsCompleted;item.CompletedDate = item.IsCompleted ? DateTime.Now : null;_sessionManager.SaveCurrentTodos(_currentTodos.ToList());todoListBox.Refresh();}
}