Last reviewed: November 20, 2026 (Asia/Shanghai); references fetched November 19, 2026 UTC.
Build the client around one reusable http.Client: read COMETAPI_API_KEY and COMETAPI_MODEL from the process environment, construct a JSON request with jsonEncode, stream the response into a byte-capped buffer, and parse it only after the HTTP status and media type pass. Return assistant text only when the response is exactly one completed chat choice. This gives a Dart command-line or server process a small, inspectable boundary without putting a key in source code or treating HTTP 200 as proof of a usable answer.
The example targets a non-streaming text request. It intentionally rejects refusals, tool calls, empty content, malformed UTF-8, extra choices, and bodies larger than the local limit. Those are application decisions layered on the provider contract; change them only with tests and a reviewed product requirement.
Install the Dart HTTP client
Create a native Dart console project and add the maintained http package
:
dart create -t console-full comet_dart_demo
cd comet_dart_demo
dart pub add http
The package’s Client API
is Future-based and exposes both convenience methods and send. The latter returns a streamed response, which lets this client count bytes as they arrive instead of handing an unbounded body directly to a JSON decoder. Keep the generated pubspec.lock with the application so an upgrade is an explicit change.
The Dart Platform.environment reference
defines the environment as a map of string keys to string values. The program below reads two names at startup and fails before dispatch when either is missing. Set them through the secret mechanism used by the process manager; do not paste a credential into a Dart file, a shell history entry, or a copied diagnostic.
Build a bounded chat request
Replace lib/comet_client.dart with this client. The endpoint is the documented Chat Completions path:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
const _endpoint = 'https://api.cometapi.com/v1/chat/completions';
const _maxPromptBytes = 8 * 1024;
const _maxResponseBytes = 1024 * 1024;
const _maxDiscardBytes = 64 * 1024;
class CometException implements Exception {
const CometException(this.code, [this.status]);
final String code;
final int? status;
@override
String toString() => status == null ? code : '$code ($status)';
}
class CometClient {
CometClient({
required String key,
required String model,
http.Client? httpClient,
Duration headerTimeout = const Duration(seconds: 30),
Duration bodyTimeout = const Duration(seconds: 30),
}) : _key = key,
_model = model,
_http = httpClient ?? http.Client(),
_headerTimeout = headerTimeout,
_bodyTimeout = bodyTimeout {
if (key.trim().isEmpty || model.trim().isEmpty) {
throw const CometException('missing_configuration');
}
}
factory CometClient.fromEnvironment() {
final env = Platform.environment;
final key = env['COMETAPI_API_KEY'];
final model = env['COMETAPI_MODEL'];
if (key == null || model == null) {
throw const CometException('missing_configuration');
}
return CometClient(key: key, model: model);
}
final String _key;
final String _model;
final http.Client _http;
final Duration _headerTimeout;
final Duration _bodyTimeout;
Future<String> complete(String prompt) async {
if (prompt.trim().isEmpty || utf8.encode(prompt).length > _maxPromptBytes) {
throw const CometException('invalid_prompt');
}
final payload = jsonEncode(<String, dynamic>{
'model': _model,
'messages': <Map<String, String>>[
<String, String>{'role': 'user', 'content': prompt},
],
'stream': false,
});
final request = http.Request('POST', Uri.parse(_endpoint))
..headers.addAll(<String, String>{
'Authorization': 'Bearer $_key',
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
})
..body = payload;
late final http.StreamedResponse response;
try {
response = await _http.send(request).timeout(_headerTimeout);
} on TimeoutException {
// Future.timeout does not cancel the source future. Closing the client is
// the best-effort transport cancellation, so discard this client after it.
_http.close();
throw const CometException('transport_timeout');
} on http.ClientException {
throw const CometException('transport_failed');
}
final mediaType = response.headers['content-type']
?.split(';').first.trim().toLowerCase();
if (response.statusCode != 200) {
await _discard(response.stream);
throw CometException('upstream_http', response.statusCode);
}
if (mediaType != 'application/json') {
await _discard(response.stream);
throw const CometException('unexpected_media_type');
}
final bytes = await _readBounded(
response.stream,
limit: _maxResponseBytes,
overflowCode: 'response_too_large',
);
late final String decodedText;
try {
decodedText = utf8.decode(bytes, allowMalformed: false);
} on FormatException {
throw const CometException('invalid_response_utf8');
}
return acceptCompletionJson(decodedText);
}
Future<List<int>> _readBounded(
Stream<List<int>> stream, {
required int limit,
required String overflowCode,
}) {
final completer = Completer<List<int>>();
final bytes = <int>[];
StreamSubscription<List<int>>? subscription;
Timer? timer;
void cancelSubscription() {
final active = subscription;
if (active != null) unawaited(active.cancel());
}
void fail(Object error, StackTrace stack) {
if (completer.isCompleted) return;
timer?.cancel();
completer.completeError(error, stack);
cancelSubscription();
}
subscription = stream.listen(
(chunk) {
if (bytes.length + chunk.length > limit) {
fail(CometException(overflowCode), StackTrace.current);
return;
}
bytes.addAll(chunk);
},
onError: (Object error, StackTrace stack) {
fail(const CometException('response_read_failed'), stack);
},
onDone: () {
if (completer.isCompleted) return;
timer?.cancel();
completer.complete(bytes);
},
cancelOnError: false,
);
timer = Timer(_bodyTimeout, () {
fail(const CometException('response_body_timeout'), StackTrace.current);
});
return completer.future;
}
Future<void> _discard(Stream<List<int>> stream) async {
try {
await _readBounded(
stream,
limit: _maxDiscardBytes,
overflowCode: 'rejected_response_too_large',
);
} on CometException {
// The status or media-type decision remains the caller-facing result.
}
}
void close() => _http.close();
}
String acceptCompletionJson(String json) {
late final dynamic decoded;
try {
decoded = jsonDecode(json);
} on FormatException {
throw const CometException('invalid_response_json');
}
return _acceptText(decoded);
}
String _acceptText(dynamic decoded) {
if (decoded is! Map<String, dynamic> ||
decoded['object'] != 'chat.completion') {
throw const CometException('invalid_completion_envelope');
}
final choices = decoded['choices'];
if (choices is! List<dynamic> || choices.length != 1) {
throw const CometException('invalid_completion_choices');
}
final choice = choices.single;
if (choice is! Map<String, dynamic> ||
choice['finish_reason'] != 'stop') {
throw const CometException('unaccepted_finish_reason');
}
final message = choice['message'];
if (message is! Map<String, dynamic> ||
message['role'] != 'assistant' ||
message['refusal'] != null ||
message['tool_calls'] != null) {
throw const CometException('unaccepted_assistant_message');
}
final content = message['content'];
if (content is! String || content.trim().isEmpty) {
throw const CometException('missing_assistant_text');
}
return content;
}
The CometAPI chat reference
documents POST /v1/chat/completions, bearer authentication, message roles, the chat.completion envelope, and finish reasons. The request keeps the endpoint literal inside the code and leaves the model ID in trusted configuration. jsonEncode handles quotes, newlines, and Unicode in the prompt; hand-built JSON would make those cases easy to corrupt.
send returns a streamed response
, whose body is exposed as a byte stream by StreamedResponse
. The media-type expression uses Dart’s supported split(';').first form. _readBounded counts chunks before UTF-8 decoding and JSON parsing, cancels the stream subscription on overflow, and applies a total body-completion timer. Rejected status and media-type responses use a separate 64 KiB disposal ceiling and the same timer, so cleanup cannot wait forever.
The status check disposes of an unexpected body through the bounded helper without exposing it in an exception. The content-type check uses split(';').first, accepts parameters such as a charset, and rejects HTML and server-sent events. Header timeout closes this client as a best-effort transport cancellation; the body timer explicitly cancels its stream subscription. The code has no automatic retry. A timeout or lost connection leaves the remote attempt’s outcome uncertain, so reconcile the operation before deciding whether to send another request.
Validate completion before returning text
The second half of the client is deliberately stricter than jsonDecode alone. The Dart JSON API
returns a dynamic value: a syntactically valid array, object, number, or string can all be decoded. acceptCompletionJson checks the object type, exactly one choice, the assistant role, stop completion, and a non-empty string before returning text. It rejects refusal and tool_calls even when those fields are well formed because this small caller has no policy for them. The public wrapper also lets a credential-free fixture import the same acceptance policy without reaching into Dart’s library-private _acceptText helper.
That separation makes later changes visible. A feature that adds tools should introduce a separate authorization and execution boundary instead of weakening this text-only validator. A feature that accepts length should decide how partial output is represented and reviewed rather than silently treating it as complete.
Run credential-free fixtures
The public acceptCompletionJson helper makes the completion policy importable from an offline fixture. The CometClient constructor also accepts an http.Client, so a test can supply a synthetic streamed response without a key or network request. Add bin/check_fixtures.dart:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../lib/comet_client.dart';
class FixtureClient extends http.BaseClient {
FixtureClient(this.response);
final http.StreamedResponse response;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async => response;
}
http.StreamedResponse fixtureResponse(
String body, {
int statusCode = 200,
Stream<List<int>>? stream,
}) {
return http.StreamedResponse(
stream ?? Stream<List<int>>.value(utf8.encode(body)),
statusCode,
headers: const <String, String>{'content-type': 'application/json'},
);
}
void requireValue(bool condition, String message) {
if (!condition) throw StateError(message);
}
void expectSyncCode(void Function() action, String expected) {
try {
action();
throw StateError('expected $expected');
} on CometException catch (error) {
requireValue(error.code == expected, '${error.code} != $expected');
}
}
Future<void> expectCode(
Future<String> Function() action,
String expected,
) async {
try {
await action();
throw StateError('expected $expected');
} on CometException catch (error) {
requireValue(error.code == expected, '${error.code} != $expected');
}
}
CometClient clientFor(http.StreamedResponse response, {Duration? bodyTimeout}) {
return CometClient(
key: 'fixture-key',
model: 'fixture-model',
httpClient: FixtureClient(response),
headerTimeout: const Duration(milliseconds: 100),
bodyTimeout: bodyTimeout ?? const Duration(milliseconds: 100),
);
}
Future<void> main() async {
const good = '{"object":"chat.completion","choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"Fixture answer."}}]}';
requireValue(acceptCompletionJson(good) == 'Fixture answer.', 'accepted text');
expectSyncCode(
() => acceptCompletionJson(good.replaceFirst('"stop"', '"length"')),
'unaccepted_finish_reason',
);
expectSyncCode(
() => acceptCompletionJson(good.replaceFirst('Fixture answer.', '')),
'missing_assistant_text',
);
expectSyncCode(() => acceptCompletionJson('[]'), 'invalid_completion_envelope');
final oversized = List<int>.filled(1024 * 1024 + 1, 65);
final largeClient = clientFor(
fixtureResponse('', stream: Stream<List<int>>.value(oversized)),
);
try {
await expectCode(() => largeClient.complete('fixture'), 'response_too_large');
} finally {
largeClient.close();
}
final stalledBody = StreamController<List<int>>();
final stalledClient = clientFor(
fixtureResponse('', stream: stalledBody.stream),
bodyTimeout: const Duration(milliseconds: 20),
);
try {
await expectCode(() => stalledClient.complete('fixture'), 'response_body_timeout');
} finally {
await stalledBody.close();
stalledClient.close();
}
final rejectedBody = StreamController<List<int>>();
final rejectedClient = clientFor(
http.StreamedResponse(
rejectedBody.stream,
503,
headers: const <String, String>{'content-type': 'text/plain'},
),
bodyTimeout: const Duration(milliseconds: 20),
);
try {
await expectCode(() => rejectedClient.complete('fixture'), 'upstream_http');
} finally {
await rejectedBody.close();
rejectedClient.close();
}
final rejectedLarge = clientFor(
http.StreamedResponse(
Stream<List<int>>.value(List<int>.filled(64 * 1024 + 1, 65)),
503,
headers: const <String, String>{'content-type': 'text/plain'},
),
);
try {
await expectCode(() => rejectedLarge.complete('fixture'), 'upstream_http');
} finally {
rejectedLarge.close();
}
print('fixtures passed');
}
Run it without COMETAPI_API_KEY, COMETAPI_MODEL, or network access:
dart run bin/check_fixtures.dart
The expected output is fixtures passed. The script checks accepted text, truncated output, empty content, an invalid envelope, an oversized streamed body, a body that never completes, a rejected response whose disposal stalls, and a rejected response larger than the 64 KiB disposal ceiling. FixtureClient is a BaseClient whose only transport method returns the supplied StreamedResponse; each case gets a fresh instance because a response stream is single-use.
The fixture code uses a separate public parser because _acceptText is library-private in Dart. The live CLI remains credential-dependent, while this command proves the local request and acceptance decisions first. After the fixture command passes, run the CLI only with runtime-injected credentials and a reviewed model.
For that live call, add bin/comet_dart_demo.dart:
import 'dart:io';
import '../lib/comet_client.dart';
Future<void> main(List<String> args) async {
if (args.length != 1 || args.single.trim().isEmpty) {
stderr.writeln('usage: dart run bin/comet_dart_demo.dart "prompt"');
exitCode = 2;
return;
}
late final CometClient client;
try {
client = CometClient.fromEnvironment();
} on CometException catch (error) {
stderr.writeln('configuration failed: ${error.code}');
exitCode = 2;
return;
}
try {
stdout.writeln(await client.complete(args.single));
} on CometException catch (error) {
stderr.writeln('request failed: ${error.code}');
exitCode = 1;
} finally {
client.close();
}
}
Set the environment variables through the runtime’s secret store and pass a harmless prompt:
export COMETAPI_API_KEY
export COMETAPI_MODEL
dart run bin/comet_dart_demo.dart "Reply with one short sentence about idempotency."
For a second local review path, compare this client with the site’s chat completion contract smoke tests , then use the credential boundary guide before putting the process under a scheduler.
Failure paths and next action
missing_configuration means the process never dispatched. Check the environment injection and model selection privately. invalid_prompt is a caller error. unexpected_media_type, invalid_response_json, and the completion codes describe an upstream response that this feature cannot accept; preserve only the category needed for an operator decision. transport_timeout bounds waiting for response headers and closes this client as a best-effort cancellation because Future.timeout does not cancel its source operation. Recreate the client before another attempt.
response_body_timeout is a total body-completion budget. _readBounded cancels its stream subscription on timeout or overflow, and rejected statuses and media types use a separate 64 KiB disposal ceiling with the same timer. A timeout or lost connection still leaves the remote attempt’s outcome uncertain, so reconcile the operation before deciding whether to send another request.
The reusable http.Client keeps connection ownership in one object and must be closed when the process is done. Do not create a client for every prompt in a long-running server, and do not share this key-bearing client with browser code. The byte ceilings and validator protect the boundary, but they do not establish factual accuracy, quota availability, or idempotency. Add request identity and reconciliation before adding retries around an uncertain attempt.
Sources checked
These six primary public references returned HTTP 200 when fetched on November 19, 2026 UTC. They support the provider contract and the Dart APIs used in the example:
- CometAPI: Create a chat completion — endpoint, bearer authentication, message roles, response envelope, and finish outcomes.
- Dart API:
Platform.environment— process environment map semantics. - Dart API:
jsonDecode— dynamic decoded result types and JSON parsing behavior. - Dart
http: Client — reusable Future-based client and close lifecycle. - Dart
http: Client.send — streamed response return type. - Dart
http: StreamedResponse — response status, headers, and byte stream.
The CometAPI page is the current provider reference. The Dart and package pages are maintained API references; their access date records the checked contract, not a product release. Local byte limits, timeout values, and the text-only acceptance policy are explicit choices for this example.
Reader next step
Run the fixture matrix without a credential, inspect the serialized request shape, and confirm the selected model’s Chat Completions capability. Then perform one authorized staging request, record only the outcome category and timing, and decide how your service will reconcile an uncertain timeout before enabling retries.