×

如何使用 ChatGPT 构建简单的拼写检查器

作者:Terry2024.07.13来源:Web前端之家浏览:2592评论:0
关键词:OpenAI

在本教程中,我们将学习如何使用 ChatGPT 在云函数内构建拼写检查器。

OpenAI 的大型语言模型 ChapGPT 不仅仅是一个聊天界面。它是一个强大的工具,可以执行一系列任务,包括翻译、代码生成,甚至拼写检查(我们将在下面看到)。通过其 REST API,ChatGPT 提供了一种简单且极其有效的方式,可以将 AI 语言分析和生成功能添加到项目中。

123339.jpg

关键要点

  1. 利用 ChatGPT 进行高级拼写检查:本教程演示了如何通过 OpenAI API 有效地使用 ChatGPT 进行拼写检查任务,超越简单的错误检测,理解和纠正基于上下文的语法细微差别。

  2. 将 AI 与云功能相结合:本文展示了将 AI 功能集成到云功能中,特别是使用 AWS Lambda,提供了在基于云的环境中运行的拼写检查器的分步指南。

  3. 探索 OpenAI 中的函数调用:本教程的一个关键部分是探索 OpenAI 模型中的函数调用功能,该功能允许结构化 JSON 响应而不是纯文本,从而支持开发更复杂、更具交互性的 AI 应用程序。

云功能

以下是云功能的代码:

// Entry point for AWS Lambda.
export async function spellcheck({ body }: { body: string }) {

    // Read the text from the request body.
    const { textToCheck } = <{ textToCheck: string }>JSON.parse(body);

    //... perform spellchecking

    // Return an HTTP OK response
    return {
        statusCode: 200,
        body: JSON.stringify(...)
    };
}

此 Typescript 函数将成为 AWS Lambda 的处理程序,接受 HTTP 请求作为输入并返回 HTTP 响应。在上面的示例中,我们body从传入的 HTTP 请求中解构字段,将其解析为 JSON 并textToCheck从请求正文中读取属性。

openai 包

为了实现拼写检查功能,我们将发送textToCheck给 OpenAI 并要求 AI 模型为我们纠正任何拼写错误。为了方便起见,我们可以使用NPM 上的 openai 包。此包由 OpenAI 维护,作为 OpenAI REST API 的便捷 Javascript/Typescript 包装器。它包含我们需要的所有 Typescript 类型,使调用 ChatGPT 变得轻而易举。

像这样安装 openai 包:

npm install --save openai

然后,我们可以在函数处理程序中导入并创建该类的一个实例OpenAI,并传入我们的 OpenAI API 密钥,在此示例中,该密钥存储在名为 的环境变量中。(注册 OpenAI 后,您可以在用户设置中OPENAI_KEY找到您的 API 密钥。)


// Import the OpenAI package
import OpenAI from "openai";

export async function spellcheck({ body }: { body: string }) {

    const { textToCheck }: { textToCheck: string } = JSON.parse(body);

    // Create a new instance of OpenAI...
    const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });

    //... perform spellchecking

    return {
        statusCode: 200,
        body: JSON.stringify(...)
    };
}

示例文本

最后,我们需要一些有拼写错误的示例文本来进行测试,而最好的获取方式就是询问 ChatGPT 本身!

image.png

这段文字是对我们的拼写检查器的一次很好的测试,因为它包含明显的拼写错误,例如“essense”,但也包含一些更复杂的语法错误,例如将“princip al”写成“princip le ”。此类错误将对我们的拼写检查器进行测试,而不仅仅是查找词典中没有出现的单词;princip和principal都是有效的英语单词,因此我们的拼写检查器需要使用它们出现的上下文来正确检测此错误。真正的测试!

文本输入,文本输出

查找textToCheck输入中的拼写错误的最简单方法是创建一个提示,要求 ChatGPT 执行拼写检查并将更正后的版本返回给我们。在本教程的后面,我们将探索一种更强大的方法,可以从 OpenAI API 获取更多数据,但目前这种简单的方法将是一个很好的第一次迭代。

