import 'dart:convert'; /// 函数服务 /// 仅实现各种功能函数,不包含AI交互逻辑 class FunctionService { /// 天气查询工具定义 /// 返回一个可直接用于tools参数的天气查询工具定义 static Map getWeatherToolDefinition() { return { 'type': 'function', 'function': { 'name': 'get_current_weather', 'description': '获取指定地点的当前天气信息', 'parameters': { 'type': 'object', 'properties': { 'location': { 'type': 'string', 'description': '地理位置,例如:北京市', }, 'unit': { 'type': 'string', 'description': '温度单位', 'enum': ['celsius', 'fahrenheit'], }, }, 'required': ['location'], }, }, }; } /// 模拟天气API实现 /// 返回一个模拟的天气信息,实际应用中应该调用真实的天气API static Future> getWeatherInfo(Map args) async { final location = args['location'] ?? '未知地点'; final unit = args['unit'] ?? 'celsius'; // 在实际应用中,这里应该调用真实的天气API return { 'location': location, 'temperature': unit == 'celsius' ? '25°C' : '77°F', 'conditions': '晴转多云', 'humidity': '55%', 'wind': '西南风 3级', 'date': DateTime.now().toString().split(' ')[0], }; } /// 解析函数调用参数 /// 从AI响应中提取函数调用参数 static Map parseFunctionCallArguments(Map functionCallResponse) { if (functionCallResponse['tool_calls'] == null || functionCallResponse['tool_calls'].isEmpty) { throw FunctionServiceException('No tool calls found in response'); } final toolCall = functionCallResponse['tool_calls'][0]; if (toolCall['function'] == null || toolCall['function']['arguments'] == null) { throw FunctionServiceException('Invalid function call format'); } try { return json.decode(toolCall['function']['arguments']); } catch (e) { throw FunctionServiceException('Failed to parse function arguments: $e'); } } /// 获取函数调用ID和名称 /// 用于构建工具响应消息 static Map getFunctionCallInfo(Map functionCallResponse) { if (functionCallResponse['tool_calls'] == null || functionCallResponse['tool_calls'].isEmpty) { throw FunctionServiceException('No tool calls found in response'); } final toolCall = functionCallResponse['tool_calls'][0]; if (toolCall['id'] == null || toolCall['function'] == null || toolCall['function']['name'] == null) { throw FunctionServiceException('Invalid function call format'); } return { 'id': toolCall['id'], 'name': toolCall['function']['name'], }; } } /// 函数调用服务异常类 class FunctionServiceException implements Exception { final String message; FunctionServiceException(this.message); @override String toString() => message; }