001/* 002 * Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.agentsflex.core.message; 017 018import com.agentsflex.core.util.Copyable; 019import com.agentsflex.core.util.Maps; 020import com.alibaba.fastjson2.JSON; 021 022import java.io.Serializable; 023import java.util.Map; 024 025public class ToolCall implements Serializable, Copyable<ToolCall> { 026 027 private String id; 028 private String name; 029 private String arguments; 030 031 public ToolCall() { 032 } 033 034 public ToolCall(String id, String name, String arguments) { 035 this.id = id; 036 this.name = name; 037 this.arguments = arguments; 038 } 039 040 public String getId() { 041 return id; 042 } 043 044 public void setId(String id) { 045 this.id = id; 046 } 047 048 public String getName() { 049 return name; 050 } 051 052 public void setName(String name) { 053 this.name = name; 054 } 055 056 public String getArguments() { 057 return arguments; 058 } 059 060 public void setArguments(String arguments) { 061 this.arguments = arguments; 062 } 063 064 public Map<String, Object> getArgsMap() { 065 if (arguments == null || arguments.isEmpty()) { 066 return null; 067 } 068 069 String jsonStr = arguments.trim(); 070 071 try { 072 return JSON.parseObject(jsonStr); 073 } catch (Exception e) { 074 if (jsonStr.contains("{") && jsonStr.contains("}")) { 075 String json = jsonStr.substring(jsonStr.indexOf("{"), jsonStr.lastIndexOf("}") + 1); 076 return JSON.parseObject(json); 077 } 078 079 if (!jsonStr.startsWith("{")) jsonStr = "{" + jsonStr; 080 if (!jsonStr.endsWith("}")) jsonStr = jsonStr + "}"; 081 082 return JSON.parseObject(jsonStr); 083 } 084 } 085 086 @Override 087 public String toString() { 088 return "ToolCall{" + 089 "id='" + id + '\'' + 090 ", name='" + name + '\'' + 091 ", arguments='" + arguments + '\'' + 092 '}'; 093 } 094 095 public String toJsonString() { 096 return Maps.of("id", id) 097 .set("name", name) 098 .set("arguments", arguments) 099 .toJSON(); 100 } 101 102 /** 103 * 创建并返回当前对象的副本。 104 * 105 * @return 一个新的、内容相同但内存独立的对象 106 */ 107 @Override 108 public ToolCall copy() { 109 ToolCall copy = new ToolCall(); 110 copy.id = this.id; 111 copy.name = this.name; 112 copy.arguments = this.arguments; 113 return copy; 114 } 115}