为此,我们需要两个提示。第一个是用户提示,指示 ChatGPT 检查拼写错误:

更正以下文本中的拼写和语法错误:

我们还需要一个系统提示来指导模型仅返回更正后的文本。

您是一位负责修改文本的文字编辑,您总是只回复修改后的文本,不提供任何解释或其他描述。

系统提示有助于为模型提供一些初始背景信息,并指示其在所有后续用户提示中以某种方式行事。在此处的系统提示中,我们指示 ChatGPT仅返回更正后的文本,而不是用描述或其他引导文本修饰它。


对于 API 调用,我们将使用上面实例化的类openai.chat.completions.create({...})上的方法OpenAI并返回响应消息。

综上所述,下面的代码将把这两个提示连同输入文本一起发送到openai.chat.completions.create({...})OpenAI API 上的端点。另请注意,我们将要使用的模型指定为gpt-3.5-turbo。我们可以为此使用任何 OpenAI 模型,包括 GPT-4:


// Import the OpenAI package
import OpenAI from "openai";

export async function spellcheck({ body }: { body: string }) {

    const { textToCheck }: { textToCheck: string } = JSON.parse(body);

    // Create a new instance of OpenAI.
    const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });

    const userPrompt = 'Correct the spelling and grammatical errors in the following text:\n\n';

    const gptResponse = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [
            {
                role: "system",
                content: "You are a copy editor that corrects pieces of text, you always reply with just the corrected text, no explanations or other description"
            },
            {
                role: "user",
                content: userPrompt + textToCheck
            }
        ]
    });

    // The message.content will contain the corrected text...
    const correctedText = gptResponse.choices[0].message.content;

    return {
        statusCode: 200,
        body: correctedText
    };
}

输入文本,输出 JSON

到目前为止,我们已经编写了一个 AWS Lambda 云函数,它将向 ChatGPT 发送一些文本并返回已删除拼写错误的更正版本。但该openai软件包允许我们做更多的事情。从我们的函数返回一些结构化数据,实际列出文本中进行的替换,这不是很好吗?这将使将此云函数与前端用户界面集成变得更加容易。

幸运的是,OpenAI 在 API 上提供了一个可以实现这一点的功能:函数调用。

函数调用是一些OpenAI 模型中存在的一项功能,允许 ChatGPT 使用一些结构化的 JSON 而不是简单的消息进行响应。通过指示 AI 模型调用函数并提供其可以调用的函数的详细信息(包括所有参数),我们可以从 API 收到更有用且更可预测的 JSON 响应。

要使用函数调用,我们需要functions在聊天完成创建选项中填充数组。在这里,我们告诉 ChatGPTmakeCorrections存在一个名为的函数,并且它可以使用一个名为的参数进行调用replacements

const gptResponse = await openai.chat.completions.create({
    model: "gpt-3.5-turbo-0613",
    messages: [ ... ],
    functions: [
        {
            name: "makeCorrections",
            description: "Makes spelling or grammar corrections to a body of text",
            parameters: {
                type: "object",
                properties: {
                    replacements: {
                        type: "array",
                        description: "Array of corrections",
                        items: {
                            type: "object",
                            properties: {
                                changeFrom: {
                                    type: "string",
                                    description: "The word or phrase to change"
                                },
                                changeTo: {
                                    type: "string",
                                    description: "The new word or phrase to replace it with"
                                },
                                reason: {
                                    type: "string",
                                    description: "The reason this change is being made",
                                    enum: ["Grammar", "Spelling"]
                                }                                    
                            }
                        }
                    }
                }
            }
        }
    ],    });

函数和所有参数的描述在这里很重要,因为 ChatGPT 无法访问我们的任何代码,因此它对该函数的所有了解都包含在我们提供的描述中。该parameters属性描述了 ChatGPT 可以调用的函数签名,并遵循JSON Schema来描述参数的数据结构。

上面的函数有一个名为的参数replacements,它与以下 TypeScript 类型一致:

type ReplacementsArgType = {
    changeFrom: string,
    changeTo: string,
    reason: "Grammar" | "Spelling"
}[]

