Skip to content

API AIResponse

Amayyas edited this page Dec 5, 2025 · 1 revision

API Reference: AIResponse

Represents a response from an AI model.

Class Definition

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,
  });
}

Properties

id

final String id

Unique identifier for this response.


content

final List<Content> content

The generated content as a list of Content objects.


finishReason

final FinishReason finishReason

Why the model stopped generating.

enum FinishReason {
  stop,          // Normal completion
  maxTokens,     // Hit token limit
  contentFilter, // Blocked by safety
  toolCalls,     // Model called tools
  unknown,       // Unknown reason
}

toolCalls

final List<ToolCallContent>? toolCalls

Tool calls made by the model (if any).


usage

final Usage? usage

Token usage statistics.


model

final String? model

The model that generated this response.


provider

final AIProvider? provider

The provider that generated this response.


createdAt

final DateTime? createdAt

When this response was created.


metadata

final Map<String, dynamic>? metadata

Additional metadata from the provider.


Computed Properties

text

String get text

Gets the combined text content of the response.

final response = await ai.chat('Hello');
print(response.text); // "Hello! How can I help you?"

hasToolCalls

bool get hasToolCalls

Whether this response contains tool calls.

if (response.hasToolCalls) {
  for (final call in response.toolCalls!) {
    // Handle tool call
  }
}

wasMaxTokens

bool get wasMaxTokens

Whether the response was cut off due to max tokens.

if (response.wasMaxTokens) {
  print('Response was truncated');
}

wasFiltered

bool get wasFiltered

Whether the response was filtered for safety.

if (response.wasFiltered) {
  print('Content was filtered');
}

Methods

copyWith

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,
})

toJson

Converts to a JSON-serializable map.

Map<String, dynamic> toJson()
final json = response.toJson();
// {
//   'id': 'resp_123',
//   'content': [...],
//   'finish_reason': 'stop',
//   'usage': {...},
//   ...
// }

Usage Class

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}');
}

Examples

Basic Usage

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}');
}

Handling Tool Calls

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);
}

Checking Completion

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;
}

Exporting Response

final response = await ai.chat('Hello');

// Export to JSON
final json = response.toJson();

// Save to file/database
await saveResponse(json);

StreamChunk

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;
}

Stream Event Types

enum StreamEventType {
  start,          // Stream started
  delta,          // Text chunk
  toolCallDelta,  // Tool call chunk
  done,           // Stream completed
  error,          // Error occurred
}

Streaming Example

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}');
  }
}

Related

Clone this wiki locally