ChatGpt 实在太火爆了,很多人在问我怎么使用 chatgpt 开发一个 AI 应用程序。这不就来了吗~

开始

你所需要准备的一个OpenAI 的密钥和一点点代码来发送提示并返回结果,例如下面这段代码:

import { OpenAIApi, Configuration } from 'openai'const openAi = new OpenAIApi(new Configuration({ apiKey: YOUR_KEY }) // openAi 密钥);async function askGpt(prompt) {const completion = await openAi.createChatCompletion({model: 'gpt-3.5-turbo',messages: [{ role: 'user', content: prompt }],});return completion.data.choices[0].message.content;}

就靠这段代码,你现在就可以开始用它做出不可思议的东西了!

构造提示模板

使用AI执行命令的基本结构是要求用户输入,构建一个提示,并生成结果。

例如,要翻译文本,你可以使用这样的代码:

const text = "Hello, my name is Steve";const prompt = "Translate to spanish";const newText = await askGpt(`I will give you a promnpt to modify some textThe text is: ${text}The prompt is ${prompt}Please only return the modified text`);// newText is: "Hola, me llamo Steve"

生成代码

正如你可能已经看到的那样,ChatGPT 不仅可以很好地处理普通单词,还可以处理代码。

因此,我们可以轻松构建一个应用程序,这个应用是通过将一个框架转换为另一个框架来帮助你学习或迁移到一个新框架,例如将 React 组件转换为Svelte

我们可以制作这样一个应用:

const sourceFramework = 'react'const generateFramework = 'svelte'const sourceCode = `import React, { useState } from 'react';function Counter() {const [count, setCount] = useState(0);const increment = () => { setCount(count + 1) };const decrement = () => { setCount(count - 1) };return (

Counter: {count}

);}
`
const newCode = await askGpt(`Please translate this code from ${sourceFramework} to ${generateFramework}.The code is:${sourceCode}Please only give me the new code, no other words.`)

输出之后,我们会得到这样的 Svelte 代码:

<script>let count = 0;function increment() { count += 1 }function decrement() { count -= 1 }</script><h1>Counter: {count}</h1><button on:click={increment}>Increment</button><button on:click={decrement}>Decrement</button>

好了! 是不是非常容易!!!

接下来,我们再来看一些例子:

一些例子

AI Shell

将人类语言转换为 CLI 命令,那我可以搞一个由 AI Shell 来实现:

// Ask in a CLIconst prompt = 'what is my ip address'const result = askGpt(`Please create a one line bash command that can do the following: ${prompt}`)

将其放入CLI界面中,您将得到:


注意,你甚至不需要知道如何拼写。

AI Agents

目前法学硕士都在活跃地研究领域之一是 AI 代理。这个应用能让 AI 帮你做一些事情,然后做完这个事情之后,它会反馈给你。

const prompt = 'Book a table for 2 for indian food tomorrow'let actionResult = '';while (true) {const result = askGpt(`You are an AI assistant that can browse the web.Your prompt is to : ${prompt}The actions you can take are- navigate to a URL, like {"action":"navigate","url":"..."}- click on an element, like {"action":"click", ...}The result of your last action was: ${actionResult}What next action will you take" />`)const action = parseAction(result)actionResult = await executeAction(action)}

上述代码正是 GPT 助手——它可以自主浏览网页以尝试完成任务的 AI。

例如,当被要求更新 REAMDE 以添加“steve is awesome”时,它向Qwik repo打开了一个pull request: