第十一章 - 借助AI提升工作效率
掌握如何运用AI大语言模型快速完成任务
本章将介绍使用AI大语言模型(LLMs)加速任务完成的技巧。本书已涵盖诸多主题:通过读取和遍历AST提取有用数据、生成AST自动创建代码、编写代码检查工具、使用类型检查器等。现在,我们将探讨如何借助AI更快更准确地编写脚本,同时保持对代码的理解能力,及时修正AI给出的错误建议。
当前可选AI工具众多。主流产品包括OpenAI的ChatGPT和GPT-4、微软的BingAI以及谷歌的Bard。还有类似Quora出品的Poe这类集成多工具的一站式平台。
工具选择建议
处理代码相关任务时,优先选择受过代码训练的模型。GPT 3.5和GPT 4在编程任务中表现优异,Bing AI的代码处理能力也值得肯定。Poe等工具适合同时测试多个模型,建议多尝试几种。本章后续示例将使用ChatGPT免费版和Bing AI,因其最易获取。
提示词技巧
生成TypeScript代码或遍历AST时,明确要求AI使用TypeScript编译器API至关重要。否则AI可能错误推荐NPM包或生成无效方案。
从AST提取数据
假设要从代码文件中提取所有类定义,可以这样提问:
使用TypeScript编译器API,找出并记录任意给定文件中定义的所有类
GPT 3.5可能返回如下代码:
import * as ts from "typescript"
function findClasses(node: ts.Node, sourceFile: ts.SourceFile) {
if (ts.isClassDeclaration(node) && node.name) {
const className = node.name.text
const classStart = node.getStart(sourceFile)
const classEnd = node.getEnd(sourceFile)
const classText = sourceFile.text.substring(classStart, classEnd)
console.log("Class:", className)
console.log("Class Text:", classText)
console.log("------------------------")
}
ts.forEachChild(node, (childNode) => findClasses(childNode, sourceFile))
}
function findClassesInFile(filePath: string) {
const sourceCode = ts.sys.readFile(filePath)
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true)
const compilerOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS
}
const transpileResult = ts.transpileModule(sourceCode, {
compilerOptions,
fileName: filePath
})
const transpiledCode = transpileResult.outputText
const transpiledSourceFile = ts.createSourceFile(filePath, transpiledCode, ts.ScriptTarget.ES5, true)
findClasses(transpiledSourceFile, transpiledSourceFile)
}
findClassesInFile("path/to/your/file.ts")
这个方案存在缺陷:将代码转译为ES5标准时,类声明被转换为函数原型,导致ts.isClassDeclaration(node)始终返回false。不过它提供了良好的修改基础。
GPT 4生成的方案更为可靠:
import * as ts from "typescript"
function getClasses(sourceFile: ts.SourceFile): string[] {
const classes: string[] = []
const visit = (node: ts.Node): void => {
if (ts.isClassDeclaration(node) && node.name) {
classes.push(node.name.text)
}
ts.forEachChild(node, visit)
}
visit(sourceFile)
return classes
}
function findClassesInFile(filePath: string): void {
const program = ts.createProgram([filePath], {})
const sourceFile = program.getSourceFile(filePath)
if (!sourceFile) {
console.error(`Could not find source file: ${filePath}`)
return
}
const classes = getClasses(sourceFile)
console.log(`Classes found in ${filePath}:`, classes)
}
const filePath = "./example.ts"
findClassesInFile(filePath)
该代码能正确创建程序并遍历AST找出所有类名。而Bing AI(截至2023年中)对此提示无法生成有效代码,Poe的Sage模型生成的代码也存在运行时错误。建议多尝试不同模型。
注意:多数AI返回TypeScript代码片段,需转译为JavaScript后执行,或直接要求AI返回JavaScript代码。
代码生成技巧
本书另一重点是代码生成。虽然TypeScript编译器API是最佳选择,但复杂任务往往需要多次提示,并将AI生成的结果组合成可用脚本。
以第9章的ThreeJS画线任务为例,可以这样提问:
给定如下配置,如何使用ThreeJS绘制线条?
{
materialColor: 0x0000ff,
points: [
[10, 0, 0],
[0, 10, 0],
[0, 0, 0],
],
}
ChatGPT可能返回:
const config = {
materialColor: 0x0000ff,
points: [
[10, 0, 0],
[0, 10, 0],
[0, 0, 0]
]
}
const scene = new THREE.Scene()
const material = new THREE.LineBasicMaterial({ color: config.materialColor })
const geometry = new THREE.Geometry()
config.points.forEach((point) => {
const [x, y, z] = point
geometry.vertices.push(new THREE.Vector3(x, y, z))
})
const line = new THREE.Line(geometry, material)
scene.add(line)
提供配置样本有助于AI生成更符合需求的代码。上下文信息越丰富,AI输出质量越高。
创建定制机器人
针对特定任务,可以创建预置上下文的专属AI机器人。
Poe等工具支持快速创建定制机器人。只需选择基础模型(目前仅ChatGPT和Claude-instant可选),设置预置提示词即可。用户每次提问时,系统都会自动注入这些预设提示。
若现有基础模型不满足需求,Poe还支持对接自定义API端点,完全自主处理提问和响应。
ThreeJS机器人示例
本书配套的ThreeJS机器人就是典型案例。基于ChatGPT模型,预设提示词为"使用ThreeJS输出以下代码"。当用户输入"创建3D球体"时,将返回:
const geometry = new THREE.SphereGeometry(5, 32, 32)
const material = new THREE.MeshBasicMaterial({ color: 0xffff00 })
const ball = new THREE.Mesh(geometry, material)
scene.add(ball)
本章小结
AI代码生成尚处早期阶段,但已能产出可用脚本。建议运用本书介绍的测试验证方法,确保AI生成结果符合预期。通过合理提示和结果校验,AI将成为开发者的高效助手。