Skip to content

Integrate OpenAI into Your Flutter/Dart Applications with dart_openai

Are you looking to harness the power of OpenAI’s state-of-the-art AI models in your Flutter or Dart applications? The dart_openai package is here to make it easy and seamless for you to integrate OpenAI’s capabilities directly into your projects. This open-source client package simplifies the process of making requests to OpenAI’s various APIs, including GPT-3, DALL-E, and more.

Why Choose dart_openai?

The dart_openai package is designed with developers in mind. It provides intuitive methods for interacting with OpenAI’s APIs without the hassle of dealing with HTTP requests. Here are some of the key features that make this package a must-have:

  • Easy Integration: Reflects OpenAI documentation with added functionalities tailored for Dart.
  • Single Authorization: Authorize once and use it anywhere in your application.
  • Developer-Friendly: Streamlined for ease of use.
  • Stream Functionality: Supports completions API and fine-tune events API.
  • Comprehensive Examples: Ready examples for almost every implementation in the /example folder.

GitHub Repository

Stay up-to-date with the latest developments, contribute, or star the project on GitHub:

Getting Started

Authentication

To use the OpenAI API, you need an API key. You can load your secret key at runtime from a .env file using the envied package.

// .env
OPEN_AI_API_KEY=<REPLACE WITH YOUR API KEY>

// 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')
  static const apiKey = _Env.apiKey;
}

// lib/main.dart
void main() {
  OpenAI.apiKey = Env.apiKey; // Initialize with API key
  // ..
}

Setting Up

You can set various configurations to optimize the package for your needs:

  • Organization ID: If you belong to a specific organization.
  • Request Timeout: Customize the default request timeout.
  • Base URL: Change the base URL if using a proxy.
  • Debugging: Enable logs for operations and responses.
OpenAI.organization = "ORGANIZATION ID";
OpenAI.requestsTimeOut = Duration(seconds: 60);
OpenAI.baseUrl = "https://api.openai.com/v1";
OpenAI.showLogs = true;
OpenAI.showResponsesLogs = true;

Usage Examples

Models

List Models:

List<OpenAIModelModel> models = await OpenAI.instance.model.list();
OpenAIModelModel firstModel = models.first;
print(firstModel.id); 

Retrieve Model:

OpenAIModelModel model = await OpenAI.instance.model.retrieve("text-davinci-003");
print(model.ownedBy); 

Completions

Create Completion:

OpenAICompletionModel completion = await OpenAI.instance.completion.create(
  model: "text-davinci-003",
  prompt: "Dart is a program",
  maxTokens: 20,
  temperature: 0.5,
  n: 1,
  stop: ["\n"],
  echo: true,
  seed: 42,
  bestOf: 2,
);
print(completion.choices.first.text); 

Create Completion Stream:

Stream<OpenAIStreamCompletionModel> completionStream = OpenAI.instance.completion.createStream(
  model: "text-davinci-003",
  prompt: "Github is ",
  maxTokens: 100,
  temperature: 0.5,
  topP: 1,
  seed: 42,
  stop: '###',
  n: 2,
);

completionStream.listen((event) {
  final firstCompletionChoice = event.choices.first;
  print(firstCompletionChoice.index);
  print(firstCompletionChoice.text);
});

Chat (ChatGPT)

Create Chat Completion:

final systemMessage = OpenAIChatCompletionChoiceMessageModel(
  content: [
    OpenAIChatCompletionChoiceMessageContentItemModel.text(
      "return any message you are given as JSON.",
    ),
  ],
  role: OpenAIChatMessageRole.assistant,
);

final userMessage = OpenAIChatCompletionChoiceMessageModel(
  content: [
    OpenAIChatCompletionChoiceMessageContentItemModel.text(
      "Hello, I am a chatbot created by OpenAI. How are you today?",
    ),
  ],
  role: OpenAIChatMessageRole.user,
);

final requestMessages = [
  systemMessage,
  userMessage,
];

OpenAIChatCompletionModel chatCompletion = await OpenAI.instance.chat.create(
  model: "gpt-3.5-turbo-1106",
  responseFormat: {"type": "json_object"},
  seed: 6,
  messages: requestMessages,
  temperature: 0.2,
  maxTokens: 500,
);
print(chatCompletion.choices.first.message);

Create Chat Completion Stream:

final userMessage = OpenAIChatCompletionChoiceMessageModel(
  content: [
    OpenAIChatCompletionChoiceMessageContentItemModel.text(
      "Hello my friend!",
    ),
  ],
  role: OpenAIChatMessageRole.user,
);

final chatStream = OpenAI.instance.chat.createStream(
  model: "gpt-3.5-turbo",
  messages: [
    userMessage,
  ],
  seed: 423,
  n: 2,
);

chatStream.listen(
  (streamChatCompletion) {
    final content = streamChatCompletion.choices.first.delta.content;
    print(content);
  },
  onDone: () {
    print("Done");
  },
);

Error Handling

Errors from the OpenAI API are managed using the RequestFailedException. Implement try-catch blocks to handle errors effectively:

try {
  final errorVariation = await OpenAI.instance.image.variation(
    image: File(/*PATH OF NON-IMAGE FILE*/),
  );
} on RequestFailedException catch(e) {
  print(e.message);
  print(e.statusCode);
}

Contributing to dart_openai

This project thrives on community support. Here’s how you can help:

  • Writing Documentation: Documenting undocumented classes, properties, methods, etc.
  • Code Refactoring: Improving code structure and readability.
  • Reviewing Code: Suggesting better ways to implement features.
  • Sharing Use Cases: Adding your examples to the /examples directory.
  • Updating Information: Keeping the package updated with API changes.
  • Donating: Supporting the project financially to ensure its continuous improvement.

Conclusion

The dart_openai package is your gateway to integrating advanced AI capabilities into your Flutter/Dart applications. Whether you are generating text, creating images, or building chatbots, this package provides the tools and examples you need to get started quickly and efficiently. Check out the full documentation for more details and start building smarter applications today!

Leave a Reply

Your email address will not be published. Required fields are marked *