Flutter OpenAI接口集成插件tl_flutter_openai的使用

发布于 1周前 作者 wuwangju 来自 Flutter

Flutter OpenAI接口集成插件 tl_flutter_openai 的使用

Tark Laboratory Flutter OpenAI Client

这是一个非官方的 Dart 客户端,用于 OpenAI API

Demo

特性

  • 完全兼容官方 OpenAI API
  • 完全类型安全
  • 支持组织身份验证

支持的端点

  • 聊天完成(Chat completions)

正在开发中的端点

  • Embeddings
  • Fine-tuning
  • Batch
  • Images
  • Models
  • Moderations

使用说明

认证

要进行认证,您需要一个 API 密钥。可以从您的个人账户设置中获取该密钥:OpenAI API 密钥

注意:API 密钥是一个秘密!
不要将其与他人共享或将其暴露在客户端代码中(如浏览器或应用程序)。生产环境请求必须通过您的后端服务器进行路由,并从环境变量或密钥管理服务中加载您的 API 密钥。

final openAI = OpenAI(
  apiKey: dotenv.env['OPENAI_API_KEY'],
);

可选:组织身份验证

对于属于多个组织或通过旧版用户 API 密钥访问项目的用户,可以通过传递头信息来指定用于 API 请求的组织和项目。这些 API 请求的使用将计入指定的组织和项目。

final openAI = OpenAI(
  apiKey: dotenv.env['OPENAI_API_KEY'],
  organizationId: dotenv.env['OPENAI_ORGANIZATION_ID'],
  projectId: dotenv.env['OPENAI_PROJECT_ID'],
);

聊天功能

给定一组构成对话的消息列表,模型将返回响应。

相关指南:Chat Completions

创建聊天完成

final response = await openAI.createChatCompletion(ChatCompletionRequest(
  model: AIModel.chatgpt4oLatest, // 选择模型
  messages: [
    SystemMessage( // 系统消息
      content: 'You are a helpful assistant.',
    ),
    UserMessage( // 用户消息
      content: 'Hello, how are you?',
    ),
  ],
));

print(response.choices.first.message.content); 
// 输出:Hello! I'm doing well. How about you?
  • ChatCompletionRequest 是用于发起聊天完成请求的主要对象。
  • AIModel.chatgpt4oLatest 是来自 AIModel 枚举的模型之一,列出了所有可用模型。
  • 您可以使用不同类型的消息,例如 SystemMessageUserMessageAssistantMessageToolMessageFunctionMessageMultiModalMessage 来构建对话。

示例代码

以下是完整的示例代码,展示了如何使用 tl_flutter_openai 插件进行聊天完成。

import 'dart:async';

import 'package:example/chat_completion_screen.dart'; // 引入聊天页面
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

Future<void> main() async {
  // 加载环境变量
  await dotenv.load();
  runApp(MyApp()); 
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const ChatCompletionScreen(), // 默认主页为聊天页面
      themeMode: ThemeMode.dark, // 设置主题为深色模式
      darkTheme: ThemeData(
        brightness: Brightness.dark, // 深色主题
        primarySwatch: Colors.blue, // 主色调
        iconTheme: const IconThemeData(color: Colors.white), // 图标颜色
        scaffoldBackgroundColor: Colors.grey[900], // 背景色
        textTheme: const TextTheme(
          bodyMedium: TextStyle(
            fontWeight: FontWeight.w500, // 字体加粗
          ),
        ),
        colorScheme: ColorScheme.dark().copyWith(
          surface: Colors.grey[900], // 表面颜色
        ),
        drawerTheme: DrawerThemeData(
          backgroundColor: Colors.grey[900], // 抽屉背景颜色
        ),
      ),
      initialRoute: '/chat-completion', // 初始路由
      routes: {
        '/chat-completion': (c) => const ChatCompletionScreen(), // 聊天路由
        '/audio': (c) => const ChatCompletionScreen(), // 音频路由
      },
    );
  }
}

更多关于Flutter OpenAI接口集成插件tl_flutter_openai的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter OpenAI接口集成插件tl_flutter_openai的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


tl_flutter_openai 是一个用于在 Flutter 应用中集成 OpenAI API 的插件。通过这个插件,你可以轻松地在你的 Flutter 应用中调用 OpenAI 的各种功能,比如文本生成、对话模型、代码生成等。

安装 tl_flutter_openai

首先,你需要在 pubspec.yaml 文件中添加 tl_flutter_openai 依赖:

dependencies:
  flutter:
    sdk: flutter
  tl_flutter_openai: ^0.1.0  # 请根据实际情况使用最新版本

然后运行 flutter pub get 来安装依赖。

基本使用

1. 初始化 OpenAI

在使用 tl_flutter_openai 之前,你需要初始化它。通常你需要在应用的入口处(如 main.dart)进行初始化:

import 'package:tl_flutter_openai/tl_flutter_openai.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 OpenAI,传入你的 API Key
  await OpenAI.init(apiKey: 'your_openai_api_key');
  
  runApp(MyApp());
}

2. 调用 OpenAI API

你可以使用 OpenAI 类中的方法来调用 OpenAI 的各种 API。以下是一些常见的用法示例:

文本生成
import 'package:tl_flutter_openai/tl_flutter_openai.dart';

Future<void> generateText() async {
  try {
    final response = await OpenAI.complete(
      prompt: "Once upon a time",
      maxTokens: 50,
      temperature: 0.7,
    );
    
    print("Generated Text: ${response.choices[0].text}");
  } catch (e) {
    print("Error: $e");
  }
}
对话模型
import 'package:tl_flutter_openai/tl_flutter_openai.dart';

Future<void> chat() async {
  try {
    final response = await OpenAI.chat(
      messages: [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
      ],
      maxTokens: 50,
      temperature: 0.7,
    );
    
    print("Chat Response: ${response.choices[0].message['content']}");
  } catch (e) {
    print("Error: $e");
  }
}
代码生成
import 'package:tl_flutter_openai/tl_flutter_openai.dart';

Future<void> generateCode() async {
  try {
    final response = await OpenAI.complete(
      prompt: "Write a function in Python to calculate the factorial of a number.",
      maxTokens: 100,
      temperature: 0.7,
    );
    
    print("Generated Code: ${response.choices[0].text}");
  } catch (e) {
    print("Error: $e");
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!