Use laf cloud development to implement uni-app to call chatGPT API, and realize dialogue with openai
1. Realize the background interface
Register laf cloud development account https://laf.dev/
Enter this page after registering an application:
- Download depends on chatgpt
- Configure apiKey
- Write the send function
//send函数源码
import cloud from '@lafjs/cloud'
export async function main(ctx: FunctionContext) {
const {
ChatGPTAPI } = await import('chatgpt')
const data = ctx.body
// 这里需要把 api 对象放入 cloud.shared 不然无法追踪上下文
let api = cloud.shared.get('api')
if (!api) {
api = new ChatGPTAPI({
apiKey: cloud.env.CHAT_GPT_API_KEY })
cloud.shared.set('api', api)
}
let res
// 这里前端如果传过来 parentMessageId 则代表需要追踪上下文
if (!data.parentMessageId) {
res = await api.sendMessage(data.message)
} else {
res = await api.sendMessage(data.message, {
parentMessageId: data.parentMessageId })
}
return res
}
Configure your apiKey
2. In the uni-app applet code
//Encapsulate cloud
import {
Cloud } from "laf-client-sdk"
// 创建 cloud 对象 这里需要将 <appid> 替换成自己的 App ID
// const cloud = new Cloud({
// baseUrl: "https://irrbat.laf.dev",
// getAccessToken: () => "", // 这里不需要授权,先填空
// })
const cloud = new Cloud({
// the laf app server base url
baseUrl: "https://irrbat.laf.dev",
// the database proxy entry, `app` is the policy name which response for the security of database access
getAccessToken: () => "",
environment: "uniapp",
})
export default cloud
send message method
import cloud from './CloudService'
export async function sendToGpt (msg,parentMessageId=null) {
// 我们提问的内容
const message = msg
let res
// 与云函数逻辑一样,有上下文 id 就传入
if (!parentMessageId) {
res = await cloud.invoke("send", {
message })
} else {
res = await cloud.invoke("send", {
message, parentMessageId: parentMessageId })
}
return Promise.resolve(res)
}
Used in WeChat Mini Programs
const cloud = new Cloud({
// the laf app server base url
baseUrl: "https://APPID.lafyun.com",
// the database proxy entry, `app` is the policy name which response for the security of database access
dbProxyUrl: "/proxy/app",
getAccessToken: () => localStorage.getItem("access_token"),
environment: "wxmp",
});
3. Realize the effect
insert image description here