Skip to content

Commit 92baa57

Browse files
authored
Merge pull request #1676 from LucasXu0/text_robot
feat: integrate OpenAI service
2 parents c46b09f + ab108e1 commit 92baa57

File tree

21 files changed

+724
-50
lines changed

21 files changed

+724
-50
lines changed

frontend/app_flowy/packages/appflowy_editor/CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,12 @@
1+
## 0.0.9
2+
* Support customize the text color and text background color.
3+
* Fix some bugs.
4+
5+
## 0.0.8
6+
* Fix the toolbar display issue.
7+
* Fix the copy/paste issue on Windows.
8+
* Minor Updates.
9+
110
## 0.0.7
211
* Refactor theme customizer, and support dark mode.
312
* Support export and import markdown.

frontend/app_flowy/packages/appflowy_editor/example/lib/home_page.dart

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import 'dart:async';
12
import 'dart:convert';
23
import 'dart:io';
34

45
import 'package:appflowy_editor/appflowy_editor.dart';
56
import 'package:example/pages/simple_editor.dart';
7+
import 'package:example/plugin/AI/text_robot.dart';
68
import 'package:file_picker/file_picker.dart';
79
import 'package:flutter/foundation.dart';
810
import 'package:flutter/material.dart';
@@ -102,6 +104,30 @@ class _HomePageState extends State<HomePage> {
102104
_loadEditor(context, jsonString);
103105
}),
104106

107+
// Text Robot
108+
_buildSeparator(context, 'Text Robot'),
109+
_buildListTile(context, 'Type Text Automatically', () async {
110+
final jsonString = Future<String>.value(
111+
jsonEncode(EditorState.empty().document.toJson()).toString(),
112+
);
113+
await _loadEditor(context, jsonString);
114+
115+
Future.delayed(const Duration(seconds: 2), () {
116+
final textRobot = TextRobot(
117+
editorState: _editorState,
118+
);
119+
textRobot.insertText(
120+
r'''
121+
Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC
122+
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
123+
124+
1914 translation by H. Rackham
125+
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
126+
''',
127+
);
128+
});
129+
}),
130+
105131
// Encoder Demo
106132
_buildSeparator(context, 'Encoder Demo'),
107133
_buildListTile(context, 'Export To JSON', () {
@@ -200,7 +226,11 @@ class _HomePageState extends State<HomePage> {
200226
);
201227
}
202228

203-
void _loadEditor(BuildContext context, Future<String> jsonString) {
229+
Future<void> _loadEditor(
230+
BuildContext context,
231+
Future<String> jsonString,
232+
) async {
233+
final completer = Completer<void>();
204234
_jsonString = jsonString;
205235
setState(
206236
() {
@@ -213,6 +243,10 @@ class _HomePageState extends State<HomePage> {
213243
);
214244
},
215245
);
246+
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
247+
completer.complete();
248+
});
249+
return completer.future;
216250
}
217251

