|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:dartantic_ai/dartantic_ai.dart' as dartantic; |
| 4 | + |
| 5 | +import 'api_key.dart'; |
| 6 | + |
| 7 | +/// An abstract interface for AI clients. |
| 8 | +abstract interface class AiClient { |
| 9 | + /// Sends a message stream request to the AI service. |
| 10 | + /// |
| 11 | + /// [prompt] is the user's message. |
| 12 | + /// [history] is the conversation history. |
| 13 | + Stream<String> sendStream( |
| 14 | + String prompt, { |
| 15 | + required List<dartantic.ChatMessage> history, |
| 16 | + }); |
| 17 | + |
| 18 | + /// Dispose of resources. |
| 19 | + void dispose(); |
| 20 | +} |
| 21 | + |
| 22 | +/// An implementation of [AiClient] using `package:dartantic_ai`. |
| 23 | +class DartanticAiClient implements AiClient { |
| 24 | + DartanticAiClient({String? modelName}) { |
| 25 | + final String apiKey = apiKeyForEval(); |
| 26 | + _provider = dartantic.GoogleProvider(apiKey: apiKey); |
| 27 | + _agent = dartantic.Agent.forProvider( |
| 28 | + _provider, |
| 29 | + chatModelName: modelName ?? 'gemini-3-flash-preview', |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + late final dartantic.GoogleProvider _provider; |
| 34 | + late final dartantic.Agent _agent; |
| 35 | + |
| 36 | + @override |
| 37 | + Stream<String> sendStream( |
| 38 | + String prompt, { |
| 39 | + required List<dartantic.ChatMessage> history, |
| 40 | + }) async* { |
| 41 | + final Stream<dartantic.ChatResult<String>> stream = _agent.sendStream( |
| 42 | + prompt, |
| 43 | + history: history, |
| 44 | + ); |
| 45 | + |
| 46 | + await for (final result in stream) { |
| 47 | + if (result.output.isNotEmpty) { |
| 48 | + yield result.output; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @override |
| 54 | + void dispose() { |
| 55 | + // Dartantic Agent/Provider doesn't strictly require disposal currently, |
| 56 | + // but good to have the hook. |
| 57 | + } |
| 58 | +} |
0 commit comments