ToolCall.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { nextTick, type Ref } from "vue";
  2. import { LocalMessageIdPool, type ChatMessagesManager } from "./Messages";
  3. import { ChatMessage as ChatMessageModel } from "../model/Message";
  4. import { ChatUtils } from "../utils/ChatUtils";
  5. import type OpenAI from "openai"
  6. import type { ChatToolContext, ChatToolsManager } from "./Tools";
  7. import type { ChatInterfaceManager } from "./Chat";
  8. import type { ChatSessionManager } from "../composables/useChatSession";
  9. export function useToolCalls(
  10. messagesManager: ChatMessagesManager,
  11. toolsManager: ChatToolsManager,
  12. interfaceManager: ChatInterfaceManager,
  13. sessionManager: ChatSessionManager
  14. ) {
  15. /**
  16. * 执行工具调用
  17. */
  18. async function executeToolCalls(toolCalls: OpenAI.Chat.ChatCompletionMessageToolCall[], parentMessageId: number) {
  19. const ctx: ChatToolContext = {
  20. messages: messagesManager.messages as Ref<ChatMessageModel[]>,
  21. scrollToBottom: interfaceManager.scrollToBottom,
  22. };
  23. for (const call of toolCalls) {
  24. if (call.type !== "function") continue;
  25. const name = call.function.name;
  26. const tool = toolsManager.toolRegistry.value.get(name);
  27. const newToolMessageId = LocalMessageIdPool.getNextId();
  28. const toolMsg = messagesManager.addMessage(ChatMessageModel.createTool(name, `调用工具 ${name}`, newToolMessageId) as ChatMessageModel);;
  29. toolMsg.parentId = parentMessageId;
  30. try {
  31. if (!tool)
  32. throw new Error(`未找到工具:${name}`);
  33. let args: any = call.function.arguments;
  34. if (typeof args === "string" && args.trim()) {
  35. try {
  36. args = JSON.parse(args);
  37. } catch (error) {
  38. throw new Error('工具参数解析失败: ' + (error as Error).message);
  39. }
  40. }
  41. const rs = await tool.handler(args, ctx);
  42. if (toolMsg) {
  43. toolMsg.content += ' 成功'
  44. toolMsg.extra = (typeof rs === "string" ? rs : JSON.stringify(rs, null, 2));
  45. toolMsg.state = "success";
  46. }
  47. } catch (error) {
  48. toolMsg.state = "error";
  49. toolMsg.content += ' 失败';
  50. toolMsg.setError("工具执行失败", ChatUtils.formatError(error));
  51. }
  52. if (toolMsg) {
  53. try {
  54. await sessionManager.persistMessages([toolMsg]);
  55. } catch (error) {
  56. console.error(error);
  57. }
  58. }
  59. await nextTick();
  60. await interfaceManager.scrollToBottom?.();
  61. }
  62. }
  63. return {
  64. executeToolCalls,
  65. }
  66. }