extractJson method
Extract JSON from generated text Uses C++ rac_structured_output_extract_json
Implementation
String? extractJson(String text) {
final textPtr = text.toNativeUtf8();
final jsonPtrPtr = calloc<Pointer<Utf8>>();
try {
final lib = PlatformLoader.loadCommons();
final extractJsonFn = lib.lookupFunction<
Int32 Function(Pointer<Utf8>, Pointer<Pointer<Utf8>>, Pointer<Void>),
int Function(Pointer<Utf8>, Pointer<Pointer<Utf8>>,
Pointer<Void>)>('rac_structured_output_extract_json');
final result = extractJsonFn(textPtr, jsonPtrPtr, nullptr);
if (result != RAC_SUCCESS) {
_logger.warning('extractJson failed with code $result');
return _fallbackExtractJson(text);
}
final jsonPtr = jsonPtrPtr.value;
if (jsonPtr == nullptr) {
return _fallbackExtractJson(text);
}
final jsonString = jsonPtr.toDartString();
lib.lookupFunction<Void Function(Pointer<Void>),
void Function(Pointer<Void>)>('rac_free')(jsonPtr.cast<Void>());
return jsonString;
} catch (e) {
_logger.error('extractJson exception: $e');
return _fallbackExtractJson(text);
} finally {
calloc.free(textPtr);
calloc.free(jsonPtrPtr);
}
}