chatWithTools method
Sends a chat request to the provider with a sequence of messages and tools.
messages
- The conversation history as a list of chat messages
tools
- Optional list of tools to use in the chat
Returns the provider's response or throws an LLMError
Implementation
@override
Future<ChatResponse> chatWithTools(
List<ChatMessage> messages,
List<Tool>? tools,
) async {
try {
final requestBody = buildRequestBody(messages, tools, false);
// Optimized trace logging with condition check
if (_logger.isLoggable(Level.FINEST)) {
_logger.finest(
'$providerName request payload: ${jsonEncode(requestBody)}');
}
// Log request headers and body for debugging
if (_logger.isLoggable(Level.FINE)) {
_logger.fine('$providerName request: POST $chatEndpoint');
_logger.fine('$providerName request headers: ${_dio.options.headers}');
}
if (_logger.isLoggable(Level.FINE)) {
_logger.fine('$providerName request body: ${jsonEncode(requestBody)}');
}
final response = await _dio.post(chatEndpoint, data: requestBody);
_logger.fine('$providerName HTTP status: ${response.statusCode}');
// Enhanced error handling with detailed information
if (response.statusCode != 200) {
_handleHttpError(response.statusCode, response.data);
}
final responseData = response.data;
if (responseData is! Map<String, dynamic>) {
throw ResponseFormatError(
'Invalid response format from $providerName API',
responseData.toString(),
);
}
return parseResponse(responseData);
} on DioException catch (e) {
throw handleDioError(e);
} catch (e) {
throw GenericError('Unexpected error: $e');
}
}