48 lines
1.6 KiB
Dart
48 lines
1.6 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:shelf/shelf.dart';
|
|
import 'package:shelf/shelf_io.dart' as shelf_io;
|
|
import 'package:shelf_router/shelf_router.dart';
|
|
|
|
Future<void> main(List<String> args) async {
|
|
final apiKey = Platform.environment['OPENROUTER_API_KEY'];
|
|
final baseUrl = Platform.environment['OPENROUTER_BASE_URL'] ?? 'https://openrouter.ai/api/v1';
|
|
|
|
final router = Router()
|
|
..post('/v1/chat/completions', (Request request) async {
|
|
if (apiKey == null || apiKey.isEmpty) {
|
|
return Response(500, body: 'OPENROUTER_API_KEY is not set');
|
|
}
|
|
|
|
final body = await request.readAsString();
|
|
final upstream = await http.post(
|
|
Uri.parse('$baseUrl/chat/completions'),
|
|
headers: {
|
|
'Authorization': 'Bearer $apiKey',
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
'HTTP-Referer': 'http://localhost:8080',
|
|
'X-Title': 'clawd_code backend',
|
|
},
|
|
body: body,
|
|
);
|
|
|
|
return Response(
|
|
upstream.statusCode,
|
|
body: upstream.body,
|
|
headers: {
|
|
'content-type': upstream.headers['content-type'] ?? 'application/json',
|
|
},
|
|
);
|
|
})
|
|
..post('/v1/models', (Request request) => Response(405, body: 'Method not allowed'))
|
|
..all('/<ignored|.*>', (Request request, String ignored) => Response.notFound('Not found'));
|
|
|
|
final handler = Pipeline()
|
|
.addMiddleware(logRequests())
|
|
.addHandler(router.call);
|
|
|
|
final server = await shelf_io.serve(handler, InternetAddress.anyIPv4, 8080);
|
|
stdout.writeln('Serving at http://${server.address.host}:${server.port}');
|
|
}
|