0% found this document useful (0 votes)
18 views10 pages

AI Chatbot using API Calling

The document outlines the development of an AI Chatbot Mobile Application using Flutter and Grok API. It details the tools, technologies, and step-by-step procedure for creating the app, including API integration, user interface structure, and chat history management. The project was successfully executed and verified, demonstrating the functionality of the chatbot application.

Uploaded by

nowfal2005km
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

AI Chatbot using API Calling

The document outlines the development of an AI Chatbot Mobile Application using Flutter and Grok API. It details the tools, technologies, and step-by-step procedure for creating the app, including API integration, user interface structure, and chat history management. The project was successfully executed and verified, demonstrating the functionality of the chatbot application.

Uploaded by

nowfal2005km
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

AI Chatbot using

API Calling

Done by:
Nowfal .S
Navinash
D.B.
Prasanna
Venkatesh K.
AI Chatbot using API Calling

Aim:
To develop an AI Chatbot Mobile Application Using Flutter and Grok API.

Tools and Technologies used:


Component Technology/Tool
Frontend Framework Flutter SDK (Version 3.0)
Programming Language Java or Kotlin
AI Integration Grok API
IDE Android Studio Arctic Fox
(v2020.3.1 Patch 4)
JDK Java Development Kit 17
Local Storage SharedPreferences (Flutter Plugin)
Testing Platforms Android Emulator or Physical Android
Phone

Procedure:
Step 1. Install Flutter & Dart Plugins in Android Studio
 Go to Plugins from the sidebar.
 Open Marketplace, search for Flutter, and click Install.
 When prompted, also install the Dart plugin.
 Restart Android Studio after installation.
Step 2. Create a New Flutter Project
 Click New Flutter Project → Select Flutter Application → Click Next.
 Set the project name as chatbot_app.
 Select your Flutter SDK path (e.g., C:\src\flutter).
 Click Next, then Finish.
Step 3. Grok API Integration
 Visit https://console.Grok.com/keys.
 Obtained API key from Grok for GPT model access
 Sent structured POST requests to Grok's endpoint using Dart's `http` package
 Parsed JSON responses and updated chat in real-time
Step 4. User Interface Structure
 Set up `pubspec.yaml` and `build.gradle` with required dependencies (http, shared_preferences,
etc.)
 Defined the app structure with `main.dart` as the entry point
 Created a `ChatScreen` widget to display the conversation UI
 Designed custom message bubbles for user and AI messages
 Implemented a collapsible navigation drawer to view old chat sessions
Step 5. Chat History Management
 Implemented local storage using SharedPreferences
 Stored chat sessions grouped by date and time
 Provided functionality to start new sessions and retrieve previous ones

Step 6. App Icon Setup


 Save your app icon as icon.png in the directory of:
chatbot_app/
└── assets/
└── icon.png
 Run in terminal:
flutter pub get
flutter pub run flutter_launcher_icons:main
Step 7. Build Commands
 After editing pubspec.yaml or build.gradle, run:
flutter clean
flutter pub get
 To run the app:
flutter run
(or click the play button in Android Studio)
 To build APK for release:
flutter build apk –release

