-
Notifications
You must be signed in to change notification settings - Fork 0
API AIResponse
Represents a response from an AI model.
class AIResponse with EquatableMixin {
const AIResponse({
required String id,
required List<Content> content,
required FinishReason finishReason,
List<ToolCallContent>? toolCalls,
Usage? usage,
String? model,
AIProvider? provider,
DateTime? createdAt,
Map<String, dynamic>? metadata,
});
}final String idUnique identifier for this response.
final List<Content> contentThe generated content as a list of Content objects.
final FinishReason finishReasonWhy the model stopped generating.
enum FinishReason {
stop, // Normal completion
maxTokens, // Hit token limit
contentFilter, // Blocked by safety
toolCalls, // Model called tools
unknown, // Unknown reason
}final List<ToolCallContent>? toolCallsTool calls made by the model (if any).
final Usage? usageToken usage statistics.
final String? modelThe model that generated this response.
final AIProvider? providerThe provider that generated this response.
final DateTime? createdAtWhen this response was created.
final Map<String, dynamic>? metadataAdditional metadata from the provider.
String get textGets the combined text content of the response.
final response = await ai.chat('Hello');
print(response.text); // "Hello! How can I help you?"bool get hasToolCallsWhether this response contains tool calls.
if (response.hasToolCalls) {
for (final call in response.toolCalls!) {
// Handle tool call
}
}bool get wasMaxTokensWhether the response was cut off due to max tokens.
if (response.wasMaxTokens) {
print('Response was truncated');
}bool get wasFilteredWhether the response was filtered for safety.
if (response.wasFiltered) {
print('Content was filtered');
}Creates a copy with updated fields.
AIResponse copyWith({
String? id,
List<Content>? content,
FinishReason? finishReason,
List<ToolCallContent>? toolCalls,
Usage? usage,
String? model,
AIProvider? provider,
DateTime? createdAt,
Map<String, dynamic>? metadata,
})Converts to a JSON-serializable map.
Map<String, dynamic> toJson()final json = response.toJson();
// {
// 'id': 'resp_123',
// 'content': [...],
// 'finish_reason': 'stop',
// 'usage': {...},
// ...
// }Token usage statistics.
class Usage {
final int promptTokens;
final int completionTokens;
final int totalTokens;
}final usage = response.usage;
if (usage != null) {
print('Prompt tokens: ${usage.promptTokens}');
print('Completion tokens: ${usage.completionTokens}');
print('Total tokens: ${usage.totalTokens}');
}final response = await ai.chat('What is Dart?');
// Get text
print('Answer: ${response.text}');
// Check finish reason
print('Finished: ${response.finishReason}');
// Token usage
if (response.usage != null) {
print('Tokens used: ${response.usage!.totalTokens}');
}final response = await ai.chatWithTools(
'What is the weather?',
tools: [weatherTool],
);
if (response.hasToolCalls) {
for (final call in response.toolCalls!) {
print('Tool: ${call.name}');
print('Args: ${call.arguments}');
// Execute and submit result
final result = await executeToolCall(call);
await ai.submitToolResult(
toolCallId: call.id,
name: call.name,
result: result,
);
}
} else {
print(response.text);
}final response = await ai.chat(message);
switch (response.finishReason) {
case FinishReason.stop:
print('Completed normally');
break;
case FinishReason.maxTokens:
print('Response was truncated');
break;
case FinishReason.contentFilter:
print('Content was filtered');
break;
case FinishReason.toolCalls:
print('Waiting for tool results');
break;
case FinishReason.unknown:
print('Unknown finish reason');
break;
}final response = await ai.chat('Hello');
// Export to JSON
final json = response.toJson();
// Save to file/database
await saveResponse(json);For streaming responses, the SDK emits StreamChunk objects.
class StreamChunk {
final StreamEventType type;
final String? delta;
final ToolCallContent? toolCallDelta;
final FinishReason? finishReason;
final Usage? usage;
final Object? error;
final Map<String, dynamic>? metadata;
// Convenience getters
bool get isStart;
bool get isDelta;
bool get isDone;
bool get isError;
}enum StreamEventType {
start, // Stream started
delta, // Text chunk
toolCallDelta, // Tool call chunk
done, // Stream completed
error, // Error occurred
}await for (final chunk in ai.streamChat('Tell me a story')) {
if (chunk.isStart) {
print('Starting...');
}
if (chunk.isDelta) {
stdout.write(chunk.delta);
}
if (chunk.isDone) {
print('\n\nDone!');
print('Finish reason: ${chunk.finishReason}');
print('Total tokens: ${chunk.usage?.totalTokens}');
}
if (chunk.isError) {
print('Error: ${chunk.error}');
}
}- API-FlutterAI - Main class reference
- Streaming - Streaming guide
- Function Calling - Tool calls
Getting Started
Core Concepts
Advanced Features
API Reference
Examples
Other