当前位置: 首页 > article >正文

Using OpenAI API from Firebase Cloud Functions in flutter app

题意:“在 Flutter 应用中通过 Firebase Cloud Functions 使用 OpenAI API。”

问题背景:

I can't figure out how to make this work.

“我不知道该如何让这正常运行。”

This is my cloud function in Javascript. I'm trying a simple code to see if the connection works (other cloud functions not using the openai package do work fine).

“这是我用 JavaScript 编写的云函数。我正在尝试一个简单的代码来测试连接是否正常(其他不使用 openai 包的云函数运行良好)。”

The function does work on GCP when I test it, but won't connect to my flutter function for some reason:

“该函数在 GCP 上测试时可以运行,但由于某种原因无法连接到我的 Flutter 函数。”

error:

flutter: Error calling Firebase Function: internal Response is missing data field.

Cloud function

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
const cors = require('cors')({ origin: true });
admin.initializeApp();

exports.openAiResponse2 = functions.https.onRequest(async (request, response) => {
  const apiKey = 'sk-';
  cors(request, response, async () => {
    try {
      const apiResponse = await axios.post(
        'https://api.openai.com/v1/chat/completions',
        {
          model: 'gpt-3.5-turbo',
          messages: [{ role: 'user', content: 'Say this is a test!' }],
          temperature: 0.7,
        },
        {
          headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json',
          },
        },
      );

     // response.status(200).json({ message: 'OpenAI API connection successful.', engines: apiResponse.data });
        response.status(200).json({
              message: 'OpenAI API connection successful.',
              completion: apiResponse.data.choices[0].message.content,
            });
    } catch (error) {
      console.error('Error connecting to OpenAI API:', error);
      response.status(500).send('Error connecting to OpenAI API');
    }
  });
});

Flutter:

Future<void> talkToMe2() async {
  try {
    HttpsCallable callable = FirebaseFunctions.instance.httpsCallable('openAiResponse2');
    print(callable);
    final response = await callable.call();
    print('response is $response');
    print('External API response: ${response.data}');
  } on FirebaseFunctionsException catch (e) {
    print('Error calling Firebase Function: ${e.code} ${e.message}');
  } catch (e) {
    print('Error calling Firebase Function: $e');
  }
}

This is my package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^11.5.0",
    "firebase-functions": "^4.2.0",
    "openai": "^3.2.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^3.0.0"
  },
  "private": true
}

And my flutter doctor

[✓] Flutter (Channel stable, 3.7.12, on macOS 13.2 22D49 darwin-arm64, locale en-ES)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] VS Code (version 1.77.3)
[✓] Connected device (4 available)
[✓] HTTP Host Availability

I can't seem to find a solution. Thanks!

“我似乎找不到解决方案。谢谢!”

问题解决:

I am not a flutter developer but httpsCallable is for onCall not onRequest.

“我不是 Flutter 开发者,但 `httpsCallable` 是用于 `onCall` 而不是 `onRequest`。”

https://firebase.google.com/docs/functions/callable?gen=2nd

https://firebase.google.com/docs/functions/http-events?gen=2nd

If you look at the flutter sample, you should have something like below for https callable

“如果你查看 Flutter 示例,针对 https callable,你应该有类似下面的代码。”

const functions = require('firebase-functions');

exports.listFruit = functions.https.onCall((data, context) => { //<<<-- not onRequest
  return ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes"]
});


http://www.kler.cn/news/306473.html

相关文章:

  • uniapp(H5)设置反向代理,设置成功后页面报错
  • 前端网络请求库:Axios
  • C++初阶学习——探索STL奥秘——vector的模拟实现
  • 20Kg载重30分钟续航多旋翼无人机技术详解
  • 微服务下功能权限与数据权限的设计与实现
  • 差分进化算法(DE算法)求解实例---旅行商问题 (TSP)
  • C语言自定义类型-联合与枚举
  • 无人机视角下落水救援检测数据集
  • Vue学习:props验证的一个小细节“Prop 名字格式”
  • 本专题大纲
  • golang学习笔记16——golang部署与运维全攻略
  • Java高级Day42-Class类
  • Linux——应用层自定义协议与序列化
  • docker 学习笔记
  • 【详细原理】蒙特卡洛树搜索
  • 财富通公司开发洗车小程序有哪些用处?
  • 通过load->model()加载数据模型:在爬虫中实现动态数据处理
  • MySQL 变量查询如何使用索引
  • 用户体验在网站建设中的重要性
  • 下载chromedriver驱动
  • CesiumJS+SuperMap3D.js混用实现可视域分析 S3M图层加载 裁剪区域绘制
  • EmguCV学习笔记 VB.Net 11.5 目标检测
  • 浪潮信息首推3秒智能控温!告别服务器开机噪音
  • 设计师福音:CleanClip 如何提升创意工作效率
  • 网络安全宣传周 | DNS安全威胁与应对措施分享
  • 数据管理生态的核心解析:数据库、数据仓库、数据湖、数据平台与数据中台的关系与实现
  • uniapp在开发app时上传文件时的问题
  • 配置RHEL和centOS的阿里云镜像源
  • Python--常见的数据格式转换
  • 安卓获取apk的公钥,用于申请app备案等