Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
luhouyang committed Jul 6, 2024
2 parents 621eb5c + d09386b commit 65ac66c
Show file tree
Hide file tree
Showing 8 changed files with 461 additions and 24 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release


/lib/env/env.g.dart
.env
7 changes: 7 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,16 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>


</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
Expand Down
9 changes: 9 additions & 0 deletions lib/env/env.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// lib/env/env.dart
import 'package:envied/envied.dart';
part 'env.g.dart';

@Envied(path: ".env")
abstract class Env {
@EnviedField(varName: 'OPEN_AI_API_KEY') // the .env variable.
static String apiKey = _Env.apiKey;
}
10 changes: 9 additions & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import 'package:dart_openai/dart_openai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:nutsnbolts/env/env.dart';
import 'package:nutsnbolts/firebase_options.dart';
import 'package:nutsnbolts/usecases/user_usecase.dart';
import 'package:provider/provider.dart';
Expand All @@ -12,6 +14,11 @@ void main() async {
options: DefaultFirebaseOptions.currentPlatform,
);

// OPENAI API Stuff Setup
OpenAI.apiKey = Env.apiKey;
OpenAI.requestsTimeOut = const Duration(seconds: 60); // 60 seconds.
OpenAI.showLogs = true;

runApp(const MainApp());
}

Expand All @@ -26,7 +33,8 @@ class MainApp extends StatelessWidget {
create: (context) => UserUsecase(),
),
],
child: const MaterialApp(debugShowCheckedModeBanner: false, home: AuthGate()),
child: const MaterialApp(
debugShowCheckedModeBanner: false, home: AuthGate()),
);
}
}
98 changes: 82 additions & 16 deletions lib/pages/add_case_page.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:io';
import 'package:dart_openai/dart_openai.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
Expand Down Expand Up @@ -155,24 +156,38 @@ class _AddCasePageState extends State<AddCasePage> {
padding: EdgeInsets.symmetric(horizontal: 16),
),
),
// Submit button is here!
ElevatedButton(
onPressed: () async {

// validation
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
}
// check for image
if (picBytes != null) {
// post image/case
await FirestoreModel().addCase(controllers, userUsecase, picFile!, picBytes!).then(
(CaseEntity caseEntity) {
// pass CaseEntity to ChatPage for OpenAI API call
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => ChatPage(caseEntity: caseEntity),
));
},
);
// // validation
// if (_formKey.currentState!.validate()) {
// _formKey.currentState!.save();
// }
// // check for image
// if (picBytes != null) {
// // post image/case
// await FirestoreModel().addCase(controllers, userUsecase, picFile!, picBytes!).then(
// (CaseEntity caseEntity) {
// // pass CaseEntity to ChatPage for OpenAI API call
// Navigator.of(context).pushReplacement(MaterialPageRoute(
// builder: (context) => ChatPage(caseEntity: caseEntity),
// ));
// },
// );
// }
// makeApiCall() function is at the bottom of the file
// please check if this implmementation is correct
if (_formKey.currentState != null && _formKey.currentState!.validate()) {
makeApiCall().then((response) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Case added successfully"),
),
);
}).catchError((error) {
// Handle any errors here
});
}
},
child: const Text("submit"))
Expand Down Expand Up @@ -414,3 +429,54 @@ class _AddCasePageState extends State<AddCasePage> {
}
// end of pictures code
}

makeApiCall() async {
// the system message that will be sent to the request.
final systemMessage = OpenAIChatCompletionChoiceMessageModel(
content: [
OpenAIChatCompletionChoiceMessageContentItemModel.text(
"return any message you are given as JSON.",
),
],
role: OpenAIChatMessageRole.assistant,
);

// the user message that will be sent to the request.
final userMessage = OpenAIChatCompletionChoiceMessageModel(
content: [
OpenAIChatCompletionChoiceMessageContentItemModel.text(
"Hello, I am a chatbot created by OpenAI. How are you today?", // TODO: Engineer a custom prompt for the image case analysis
),

//! image url contents are allowed only for models with image support such gpt-4.
OpenAIChatCompletionChoiceMessageContentItemModel.imageUrl(
"https://placehold.co/600x400", // TODO: Send the image that was picked by the user
),
],
role: OpenAIChatMessageRole.user,
);

// all messages to be sent.
final requestMessages = [
systemMessage,
userMessage,
];

// the actual request.
OpenAIChatCompletionModel chatCompletion = await OpenAI.instance.chat.create(
model: "gpt-3.5-turbo-1106", // TODO: Change model to GPT-4
responseFormat: {"type": "json_object"},
seed: 6,
messages: requestMessages,
temperature: 0.2,
maxTokens: 500,
);

// print the response.

// TODO: Handle the response from the API and put it into a case chat
print(chatCompletion.choices.first.message); // ...
print(chatCompletion.systemFingerprint); // ...
print(chatCompletion.usage.promptTokens); // ...
print(chatCompletion.id); // ...
}
25 changes: 18 additions & 7 deletions lib/pages/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,17 @@ class _HomePageState extends State<HomePage> {
children: [
Text(
"nuts & bolts.",
style: TextStyle(color: MyColours.secondaryColour, fontSize: 28, fontWeight: FontWeight.bold),
style: TextStyle(
color: MyColours.secondaryColour,
fontSize: 28,
fontWeight: FontWeight.bold),
),
Text(
"Welcome, ${user!.displayName}!",
style: TextStyle(color: Colors.white.withOpacity(0.8), fontSize: 18, fontWeight: FontWeight.w600),
style: TextStyle(
color: Colors.white.withOpacity(0.8),
fontSize: 18,
fontWeight: FontWeight.w600),
)
],
),
Expand Down Expand Up @@ -85,11 +91,13 @@ class _HomePageState extends State<HomePage> {
children: [
const Text(
"Want something fixed?",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
),
Text(
"Get a technician now!",
style: TextStyle(fontSize: 14, color: Colors.grey[700]),
style: TextStyle(
fontSize: 14, color: Colors.grey[700]),
),
],
),
Expand All @@ -106,7 +114,8 @@ class _HomePageState extends State<HomePage> {
.limit(5)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.connectionState == ConnectionState.waiting) {
if (!snapshot.hasData ||
snapshot.connectionState == ConnectionState.waiting) {
return Column(
children: [
SizedBox(
Expand All @@ -126,7 +135,8 @@ class _HomePageState extends State<HomePage> {
children: [
const Text(
"Your Cases",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18),
),
const SizedBox(
height: 10,
Expand All @@ -137,7 +147,8 @@ class _HomePageState extends State<HomePage> {
physics: const NeverScrollableScrollPhysics(),
itemCount: snapshot.data!.size,
itemBuilder: (context, index) {
CaseEntity caseEntity = CaseEntity.from(snapshot.data!.docs[index].data());
CaseEntity caseEntity = CaseEntity.from(
snapshot.data!.docs[index].data());
return CaseCard(caseEntity: caseEntity);
},
),
Expand Down
Loading

0 comments on commit 65ac66c

Please sign in to comment.