How to integrate ChatGPT API into Flutter application

ChatGPT is a powerful tool that allows us to generate text that resembles human conversation. By integrating ChatGPT into our Flutter application, we can provide users with an interactive and conversational experience. Let's explore the steps to integrate ChatGPT into a Flutter application.

This Answer assumes that we have the basic knowledge of Flutter and have already set up the project and created the UI.

Add dependencies

To integrate the ChatGPT API into a Flutter application, we must utilize the HTTP package to send API requests to the ChatGPT server. We can also utilize the JSON package to handle the parsing of the JSON response received from the API.

We can open the pubspec.yaml file of our Flutter project and add the following dependencies.

dependencies:
  http: 
  json: 

Leaving the version place empty will install the latest available version of the package.

Now we can install these dependencies by running the following command.

flutter pub get

After adding the dependencies, we can import the packages into the dart file by adding the following lines of code at the top of the file.

import "package:http/http.dart" as http;
import "dart:convert";

Getting ChatGPT API key

To use the OpenAI API, we'll need an API key. We can get this from the OpenAI website after we've signed up and logged in. Don't forget to keep this key safe.

Implementation

Firstly, we will declare and assign our API key to a variable to use it at multiple places.

const String OpenAiKey = 'ChatGPT-Key';

We can declare a list called messages to store the conversation history between the user and the assistant. Each message is represented by a map containing the role ('user' or 'assistant') and the content of the message.

final List<Map<String, String>> messages = [];

In the code below, the chatGPTAPI function is defined with the Future<String> return type, indicating that it will return a String value in the future. It takes a prompt parameter representing the user's message.

Future<String> chatGPTAPI(String prompt) async {
// We can write code related to this function here.
}

We add the user's message to the messages list by appending a map with the role 'user' and the content as prompt.

messages.add({
'role': 'user',
'content': prompt,
});

Within a try-catch block, we send an HTTP POST request to the ChatGPT API endpoint using the http.post method. We include the required headers and the body, which contains the Content-Type.The Content-Type describes the type in which we want our response to be. Authorization is where we define our API key and model to use gpt-3.5-turbo , and the conversation history is stored in messages.

try {
final res = await http.post(
Uri.parse('https://api.openai.com/v1/chat/completions'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $OpenAiKey',
},
body: jsonEncode({
"model": "gpt-3.5-turbo",
"messages": messages,
}),
);
// Code continues

If the response's status code is 200 (indicating a successful request), we extract the generated response from the API's JSON response. The content is accessed using jsonDecode(res.body)['choices'][0]['message']['content'] and stored in the content variable. We trim the content to remove any leading or trailing whitespace, add it to the messages list to maintain the conversation with role of assistant, and then content is returned.

if (res.statusCode == 200) {
String content =
jsonDecode(res.body)['choices'][0]['message']['content'];
content = content.trim();
messages.add({
'role': 'assistant',
'content': content,
});
return content;
}
else{
return 'An internal error occurred';
}

In the code below, we have put together the code explained above.

final List<Map<String, String>> messages = [];
const String OpenAiKey = 'ChatGPT-Key';
Future<String> chatGPTAPI(String prompt) async {
messages.add({
'role': 'user',
'content': prompt,
});
try {
final res = await http.post(
Uri.parse('https://api.openai.com/v1/chat/completions'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $nOpenAiKey',
},
body: jsonEncode({
"model": "gpt-3.5-turbo",
"messages": messages,
}),
);
if (res.statusCode == 200) {
String content =
jsonDecode(res.body)['choices'][0]['message']['content'];
content = content.trim();
messages.add({
'role': 'assistant',
'content': content,
});
return content;
}
return 'An internal error occurred';
} catch (e) {
return e.toString();
}
}

The code above will only execute when we will replace "ChatGPT-key" with our secret OpenAI API key. We can learn how to get our API key here.

Conclusion

By integrating ChatGPT into our Flutter application, we can harness the power of AI to generate text that resembles human conversation. This integration enables us to provide users with an interactive and engaging experience. By using this function, we can create a fully functional virtual assistant app.

Copyright ©2024 Educative, Inc. All rights reserved