Flutter AI Voice Assistant via ChatGPT

This project is a Flutter AI Voice Assistant via ChatGPT by OpenAI.

This project requires a valid session token from ChatGPT to access its unofficial REST API , speech_to_text and flutter_tts

*Sometimes slow to respond, mostly due to excessive use of ChatGPT

Demo

Usage

import 'package:flutter_chatgpt_api/flutter_chatgpt_api.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';

 @override
  void initState() {
    super.initState();
    _api = ChatGPTApi(sessionToken: SESSION_TOKEN);
    isLoading = false;
    _initSpeech();
  }
 
  void _initSpeech() async {
    speechEnabled = await _speechToText.initialize();
    _speechToText.systemLocale().then(
          (value) => tts.setLanguage(value!.localeId),
        );
    tts.setSpeechRate(0.6);
    setState(() {});
  }

  void _startListening() async {
    await _speechToText.listen(onResult: _onSpeechResult);
    setState(() {});
  }

  void _onSpeechResult(SpeechRecognitionResult result) {
    setState(
      () {
        if (result.finalResult) {
          _buildSubmit(result.recognizedWords);
        }
      },
    );
  }
_buildSubmit(String prompt) async {
    setState(
      () {
        _messages.add(
          ChatMessage(
            text: prompt,
            chatMessageType: ChatMessageType.user,
          ),
        );
        isLoading = true;
      },
    );
    var input = prompt;
    Future.delayed(const Duration(milliseconds: 50)).then((_) => _scrollDown());
    var newMessage = await _api.sendMessage(
      input,
      conversationId: _conversationId,
      parentMessageId: _parentMessageId,
    );
    setState(() {
      _conversationId = newMessage.conversationId;
      _parentMessageId = newMessage.messageId;
      isLoading = false;
      _messages.add(
        ChatMessage(
          text: newMessage.message,
          chatMessageType: ChatMessageType.bot,
        ),
      );
      tts.speak(newMessage.message);
    });
    Future.delayed(const Duration(milliseconds: 50)).then((_) => _scrollDown());
  }

SessionToken

To get a session token:

  1. Go to https://chat.openai.com/chat and log in or sign up.
  2. Open dev tools.
  3. Open Application > Cookies (Storage > Cookies on FireFox)

image

  1. Create these files and add your session token to run the tests and example respectively:
  • lib/session_token.dart

Should look something like this:

const SESSION_TOKEN = 'my session token from https://chat.openai.com/chat';

Credit

License

MIT Copyright (c) 2022, Emre Coşkunçay

If you found this project interesting, please consider supporting my open source work by sponsoring me or following me on twitter twitter