Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prompt ChatGPT ports #41

Merged
merged 8 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions dart/prompt_chatgpt/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# See https://www.dartlang.org/guides/libraries/private-files

# Files and directories created by pub
.dart_tool/
.packages
build/
# If you're building an application, you may want to check-in your pubspec.lock
pubspec.lock

# Directory created by dartdoc
# If you don't generate documentation locally you can remove this line.
doc/api/

# dotenv environment variables file
.env*

# Avoid committing generated Javascript files:
*.dart.js
*.info.json # Produced by the --dump-info flag.
*.js # When generated by dart2js. Don't specify *.js if your
# project includes source files written in JavaScript.
*.js_
*.js.deps
*.js.map

.flutter-plugins
.flutter-plugins-dependencies
85 changes: 85 additions & 0 deletions dart/prompt_chatgpt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# 🤖 Dart Prompt ChatGPT Function

Ask question, and let OpenAI GPT-3.5-turbo answer.

## 🧰 Usage

### `GET`

HTML form for interacting with the function.

### `POST`

Query the model for a completion.

**Parameters**

| Name | Description | Location | Type | Sample Value |
| ------------ | ------------------------------------ | -------- | ------------------ | ----------------------------- |
| Content-Type | The content type of the request body | Header | `application/json` | N/A |
| prompt | Text to prompt the model | Body | String | `Write a haiku about Mondays` |

Sample `200` Response:

Response from the model.

```json
{
"ok": true,
"completion": "Monday's heavy weight, Dawning with a sigh of grey, Hopeful hearts await."
}
```

Sample `400` Response:

Response when the request body is missing.

```json
{
"ok": false,
"error": "Missing body with a prompt."
}
```

Sample `500` Response:

Response when the model fails to respond.

```json
{
"ok": false,
"error": "Failed to query model."
}
```

## ⚙️ Configuration

| Setting | Value |
| ----------------- | --------------- |
| Runtime | Dart (2.17) |
| Entrypoint | `lib/main.dart` |
| Build Commands | `dart pub get` |
| Permissions | `any` |
| Timeout (Seconds) | 15 |

## 🔒 Environment Variables

### OPENAI_API_KEY

A unique key used to authenticate with the OpenAI API. Please note that this is a paid service and you will be charged for each request made to the API. For more information, see the [OpenAI pricing page](https://openai.com/pricing/).

| Question | Answer |
| ------------- | --------------------------------------------------------------------------- |
| Required | Yes |
| Sample Value | `sk-wzG...vcy` |
| Documentation | [OpenAI Docs](https://platform.openai.com/docs/quickstart/add-your-api-key) |

### OPENAI_MAX_TOKENS

The maximum number of tokens that the OpenAI response should contain. Be aware that OpenAI models read and write a maximum number of tokens per API call, which varies depending on the model. For GPT-3.5-turbo, the limit is 4096 tokens.

| Question | Answer |
| ------------- | ------------------------------------------------------------------------------------------------------------- |
| Required | No |
| Sample Value | `512` |
| Documentation | [OpenAI: What are tokens?](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them) |
1 change: 1 addition & 0 deletions dart/prompt_chatgpt/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include: package:lints/recommended.yaml
40 changes: 40 additions & 0 deletions dart/prompt_chatgpt/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import 'dart:io';
import 'dart:async';
import 'package:dart_openai/dart_openai.dart';
import 'utils.dart';

Future<dynamic> main(final context) async {
throwIfMissing(Platform.environment, ['OPENAI_API_KEY']);

if (context.req.method == 'GET') {
return context.res.send(getStaticFile('index.html'), 200,
{'Content-Type': 'text/html; charset=utf-8'});
}

try {
throwIfMissing(context.req.body, ['prompt']);
} catch (err) {
return context.res.json({'ok': false, 'error': err.toString()});
}

OpenAI.apiKey = Platform.environment['OPENAI_API_KEY']!;

try {
final response = await OpenAI.instance.chat.create(
model: 'gpt-3.5-turbo',
maxTokens: int.parse(Platform.environment['OPENAI_MAX_TOKENS'] ?? '512'),
messages: [
OpenAIChatCompletionChoiceMessageModel(
content: context.req.body['prompt'],
role: OpenAIChatMessageRole.user)
],
);

final completion = response.choices[0].message.content;

return context.res.json({'ok': true, 'completion': completion}, 200);
} on RequestFailedException {
return context.res
.json({'ok': false, 'error': 'Failed to query model.'}, 500);
}
}
27 changes: 27 additions & 0 deletions dart/prompt_chatgpt/lib/utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'dart:io';

/// Throws an error if any of the keys are missing from the object
/// @param obj - The object to check
/// @param keys - The list of keys to check for
/// @throws Exception
void throwIfMissing(Map<String, dynamic> obj, List<String> keys) {
final missing = <String>[];
for (var key in keys) {
if (!obj.containsKey(key) || obj[key] == null) {
missing.add(key);
}
}
if (missing.isNotEmpty) {
throw Exception('Missing required fields: ${missing.join(', ')}');
}
}

final String _dirname = Platform.script.toFilePath();
final String staticFolder = '${Uri.file(_dirname).resolve('../static')}';

/// Returns the contents of a file in the static folder
/// @param fileName - The name of the file to read
/// @returns Contents of static/{fileName}
String getStaticFile(String fileName) {
return File('${staticFolder}/$fileName').readAsStringSync();
}
11 changes: 11 additions & 0 deletions dart/prompt_chatgpt/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: prompt_chatgpt
version: 1.0.0

environment:
sdk: ^2.17.0

dependencies:
dart_openai: ^3.0.0

dev_dependencies:
lints: ^2.0.0
Loading