Flutter OpenAI API集成插件openai_api的使用

Flutter OpenAI API集成插件openai_api的使用

简介

openai_api 是一个用于Flutter应用中与OpenAI API交互的插件。它支持多种API,包括聊天、图像生成和音频处理等。本文将介绍如何在Flutter项目中使用这个插件。

特性

  • ✅ 聊天
  • ✅ 图像生成
  • ✅ 音频(文本转语音TTS和语音识别STT)
  • ✅ 模型管理
  • ❌ 编辑(不支持)
  • ❌ 补全(不支持)
  • ❌ 嵌入(不支持)
  • ❌ 文件(不支持)
  • ❌ 微调(不支持)
  • ❌ 审核(不支持)
  • ❌ 引擎(不支持)

使用指南

初始化OpenAI客户端

首先,你需要初始化一个OpenaiClient实例:

final client = OpenaiClient(
  config: OpenaiConfig(
    apiKey: Env.apiKey,   // 从openai.com获取你的API密钥
    baseUrl: Env.baseUrl,  // 如果需要设置反向代理API,请在此处指定
    httpProxy: Env.httpProxy,  // 如果需要通过HTTP代理访问API,请在此处指定
  ),
);

调用API

音频转录

下面是一个如何使用此插件进行音频转录的例子:

final result = await client.createTranscription(
  TranscriptionRequest(
    file: 'assets/ttsmaker-file-2023-3-22-14-57-0.mp3',
  ),
);
print(result.text);

音频翻译

对于音频翻译,你可以这样操作:

final translateResult = await client.createTraslation(
  TranslationRequest(
    file: 'assets/ttsmaker-file-2023-3-22-17-27-30.mp3',
  ),
);
print(translateResult.text);

示例代码

这里提供了一个完整的示例,展示了如何使用openai_api进行聊天、图像生成等功能:

import 'dart:convert';
import 'package:openai_api/openai_api.dart';

void main() async {
  final client = OpenaiClient(
    config: OpenaiConfig(
      apiKey: Env.apiKey,
      baseUrl: Env.baseUrl,
      httpProxy: Env.httpProxy,
    ),
  );

  await runConversation(client);

  client.client.close();
}

Future<void> runConversation(OpenaiClient client) async {
  final messages = [
    ChatMessage.user(content: "What's the weather like in San Francisco, Tokyo, Shanghai and Paris?")
  ];

  final tools = [
    ChatTool(
        function: ChatFunction(
          name: "get_current_weather",
          description: "Get the current weather in a given location",
          parameters: ChatFunctionParameters(
            type: "object",
            properties: {
              "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
              "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            required: ["location"],
          ),
        ))
  ];

  final result = await client.sendChatCompletion(ChatCompletionRequest(
    model: Models.gpt4_1106Preview,
    messages: messages,
    tools: tools,
    toolChoice: "auto",
  ));

  final msg = result.choices.first.message;
  final toolCalls = msg?.toolCalls;

  if (toolCalls != null) {
    final availableFunctions = {"get_current_weather": getCurrentWeatherOnline};
    messages.add(msg!);

    for (final toolCall in toolCalls) {
      final functionName = toolCall.function.name;
      final toCall = availableFunctions[functionName];
      final args = json.decode(toolCall.function.arguments);
      final res = await toCall!(args["location"]);
      messages.add(
        ChatMessage.tool(content: res, toolCallId: toolCall.id, name: functionName),
      );
    }

    final response = await client.sendChatCompletion(ChatCompletionRequest(
      messages: messages,
      model: Models.gpt4_1106Preview,
    ));
    print(response.choices.first.message?.content);
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中集成并使用openai_api插件的示例代码。这个示例将展示如何初始化OpenAI API客户端,并向API发送一个请求以生成文本。

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

dependencies:
  flutter:
    sdk: flutter
  openai_api: ^最新版本号  # 请替换为实际发布的最新版本号

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

接下来,在你的Flutter应用中,你可以按照以下步骤使用openai_api插件:

  1. 导入包并初始化OpenAI API客户端
import 'package:flutter/material.dart';
import 'package:openai_api/openai_api.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('OpenAI API Integration'),
        ),
        body: Center(
          child: OpenAIExample(),
        ),
      ),
    );
  }
}

class OpenAIExample extends StatefulWidget {
  @override
  _OpenAIExampleState createState() => _OpenAIExampleState();
}

class _OpenAIExampleState extends State<OpenAIExample> {
  final OpenAIApi _openaiApi = OpenAIApi(apiKey: '你的OpenAI API密钥');

  String? _responseText;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
          onPressed: _generateText,
          child: Text('Generate Text'),
        ),
        if (_responseText != null)
          Text(
            _responseText!,
            style: TextStyle(fontSize: 18),
            maxLines: 10,
            overflow: TextOverflow.ellipsis,
          ),
      ],
    );
  }

  Future<void> _generateText() async {
    try {
      final Completion completion = await _openaiApi.createCompletion(
        engine: 'davinci',
        prompt: 'Once upon a time',
        maxTokens: 150,
        temperature: 0.7,
      );
      setState(() {
        _responseText = completion.choices!.first.text;
      });
    } catch (e) {
      print('Error: $e');
      setState(() {
        _responseText = 'Error generating text.';
      });
    }
  }
}
  1. 注意事项
  • 替换你的OpenAI API密钥为你的实际OpenAI API密钥。
  • engine参数指定了要使用的模型,这里使用的是davinci。OpenAI提供了多个模型,你可以根据需要选择。
  • prompt参数是你希望模型继续生成的文本。
  • maxTokens参数限制了生成的文本的最大令牌数。
  • temperature参数控制生成文本的随机性。值越高,生成的文本越具有创造性,但也可能更不相关。

这个示例展示了如何使用openai_api插件在Flutter应用中集成OpenAI API,并生成文本。你可以根据需要调整参数,以满足你的具体需求。

回到顶部