在 JSON Schema 中定义这种类型将确保我们从 ChatGPT 返回的 JSON 符合这种可预测的形状,并且我们可以使用它将JSON.parse()其反序列化为这种类型的对象:

const args = <ReplacementsArgType>JSON.parse(responseChoice.message.function_call!.arguments);

综合起来

以下是我们的 AWS Lambda 函数的最终代码。它调用 ChatGPT 并返回一段文本的更正列表。

这里需要注意一些额外事项。如前所述,只有少数 OpenAI 模型支持函数调用。其中一个模型是gpt-3.5-turbo-0613,因此已在对完成端点的调用中指定了这一点。我们还在function_call: { name: 'makeCorrections' }调用中添加了。此属性是向模型发出的指令,我们希望它返回调用我们的函数所需的参数makeCorrections,并且我们不希望它返回聊天消息:

import OpenAI from "openai";
import { APIGatewayEvent } from "aws-lambda";

type ReplacementsArgType = {
    changeFrom: string,
    changeTo: string,
    reason: "Grammar" | "Spelling"
}[]

export async function main({ body }: { body: string }) {

    const { textToCheck }: { textToCheck: string } = JSON.parse(body);

    const openai = new OpenAI({ apiKey: process.env.OPENAI_KEY });

    const prompt = 'Correct the spelling and grammatical errors in the following text:\n\n';

    // Make ChatGPT request using Function Calling...
    const gptResponse = await openai.chat.completions.create({
        model: "gpt-3.5-turbo-0613",
        messages: [
            {
                role: "user",
                content: prompt + textToCheck
            }
        ],
        functions: [
            {
                name: "makeCorrections",
                description: "Makes spelling or grammar corrections to a body of text",
                parameters: {
                    type: "object",
                    properties: {
                        replacements: {
                            type: "array",
                            description: "Array of corrections",
                            items: {
                                type: "object",
                                properties: {
                                    changeFrom: {
                                        type: "string",
                                        description: "The word or phrase to change"
                                    },
                                    changeTo: {
                                        type: "string",
                                        description: "The new word or phrase to replace it with"
                                    },
                                    reason: {
                                        type: "string",
                                        description: "The reason this change is being made",
                                        enum: ["Grammar", "Spelling"]
                                    }                                    
                                }
                            }
                        }
                    }
                }
            }
        ],
        function_call: { name: 'makeCorrections' }
    });

    const [responseChoice] = gptResponse.choices;

    // Deserialize the "function_call.arguments" property in the response
    const args = <ReplacementsArgType>JSON.parse(responseChoice.message.function_call!.arguments);

    return {
        statusCode: 200,
        body: JSON.stringify(args)
    };
}

此函数可以部署到 AWS Lambda 并使用以下请求正文通过 HTTP 调用:

{
    "textToCheck": "Thier journey to the nearby city was quite the experience. If you could of seen the way people reacted when they first saw the castle, it was as if they were taken back to a era long forgotten. The architecture, with it's grand spires and ancient motifs, captured the essense of a time when knights roamed the land. The principle reason for visiting, however, was the art exhibition showcasing several peices from renowned artists of the past."}

它将以 JSON 数组的形式返回更正列表,如下所示:

[
  {
    "changeFrom": "Thier",
    "changeTo": "Their",
    "reason": "Spelling"
  },
  {
    "changeFrom": "could of",
    "changeTo": "could have",
    "reason": "Grammar"
  },
  {
    "changeFrom": "a",
    "changeTo": "an",
    "reason": "Grammar"
  },//...]

结论

通过利用 OpenAI API 和云函数,您可以创建不仅能识别拼写错误还能理解上下文的应用程序,从而捕捉典型拼写检查器可能忽略的复杂语法细微差别。本教程提供了基础,但 ChatGPT 在语言分析和纠正方面的潜在应用非常广泛。随着人工智能的不断发展,此类工具的功能也将不断发展。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/OpenAIgtp23if823048.html

网友评论文明上网理性发言 已有0人参与

发表评论: