How to Create a Chatbot Using OpenAI in Flutter Ap?

aaronreddix

Aaron Reddix

Posted on July 22, 2024

How to Create a Chatbot Using OpenAI in Flutter Ap?

Creating a chatbot is one of the most popular and practical applications of AI in mobile apps. In this example, we'll build a simple chatbot using Flutter and OpenAI. The chatbot will interact with users by generating responses based on user input.

Prerequisites

Ensure you have the following set up before proceeding:

1. Flutter Environment: Follow the official Flutter installation guide to set up your development environment.

2. OpenAI API Key: Sign up at OpenAI to get your API key.

Step 1: Set Up Your Flutter Project

1. Create a New Flutter Project: Open your terminal and run:

flutter create chatbot_app
cd chatbot_app
Enter fullscreen mode Exit fullscreen mode

2. Open the Project in Your Code Editor: If you have Visual Studio Code, you can use:

code .
Enter fullscreen mode Exit fullscreen mode

3. Add Dependencies: Open your pubspec.yaml file and add the http package under dependencies. This package will help us make network requests.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
Enter fullscreen mode Exit fullscreen mode

4. Install the Package: Run the following command to get the newly added dependency:

flutter pub get
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the OpenAI Service

1. Create a new file: lib/openai_service.dart.

Add the following code to handle the interaction with the OpenAI API:

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

class OpenAIService {
  final String apiKey = 'YOUR_API_KEY';

  Future<String> generateResponse(String prompt) async {
    final response = await http.post(
      Uri.parse('https://api.openai.com/v1/engines/davinci-codex/completions'),
      headers: {
        'Authorization': 'Bearer $apiKey',
        'Content-Type': 'application/json',
      },
      body: jsonEncode({
        'prompt': prompt,
        'max_tokens': 150,
      }),
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      return data['choices'][0]['text'];
    } else {
      throw Exception('Failed to generate response');
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_API_KEY' with your actual OpenAI API key.

Step 3: Build the Chatbot UI

Open lib/main.dart and replace its contents with the following code to build the user interface of the chatbot:

import 'package:flutter/material.dart';
import 'openai_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final OpenAIService openAIService = OpenAIService();
  final TextEditingController _controller = TextEditingController();
  List<Map<String, String>> messages = [];

  void _sendMessage() async {
    final text = _controller.text;
    if (text.isNotEmpty) {
      setState(() {
        messages.add({'sender': 'user', 'text': text});
      });
      _controller.clear();

      final response = await openAIService.generateResponse(text);
      setState(() {
        messages.add({'sender': 'bot', 'text': response.trim()});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AI Chatbot'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: messages.length,
              itemBuilder: (context, index) {
                final message = messages[index];
                return Container(
                  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                  child: Column(
                    crossAxisAlignment: message['sender'] == 'user'
                        ? CrossAxisAlignment.end
                        : CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: message['sender'] == 'user'
                              ? Colors.blue[200]
                              : Colors.grey[300],
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Text(message['text'] ?? ''),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(
                      hintText: 'Enter your message',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: _sendMessage,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Running the App

Run the App: Open your terminal, navigate to your project directory, and run:

flutter run
Enter fullscreen mode Exit fullscreen mode

This will launch your Flutter app on the connected device or emulator.

Testing Your Chatbot

- Interact with the Bot: Type a message in the text field and press the send button. The bot will respond using the OpenAI API.
- Check for Errors: If there are issues, check the console output for any error messages. Common errors might include issues with the API key or network connectivity.

Conclusion

In this guide, we created a simple chatbot using Flutter and OpenAI. We covered setting up the project, creating a service to interact with the OpenAI API, and building a user interface for the chatbot. This example demonstrates how you can integrate advanced AI capabilities into your Flutter applications, enhancing user interaction and experience. With this foundation, you can further customize and expand your chatbot to handle more complex interactions.

💖 💪 🙅 🚩
aaronreddix
Aaron Reddix

Posted on July 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related