218252
void _exportFile(

frontend/app_flowy/packages/appflowy_editor/example/lib/pages/simple_editor.dart

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import 'dart:convert';
22

33
import 'package:appflowy_editor/appflowy_editor.dart';
44
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
5+
import 'package:example/plugin/AI/continue_to_write.dart';
6+
import 'package:example/plugin/AI/auto_completion.dart';
7+
import 'package:example/plugin/AI/gpt3.dart';
8+
import 'package:example/plugin/AI/smart_edit.dart';
59
import 'package:flutter/material.dart';
610

711
class SimpleEditor extends StatelessWidget {
@@ -64,6 +68,14 @@ class SimpleEditor extends StatelessWidget {
6468
codeBlockMenuItem,
6569
// Emoji
6670
emojiMenuItem,
71+
// Open AI
72+
if (apiKey.isNotEmpty) ...[
73+
autoCompletionMenuItem,
74+
continueToWriteMenuItem,
75+
]
76+
],
77+
toolbarItems: [
78+
smartEditItem,
6779
],
6880
);
6981
} else {
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import 'package:appflowy_editor/appflowy_editor.dart';
2+
import 'package:example/plugin/AI/gpt3.dart';
3+
import 'package:example/plugin/AI/text_robot.dart';
4+
import 'package:flutter/material.dart';
5+
import 'package:flutter/services.dart';
6+
7+
SelectionMenuItem autoCompletionMenuItem = SelectionMenuItem(
8+
name: () => 'Auto generate content',
9+
icon: (editorState, onSelected) => Icon(
10+
Icons.rocket,
11+
size: 18.0,
12+
color: onSelected
13+
? editorState.editorStyle.selectionMenuItemSelectedIconColor
14+
: editorState.editorStyle.selectionMenuItemIconColor,
15+
),
16+
keywords: ['auto generate content', 'open ai', 'gpt3', 'ai'],
17+
handler: ((editorState, menuService, context) async {
18+
showDialog(
19+
context: context,
20+
builder: (context) {
21+
final controller = TextEditingController(text: '');
22+
return AlertDialog(
23+
content: RawKeyboardListener(
24+
focusNode: FocusNode(),
25+
child: TextField(
26+
autofocus: true,
27+
controller: controller,
28+
maxLines: null,
29+
decoration: const InputDecoration(
30+
border: OutlineInputBorder(),
31+
hintText: 'Please input something...',
32+
),
33+
),
34+
onKey: (key) {
35+
if (key is! RawKeyDownEvent) return;
36+
if (key.logicalKey == LogicalKeyboardKey.enter) {
37+
Navigator.of(context).pop();
38+
// fetch the result and insert it
39+
final textRobot = TextRobot(editorState: editorState);
40+
const gpt3 = GPT3APIClient(apiKey: apiKey);
41+
gpt3.getGPT3Completion(
42+
controller.text,
43+
'',
44+
onResult: (result) async {
45+
await textRobot.insertText(
46+
result,
47+
inputType: TextRobotInputType.character,
48+
);
49+
},
50+
onError: () async {},
51+
);
52+
} else if (key.logicalKey == LogicalKeyboardKey.escape) {
53+
Navigator.of(context).pop();
54+
}
55+
},
56+
),
57+
);
58+
},
59+
);
60+
}),
61+
);
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import 'package:appflowy_editor/appflowy_editor.dart';
2+
import 'package:example/plugin/AI/gpt3.dart';
3+
import 'package:example/plugin/AI/text_robot.dart';
4+
import 'package:flutter/material.dart';
5+
6+
SelectionMenuItem continueToWriteMenuItem = SelectionMenuItem(
7+
name: () => 'Continue To Write',
8+
icon: (editorState, onSelected) => Icon(
9+
Icons.print,
10+
size: 18.0,
11+
color: onSelected
12+
? editorState.editorStyle.selectionMenuItemSelectedIconColor
13+
: editorState.editorStyle.selectionMenuItemIconColor,
14+
),
15+
keywords: ['continue to write'],
16+
handler: ((editorState, menuService, context) async {
17+
// Two cases
18+
// 1. if there is content in the text node where the cursor is located,
19+
// then we use the current text content as data.
20+
// 2. if there is no content in the text node where the cursor is located,
21+
// then we use the previous / next text node's content as data.
22+
23+
final selection =
24+
editorState.service.selectionService.currentSelection.value;
25+
if (selection == null || !selection.isCollapsed) {
26+
return;
27+
}
28+
29+
final textNodes = editorState.service.selectionService.currentSelectedNodes
30+
.whereType<TextNode>();
31+
if (textNodes.isEmpty) {
32+
return;
33+
}
34+
35+
final textRobot = TextRobot(editorState: editorState);
36+
const gpt3 = GPT3APIClient(apiKey: apiKey);
37+
final textNode = textNodes.first;
38+
39+
var prompt = '';
40+
var suffix = '';
41+
42+
void continueToWriteInSingleLine() {
43+
prompt = textNode.delta.slice(0, selection.startIndex).toPlainText();
44+
suffix = textNode.delta
45+
.slice(
46+
selection.endIndex,
47+
textNode.toPlainText().length,
48+
)
49+
.toPlainText();
50+
}
51+
52+
void continueToWriteInMulitLines() {
53+
final parent = textNode.parent;
54+
if (parent != null) {
55+
for (final node in parent.children) {
56+
if (node is! TextNode || node.toPlainText().isEmpty) continue;
57+
if (node.path < textNode.path) {
58+
prompt += '${node.toPlainText()}\n';
59+
} else if (node.path > textNode.path) {
60+
suffix += '${node.toPlainText()}\n';
61+
}
62+
}
63+
}
64+
}
65+
66+
if (textNodes.first.toPlainText().isNotEmpty) {
67+
continueToWriteInSingleLine();
68+
} else {
69+
continueToWriteInMulitLines();
70+
}
71+
72+
if (prompt.isEmpty && suffix.isEmpty) {
73+
return;
74+
}
75+
76+
late final BuildContext diglogContext;
77+
78+
showDialog(
79+
context: context,
80+
builder: (context) {
81+
diglogContext = context;
82+
return AlertDialog(
83+
content: Column(
84+
mainAxisSize: MainAxisSize.min,
85+
children: const [
86+
CircularProgressIndicator(),
87+
SizedBox(height: 10),
88+
Text('Loading'),
89+
],
90+
),
91+
);
92+
},
93+
);
94+
95+
gpt3.getGPT3Completion(
96+
prompt,
97+
suffix,
98+
onResult: (result) async {
99+
Navigator.of(diglogContext).pop(true);
100+
await textRobot.insertText(
101+
result,
102+
inputType: TextRobotInputType.word,
103+
);
104+
},
105+
onError: () async {
106+
Navigator.of(diglogContext).pop(true);
107+
},
108+
);
109+
}),
110+
);
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import 'package:http/http.dart' as http;
2+
import 'dart:async';
3+
import 'dart:convert';
4+
5+
// Please fill in your own API key
6+
const apiKey = '';
7+
8+
enum GPT3API {
9+
completion,
10+
edit,
11+
}
12+
13+
extension on GPT3API {
14+
Uri get uri {
15+
switch (this) {
16+
case GPT3API.completion:
17+
return Uri.parse('https://api.openai.com/v1/completions');
18+
case GPT3API.edit:
19+
return Uri.parse('https://api.openai.com/v1/edits');
20+
}
21+
}
22+
}
23+
24+
class GPT3APIClient {
25+
const GPT3APIClient({
26+
required this.apiKey,
27+
});
28+
29+
final String apiKey;
30+
31+
/// Get completions from GPT-3
32+
///
33+
/// [prompt] is the prompt text
34+
/// [suffix] is the suffix text
35+
/// [onResult] is the callback function to handle the result
36+
/// [maxTokens] is the maximum number of tokens to generate
37+
/// [temperature] is the temperature of the model
38+
///
39+
/// See https://beta.openai.com/docs/api-reference/completions/create
40+
Future<void> getGPT3Completion(
41+
String prompt,
42+
String suffix, {
43+
required Future<void> Function(String result) onResult,
44+
required Future<void> Function() onError,
45+
int maxTokens = 200,
46+
double temperature = .3,
47+
}) async {
48+
final data = {
49+
'model': 'text-davinci-003',
50+
'prompt': prompt,
51+
'suffix': suffix,
52+
'max_tokens': maxTokens,
53+
'temperature': temperature,
54+
'stream': false,
55+
};
56+
57+
final headers = {
58+
'Authorization': apiKey,
59+
'Content-Type': 'application/json',
60+
};
61+
62+
final response = await http.post(
63+
GPT3API.completion.uri,
64+
headers: headers,
65+
body: json.encode(data),
66+
);
67+
68+
if (response.statusCode == 200) {
69+
final result = json.decode(response.body);
70+
final choices = result['choices'];
71+
if (choices != null && choices is List) {
72+
for (final choice in choices) {
73+
final text = choice['text'];
74+
await onResult(text);
75+
}
76+
}
77+
} else {
78+
await onError();
79+
}
80+
}
81+
82+
Future<void> getGPT3Edit(
83+
String apiKey,
84+
String input,
85+
String instruction, {
86+
required Future<void> Function(List<String> result) onResult,
87+
required Future<void> Function() onError,
88+
int n = 1,
89+
double temperature = .3,
90+
}) async {
91+
final data = {
92+
'model': 'text-davinci-edit-001',
93+
'input': input,
94+
'instruction': instruction,
95+
'temperature': temperature,
96+
'n': n,
97+
};
98+
99+
final headers = {
100+
'Authorization': apiKey,
101+
'Content-Type': 'application/json',
102+
};
103+
104+
final response = await http.post(
105+
Uri.parse('https://api.openai.com/v1/edits'),
106+
headers: headers,
107+
body: json.encode(data),
108+
);
109+
if (response.statusCode == 200) {
110+
final result = json.decode(response.body);
111+
final choices = result['choices'];
112+
if (choices != null && choices is List) {
113+
await onResult(choices.map((e) => e['text'] as String).toList());
114+
}
115+
} else {
116+
await onError();
117+
}
118+
}
119+
}

0 commit comments

Comments
 (0)