蒼時弦也
蒼時弦也
資深軟體工程師
發表於

對話 UseCase - Clean Architecture in TypeScript

這篇文章是 Clean Architecture in TypeScript 系列的一部分,你可以透過 Leanpub 提前閱讀內容。

驗證大型語言模型可以順利整合後,我們需要繼續依照 Clean Architecture 的處理方式將物件拆分開來,在對話紀錄的處理上我們已經完成過一次,基本上只要依照相同的方式處理即可。

定義介面

這一次我們需要一個叫做 ChatWithAssistant 的 Use Case 來幫我們處理對話的商業邏輯,除此之外還可以順便將原本假的對話紀錄重構成支援以記憶體方式保存的版本,開始進入使用真實對話紀錄的範圍。

首先,更新 src/usecase/interface.ts 更新定義

 1import { ChatMessage } from '@/entity/ChatMessage'
 2
 3export interface ChatMessageRepository {
 4	byId(id: string): Promise<ChatMessage[]>;
 5	save(id: string, messages: ChatMessage[]): Promise<void>;
 6}
 7
 8// ...
 9
10export interface AssistantService {
11	ask(messages: ChatMessage[]): Promise<string>;
12}

接下來實作 src/usecase/chatWithAssistant.ts 的內容,因為我們還沒有設計 Chat 用於聚合物件,所以需要先手動處理 ChatMessage 列表的組合。

 1import { ChatMessage } from '@/entity/ChatMessage';
 2import { ChatMessageRepository, ChatMessagePresenter, AssistantService } from './interface';
 3
 4export class ChatWithAssistant {
 5	constructor(
 6		private readonly chatMessageRepository: ChatMessageRepository,
 7		private readonly assistantService: AssistantService,
 8		private readonly chatMessagePresenter: ChatMessagePresenter,
 9	) {}
10
11	async execute(id: string, message: string): Promise<void> {
12		const messages = await this.chatMessageRepository.byId(id);
13
14		let newMessages: ChatMessage[] = [
15			...messages,
16			new ChatMessage(
17				(messages.length + 1).toString(),
18				id,
19				'user',
20				message
21			),
22		]
23
24		const response = await this.assistantService.ask(newMessages);
25
26		newMessages = [
27			...newMessages,
28			new ChatMessage(
29				(messages.length + 2).toString(),
30				id,
31				'assistant',
32				response
33			),
34		]
35
36		await this.chatMessageRepository.save(id, newMessages);
37
38		newMessages.forEach((message) => {
39			this.chatMessagePresenter.addMessage(message);
40		});
41	}
42}

設計上就是透過 Repository 將訊息取出後,加入使用者的訊息再由語言模型產生新的訊息,並且保存起來用於下一次的對話,為了初期保持行為單純,我們直接將所有訊息回傳。

進行重構

接下來的部分交給 AI 處理即可,大部分關鍵的資訊我們已經在 Use Case 實作中處理完畢,剩下的細節繼續交給 AI 來調整,只需要在最後進行檢查即可。

以 Aider 為例,以下檔案設定為 Read-only 用於參考

  • src/presenter/JsonChatMessagePresenter.ts
  • src/usecase/chatWithAssistant.ts
  • src/usecase/interface.ts

接下來將我們想要編輯的檔案加入到可編輯的檔案中

  • src/api/chat.ts
  • src/controller/chat.ts
  • src/repository/KvChatMessageRepository.ts
  • src/view/Chat.tsx

完成設定後,我們可以用以下的提示來進行修改。

 1Refactor `src/controller/chat.ts` to use `ChatWithAssistant` usecase when user sends a message.
 2
 3## ChatMessageRepository
 4
 5* Update the existing repository to add `save` method for saving chat messages.
 6* Make existing mock data to use real data, returning empty array when no messages are found.
 7
 8## AssistantService
 9
10* Move existing LLM implementation to `src/service/llmAssistantService.ts`.
11* Make AI SDK `generateText` to use multiple messages mode to support contextual conversations.
12
13```typescript
14const { text } = await generateText({
15    // ...
16    messages: [
17        {
18            role: 'user',
19            content: userMessage,
20        },
21        {
22            role: 'assistant',
23            content: assistantMessage,
24        },
25    ],
26})
27```
28
29## Chat API
30
31Update chat API client `sendChatMessage` to match new API interface.
32
33## Chat View
34
35The new API returns full chat history, so the chat view should be updated to display all messages in the conversation.

這一次調整的範圍又在更大一些,目前大部分語言模型都還在提升 Context 的範圍,即使大範圍修改通常也不太會失敗,不過要注意讓 AI 自己搜尋檔案時,指示不夠明確可能會參考錯誤檔案的問題,這部分可以根據正在進行的工作取捨。

修正細節

到目前為止,每一次使用 AI 後都會遺留一些小問題,我們盡可能的將這些問題修正。一定程度上可以確保後續實作在參考時,不會使用到有問題當作基準,另一部分則是 AI 的隨機性有可能造成一些小問題。

這一次的案例中,我們在 src/repository/KvChatMessageRepository.ts 中發現之前製作的假資料一部分被留下。

 1export class KvChatMessageRepository implements ChatMessageRepository {
 2  // Mock data storage - would be replaced with KV in production
 3  private static mockMessages: Record<string, MessageSchema[]> = {
 4    'default': [
 5      {
 6        id: '0',
 7        chatId: 'default',
 8        role: 'assistant',
 9        content: 'Hello! How can I help you today?'
10      }
11    ]
12  };
13
14  // ...
15}

推測原因可能是因為被判斷成要先主動發出訊息呈現在畫面上,因此這樣設定,在我們會希望預設是沒有任何訊息的,因此修改為下面的版本。

1export class KvChatMessageRepository implements ChatMessageRepository {
2  // Mock data storage - would be replaced with KV in production
3  private static mockMessages: Record<string, MessageSchema[]> = {};
4
5  // ...
6}

這樣一來就完成將對話功能重構為 Clean Architecture 的狀態,透過幾次的實踐我們已經開始能透過 AI 來處理細碎的修改任務,同時又保持容易修改的狀態,開始跟以往開發方式有一些差異。