Flutter ChatGPT完成请求插件chatgpt_completions的使用

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

Flutter ChatGPT完成请求插件 chatgpt_completions 的使用

特性

  • 文本补全(不带流响应)
  • 文本补全(带流响应)

示例动画

开始使用

安装包

在您的项目中添加 chatgpt_completions 包:

flutter pub add chatgpt_completions

使用方法

初始化实例

首先,您需要初始化插件,并提供从 OpenAI 控制台获取的 API 密钥:

/// Generate api key from openai console: https://platform.openai.com/account/api-keys
ChatGPTCompletions.instance.initialize(apiKey: "api_key_here");

文本补全(不带流响应)

以下是如何执行不带流响应的文本补全请求:

String? responseWithoutStream = await ChatGPTCompletions.instance.textCompletions(
  TextCompletionsParams(
    prompt: "What's Flutter?",
    model: GPTModel.davinci,
    temperature: 0.2,
    topP: 1,
    n: 1,
    stream: false,
    maxTokens: 2048,
  ),
);

print("OpenAI: $responseWithoutStream");

文本补全(带流响应)

如果需要实时接收响应,可以设置 stream 参数为 true

String responseWithStream = "";
StreamSubscription? responseSubscription;

await ChatGPTCompletions.instance.textCompletions(
  TextCompletionsParams(
    prompt: "What's Flutter?",
    model: GPTModel.davinci,
    temperature: 0.2,
    topP: 1,
    n: 1,
    stream: true, // 设置为 true 以启用流响应
    maxTokens: 2048,
  ),
  onStreamValue: (characters) {
    responseWithStream += characters;
    print(responseWithStream);
  },
  onStreamCreated: (subscription) {
    responseSubscription = subscription;
  },
);

停止生成响应:

responseSubscription?.cancel();

使用 GPT-3.5-Turbo 或 GPT-4 模型

对于更高级的模型,如 gpt-3.5-turbogpt-4,您可以使用 messagesTurbo 参数:

await ChatGPTCompletions.instance.textCompletions(
  TextCompletionsParams(
    messagesTurbo: [
      MessageTurbo(
        role: TurboRole.user,
        content: "What's Flutter?",
      ),
    ],
    model: GPTModel.gpt3p5turbo, // 切换到 gpt-3.5-turbo 模型
  ),
  onStreamValue: (characters) {
    responseWithStream += characters;
    print(responseWithStream);
  },
  onStreamCreated: (subscription) {
    responseSubscription = subscription;
  },
  // 延迟 100ms 接收下一个值
  debounce: const Duration(milliseconds: 100),
);

示例 Demo

以下是一个完整的示例代码,展示了如何使用 chatgpt_completions 插件进行文本补全:

// ignore_for_file: avoid_print

import 'dart:async';
import 'package:chatgpt_completions/chatgpt_completions.dart';

void main() async {
  /// Generate api key from openai console: https://platform.openai.com/account/api-keys
  ChatGPTCompletions.instance.initialize(apiKey: '<openai_api_key>');

  print("Generating answer without stream...");

  // Text completions without stream response (stream: false)
  String? responseWithoutStream = await ChatGPTCompletions.instance.textCompletions(
    TextCompletionsParams(
      prompt: "What's Flutter?",
      model: GPTModel.davinci,
      stream: false,
    ),
  );

  print("OpenAI: $responseWithoutStream");

  print("\n\n-> Generating answer with stream...");
  await Future.delayed(const Duration(seconds: 2));

  // Text completions with stream response (stream: true)
  String responseWithStream = "";

  StreamSubscription? responseSubscription;

  await ChatGPTCompletions.instance.textCompletions(
    TextCompletionsParams(
      prompt: "What's Flutter?",
      model: GPTModel.davinci,
    ),
    onStreamValue: (characters) {
      responseWithStream += characters;
      print(responseWithStream);
    },
    onStreamCreated: (subscription) {
      responseSubscription = subscription;
    },
    // Debounce 200ms for receive next value
    debounce: const Duration(milliseconds: 200),
  );

  // Stop generating
  responseSubscription?.cancel();

  // Using Chat Completion API: GPT-3.5-Turbo, GPT-4,...
  await ChatGPTCompletions.instance.textCompletions(
    TextCompletionsParams(
      messagesTurbo: [
        MessageTurbo(
          role: TurboRole.user,
          content: "Where is the tallest building in the world?",
        ),
      ],
      model: GPTModel.gpt3p5turbo,
    ),
    onStreamValue: (characters) {
      responseWithStream += characters;
      print(characters);
    },
    onStreamCreated: (subscription) {
      responseSubscription = subscription;
    },
    // Debounce 100ms for receive next value
    debounce: const Duration(milliseconds: 100),
  );
}

更多关于Flutter ChatGPT完成请求插件chatgpt_completions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter ChatGPT完成请求插件chatgpt_completions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用chatgpt_completions插件来完成ChatGPT请求的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了chatgpt_completions依赖:

dependencies:
  flutter:
    sdk: flutter
  chatgpt_completions: ^latest_version  # 请替换为最新的版本号

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

接下来,我们需要在Flutter应用中配置ChatGPT的API密钥,并发送请求。以下是一个完整的示例:

import 'package:flutter/material.dart';
import 'package:chatgpt_completions/chatgpt_completions.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ChatGPT Completions Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChatGPTPage(),
    );
  }
}

class ChatGPTPage extends StatefulWidget {
  @override
  _ChatGPTPageState createState() => _ChatGPTPageState();
}

class _ChatGPTPageState extends State<ChatGPTPage> {
  final ChatGPTClient _chatGPTClient = ChatGPTClient(apiKey: 'YOUR_API_KEY'); // 请替换为你的ChatGPT API密钥
  String _responseText = '';

  void _sendRequest() async {
    try {
      CompletionRequest request = CompletionRequest(
        prompt: 'Write a Flutter plugin to interact with ChatGPT API',
        maxTokens: 150,
        temperature: 0.7,
        n: 1,
        stop: null,
      );

      CompletionResponse response = await _chatGPTClient.createCompletion(request);
      setState(() {
        _responseText = response.choices!.first.text;
      });
    } catch (e) {
      setState(() {
        _responseText = 'Error: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ChatGPT Completions Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _sendRequest,
              child: Text('Send Request to ChatGPT'),
            ),
            SizedBox(height: 20),
            Text(
              _responseText,
              style: TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

注意事项:

  1. API密钥:确保你已经从OpenAI获取了API密钥,并将其替换为代码中的YOUR_API_KEY
  2. 错误处理:示例中包含了基本的错误处理,但你可能需要根据具体需求扩展错误处理逻辑。
  3. 依赖版本:请确保使用最新的chatgpt_completions包版本,因为API和包本身可能会随时间更新。

这个示例展示了如何使用chatgpt_completions插件在Flutter应用中发送ChatGPT请求,并显示返回的文本。你可以根据实际需求进一步定制和扩展这个示例。

回到顶部