generateResponse method
Generates a response from the LLM based on the given prompt.
prompt - The input prompt to send to the model.
context - Optional list of context strings to prepend to the prompt.
Returns the generated text response.
Throws Exception if the request fails.
Implementation
@override
Future<String> generateResponse(String prompt,
{List<String>? context}) async {
final fullPrompt =
context != null ? '${context.join('\n')}\n\n$prompt' : prompt;
final url = Uri.parse(
'https://generativelanguage.googleapis.com/v1beta/models/$modelName:generateContent');
final response = await HttpUtils.postWithRetry(
url,
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': apiKey,
},
body: jsonEncode({
'contents': [
{
'parts': [
{'text': fullPrompt}
]
}
]
}),
timeout: timeout,
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
try {
return data['candidates'][0]['content']['parts'][0]['text'] as String;
} catch (e) {
throw Exception('Error parsing Gemini response: $e');
}
} else {
throw Exception(
'Failed to generate response from Gemini: ${response.body}');
}
}