I created the project but in the end this error appeared for me
and android studio told me it can not refresh access token
this error message Unhandled Exception: Exception: ChatGPT failed to refresh auth token: Exception: Failed to refresh access token
what is the solution?
this code inside chat_gpt.dart
Future<String> _refreshAccessToken() async {
final cachedAccessToken = this._accessTokenCache['KEY_ACCESS_TOKEN'];
if (cachedAccessToken != null) {
return cachedAccessToken;
}
try {
final res =
await http.get(Uri.parse('$apiBaseUrl/auth/session'), headers: {
'cookie': '__Secure-next-auth.session-token=$sessionToken',
'user-agent': userAgent,
});
if (res.statusCode != 200) {
throw Exception('Failed to refresh access token');
}
final accessToken = jsonDecode(res.body)['accessToken'];
if (accessToken == null) {
throw Exception(
'Failed to refresh access token, token in response is null');
}
_accessTokenCache['KEY_ACCESS_TOKEN'] = accessToken;
return accessToken;
} catch (err) {
throw Exception('ChatGPT failed to refresh auth token: $err');
}
}
and this code is in sendMessage function
Future<ChatResponse> sendMessage(
String message, {
String? conversationId,
String? parentMessageId,
}) async {
final accessToken = await _refreshAccessToken();
parentMessageId ??= Uuid().v4();
final body = ConversationJSONBody(
action: 'next',
conversationId: conversationId,
messages: [
Prompt(
content: PromptContent(contentType: 'text', parts: [message]),
id: Uuid().v4(),
role: 'user',
)
],
model: 'text-davinci-002-render',
parentMessageId: parentMessageId,
).toJson();
final url = '$backendApiBaseUrl/conversation';
final response = await http.post(
Uri.parse(url),
headers: {
'Authorization': 'Bearer ${accessToken}',
'Content-Type': 'application/json',
'user-agent': userAgent,
},
body: jsonEncode(body),
);
if (response.statusCode != 200) {
if (response.statusCode == 429) {
throw Exception('Rate limited');
} else {
throw Exception('Failed to send message');
}
} else if (_errorMessages.contains(response.body)) {
throw Exception('OpenAI returned an error');
}
String longestLine =
response.body.split('\n').reduce((a, b) => a.length > b.length ? a : b);
var result = longestLine.replaceFirst('data: ', '');
var resultJson = jsonDecode(result);
var messageResult = ConversationResponseEvent.fromJson(resultJson);
var lastResult = messageResult.message?.content.parts.first;
if (lastResult == null) {
throw Exception('No response from OpenAI');
} else {
return ChatResponse(
message: lastResult,
messageId: messageResult.message!.id,
conversationId: messageResult.conversationId,
);
}
}