rewrite method
Asks the model to rewrite text according to instruction.
Plain text in, plain text out — no tool call, and nothing is executed as a result. Used to polish a generated changelog, where the model's job is editorial rather than deciding what the CLI does.
Throws AiException on transport or protocol failure.
Implementation
@override
Future<String> rewrite({
required String instruction,
required String text,
}) async {
final body = await post(
'${config.baseUrl}/v1/messages',
{
'model': config.model,
'max_tokens': config.maxTokens,
'system': instruction,
'messages': [
{
'role': 'user',
'content': [
{'type': 'text', 'text': text},
],
},
],
},
{
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
if (config.hasApiKey) 'x-api-key': config.apiKey,
},
);
if (body['stop_reason'] == 'refusal') {
throw AiException('the model declined to rewrite this text');
}
if (body['stop_reason'] == 'max_tokens') {
throw AiException(
'the reply was cut off by the token limit — raise `max-tokens` '
'(currently ${config.maxTokens}) and try again',
);
}
final content = body['content'];
if (content is! List) throw AiException('$name returned no content');
final buffer = StringBuffer();
for (final block in content) {
if (block is Map && block['type'] == 'text') {
buffer.write(block['text'] ?? '');
}
}
final result = buffer.toString().trim();
if (result.isEmpty) throw AiException('$name returned nothing to use');
return result;
}