Code:
app/lib/main.dart

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MyApp());
}
class ChatSession {
String title;
DateTime createdAt;
List<String> messages;
ChatSession({required this.title, required this.createdAt, required this.messages});
Map<String, dynamic> toJson() => {
'title': title,
'createdAt': createdAt.toIso8601String(),
'messages': messages,
};
static ChatSession fromJson(Map<String, dynamic> json) => ChatSession(
title: json['title'],
createdAt: DateTime.parse(json['createdAt']),
messages: List<String>.from(json['messages']),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'AI Chatbot',
theme: ThemeData(primarySwatch: Colors.blue),
debugShowCheckedModeBanner: false,
home: ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _controller = TextEditingController();
List<ChatSession> sessions = [];
int currentSessionIndex = 0;
bool isThinking = false;
late GlobalKey<ScaffoldState> _scaffoldKey;
@override
void initState() {
super.initState();
_scaffoldKey = GlobalKey<ScaffoldState>();
loadSessions();
}
Future<void> loadSessions() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String>? savedSessions = prefs.getStringList('chat_sessions');
if (savedSessions != null) {
setState(() {
sessions = savedSessions.map((e) => ChatSession.fromJson(jsonDecode(e))).toList();
});
}
if (sessions.isEmpty) {
newChat();
}
}
Future<void> saveSessions() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String> sessionStrings = sessions.map((e) => jsonEncode(e.toJson())).toList();
await prefs.setStringList('chat_sessions', sessionStrings);
}
void newChat() {
setState(() {
final session = ChatSession(
title: 'Chat ${DateFormat('dd/MM/yyyy HH:mm').format(DateTime.now())}',
createdAt: DateTime.now(),
messages: [],
);
sessions.add(session);
currentSessionIndex = sessions.length - 1;
});
saveSessions();
}
Future<String> getGrokResponse(String message) async {
final apiKey = "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";
final url = Uri.parse("https://api.Grok.com/openai/v1/chat/completions");
final response = await http.post(
url,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $apiKey",
},
body: json.encode({
"model": "llama3-8b-8192",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message}
],
"temperature": 0.7
}),
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
return data["choices"][0]["message"]["content"];
} else {
return "Error: ${response.statusCode} - ${response.body}";
}
}
void sendMessage() async {
final text = _controller.text.trim();
if (text.isEmpty) return;
setState(() {
sessions[currentSessionIndex].messages.add("You: $text");
sessions[currentSessionIndex].messages.add("Bot: thinking...");
_controller.clear();
isThinking = true;
});
await saveSessions();
final response = await getGrokResponse(text);
setState(() {
sessions[currentSessionIndex].messages.removeLast();
sessions[currentSessionIndex].messages.add("Bot: $response");
isThinking = false;
});
await saveSessions();
}
@override
Widget build(BuildContext context) {
final currentMessages = sessions.isNotEmpty ? sessions[currentSessionIndex].messages : [];
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('AI Chatbot'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () => _scaffoldKey.currentState?.openDrawer(),
),
),
drawer: Drawer(
child: SafeArea(
child: Column(
children: [
ListTile(
title: Text('New Chat', style: TextStyle(fontWeight: FontWeight.bold)),
leading: Icon(Icons.add),
onTap: () {
newChat();
Navigator.pop(context);
},
),
Divider(),
Expanded(
child: ListView.builder(
itemCount: sessions.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
sessions[index].title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
tileColor: index == currentSessionIndex ? Colors.blue[100] : null,
onTap: () {
setState(() {
currentSessionIndex = index;
});
Navigator.pop(context);
},
trailing: IconButton(
icon: Icon(Icons.delete, color: Colors.red),
onPressed: () {
setState(() {
sessions.removeAt(index);
if (sessions.isEmpty) {
newChat();
} else if (currentSessionIndex >= sessions.length) {
currentSessionIndex = sessions.length - 1;
}
});
saveSessions();
},
),
);
},
),
),
],
),
),
),
body: Row(
children: [
Expanded(
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: currentMessages.length,
itemBuilder: (context, index) {
String message = currentMessages[index];
bool isUser = message.startsWith("You:");
bool isBot = message.startsWith("Bot:");
return ListTile(
title: RichText(
text: TextSpan(
children: [
TextSpan(
text: isUser
? "You:"
: isBot
? "Bot:"
: "",
style: TextStyle(
fontWeight: FontWeight.bold,
color: isUser
? Colors.blue
: isBot
? Colors.green
: Colors.black,
),
),
TextSpan(
text: message.contains(":")
? message.substring(message.indexOf(":") + 1)
: message,
style: TextStyle(color: Colors.black),
),
],
),
),
);
},
),
),
Divider(height: 1.0),
Container(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
onSubmitted: (_) => sendMessage(),
decoration: InputDecoration(hintText: "Type your message..."),
),
),
IconButton(
icon: Icon(Icons.send),
onPressed: sendMessage,
),
],
),
),
],
),
),
],
),
);
}
}

app/pubspec.yaml

name: chatbot_app
description: chatbot app by API calling
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: ^0.13.4
shared_preferences: ^2.0.15
intl: ^0.17.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter_launcher_icons: ^0.11.0 # compatible version
flutter_icons:
android: true
ios: true
image_path: "assets/icon.png"
flutter:
uses-material-design: true
assets:
- assets/icon.png

app/android/app/build.gradle

name: chatbot_app
description: chatbot app by API calling
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.17.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: ^0.13.4
shared_preferences: ^2.0.15
intl: ^0.17.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter_launcher_icons: ^0.11.0 # compatible version
flutter_icons:
android: true
ios: true
image_path: "assets/icon.png"
flutter:
uses-material-design: true
assets:
- assets/icon.png
Output Screenshot:

Result:
Thus, the program to develop an AI Chatbot Mobile Application using Flutter and Grok API was
executed successfully and the output was verified.

You might also like