Skip to content

Commit 5d45d74

Browse files
committed
Fix main entrypoint, async nits, global tools
- Changed main entrypoint js in package.json to be where it is now. - If you know something is defined but TS doesn't, you can use the damnit flag, `!` instead of eslint ignore comments. `this.promise = new Promise(() => { .... this.process!.on('exit', ...)` - `async function foo(): Promise<x> { return await bar() }` is redundant. This is functionally the same as just saying `function foo(): Promise<x> { return bar() }` but makes debugging harder. By marking the function async and awaiting you're creating an extra promise that does nothing but immediately resolve after bar's does. You don't have to declare your function as async in order for the consumer to be able to await it. The consumer just needs a function that returns a Promise (which bar() already returns). On your side you only have to say `async` if you want to use `await` for something in the body (other than just immediately returning it) - Similarly text() and json() have that + a 2nd layer of extra promises. `throw` is the same as reject() and throws 'cascade' up so all json() needs to be is `return JSON.parse(await this.text())`. Also the returned JSON isn't necessarily an object, it could be an array or a random scalar so it should just return `any`. - Changed default for a text block to just plain 'text' format, markdown will be a separate option (that the parser doesn't need to know about) - Parameters (or ToolDef) should support globalTools and toolDefToString serializing them.
1 parent 6ea6f8b commit 5d45d74

File tree

2 files changed

+44
-50
lines changed

2 files changed

+44
-50
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "@gptscript-ai/gptscript",
33
"version": "v0.5.0",
44
"description": "Run gptscript in node.js",
5-
"main": "lib/gptscript.js",
5+
"main": "dist/gptscript.js",
66
"repository": {
77
"type": "git",
88
"url": "git+https://github.com/gptscript-ai/node-gptscript.git"

src/gptscript.ts

+43-49
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,7 @@ export class Run extends events.EventEmitter {
151151
})
152152
}
153153
this.promise = new Promise((resolve, reject) => {
154-
// @ts-ignore
155-
this.process.on("exit", (code: number | null, signal: NodeJS.Signals | null) => {
154+
this.process!.on("exit", (code: number | null, signal: NodeJS.Signals | null) => {
156155
server.close()
157156

158157
if (signal) {
@@ -267,13 +266,18 @@ export class Run extends events.EventEmitter {
267266
}
268267

269268
emitEvent(data: string): string {
270-
for (const event of data.split("\n")) {
271-
if (event.trim() === "") continue
269+
for (let event of data.split("\n")) {
270+
event = event.trim()
271+
272+
if (!event) {
273+
continue
274+
}
275+
272276
let f: Frame
273277
try {
274-
f = JSON.parse(event.trim()) as Frame
278+
f = JSON.parse(event) as Frame
275279
} catch (error) {
276-
return event.trim()
280+
return event
277281
}
278282

279283
if (!this.state) {
@@ -354,35 +358,20 @@ export class Run extends events.EventEmitter {
354358
return this
355359
}
356360

357-
public async text(): Promise<string> {
358-
return new Promise((resolve, reject) => {
359-
if (this.err) {
360-
reject(this.err)
361-
}
362-
if (!this.promise) {
363-
reject(new Error("Run not started"))
364-
}
361+
public text(): Promise<string> {
362+
if (this.err) {
363+
throw new Error(this.err)
364+
}
365365

366-
this.promise?.then(text => {
367-
resolve(text)
368-
}).catch(error => {
369-
reject(error)
370-
})
371-
})
366+
if (!this.promise) {
367+
throw new Error("Run not started")
368+
}
369+
370+
return this.promise
372371
}
373372

374-
public async json(): Promise<Record<string, any>> {
375-
return new Promise((resolve, reject) => {
376-
this.text().then(text => {
377-
try {
378-
resolve(JSON.parse(text))
379-
} catch (error) {
380-
reject(error)
381-
}
382-
}).catch(error => {
383-
reject(error)
384-
})
385-
})
373+
public async json(): Promise<any> {
374+
return JSON.parse(await this.text())
386375
}
387376

388377
public abort(): void {
@@ -424,6 +413,7 @@ export interface Parameters {
424413
internalPrompt: boolean
425414
arguments: ArgumentSchema
426415
tools: string[]
416+
globalTools: string[]
427417
export: string[]
428418
blocking: boolean
429419
}
@@ -456,7 +446,6 @@ export interface Tool extends ToolDef {
456446
type: "tool"
457447
toolMapping: Record<string, string>
458448
localTools: Record<string, string>
459-
globalTools: string[]
460449
source: SourceRef
461450
workingDir: string
462451
}
@@ -629,26 +618,26 @@ function getCmdPath(): string {
629618
return path.join(__dirname, "..", "bin", "gptscript")
630619
}
631620

632-
export async function listTools(gptscriptURL?: string): Promise<string> {
633-
return await runBasicCommand("list-tools", gptscriptURL)
621+
export function listTools(gptscriptURL?: string): Promise<string> {
622+
return runBasicCommand("list-tools", gptscriptURL)
634623
}
635624

636-
export async function listModels(gptscriptURL?: string): Promise<string> {
637-
return await runBasicCommand("list-models", gptscriptURL)
625+
export function listModels(gptscriptURL?: string): Promise<string> {
626+
return runBasicCommand("list-models", gptscriptURL)
638627
}
639628

640-
export async function version(gptscriptURL?: string): Promise<string> {
641-
return await runBasicCommand("version", gptscriptURL)
629+
export function version(gptscriptURL?: string): Promise<string> {
630+
return runBasicCommand("version", gptscriptURL)
642631
}
643632

644-
async function runBasicCommand(cmd: string, gptscriptURL?: string): Promise<string> {
633+
function runBasicCommand(cmd: string, gptscriptURL?: string): Promise<string> {
645634
const r = new Run("", {gptscriptURL: gptscriptURL})
646635
if (gptscriptURL) {
647636
r.request(cmd, null)
648637
} else {
649638
r.exec(getCmdPath(), ["--" + cmd])
650639
}
651-
return await r.text()
640+
return r.text()
652641
}
653642

654643
export function run(toolName: string, opts: RunOpts): Run {
@@ -707,7 +696,7 @@ export async function parseTool(tool: string, gptscriptURL?: string): Promise<Bl
707696
return parseBlocksFromNodes((await r.json()).nodes)
708697
}
709698

710-
export async function stringify(blocks: Block[], gptscriptURL?: string): Promise<string> {
699+
export function stringify(blocks: Block[], gptscriptURL?: string): Promise<string> {
711700
const nodes: any[] = []
712701

713702
for (const block of blocks) {
@@ -720,7 +709,7 @@ export async function stringify(blocks: Block[], gptscriptURL?: string): Promise
720709
} else if (block.type === "text") {
721710
nodes.push({
722711
textNode: {
723-
text: "!" + (block.format || "markdown") + "\n" + block.content
712+
text: "!" + (block.format || "text") + "\n" + block.content
724713
}
725714
})
726715
}
@@ -733,7 +722,7 @@ export async function stringify(blocks: Block[], gptscriptURL?: string): Promise
733722
r.exec(getCmdPath(), ["fmt", "-"], JSON.stringify({nodes: nodes}))
734723
}
735724

736-
return await r.text()
725+
return r.text()
737726
}
738727

739728
function parseBlocksFromNodes(nodes: any[]): Block[] {
@@ -749,7 +738,7 @@ function parseBlocksFromNodes(nodes: any[]): Block[] {
749738
})
750739
}
751740
if (node.textNode) {
752-
const format = node.textNode.text.substring(1, node.textNode.text.indexOf("\n")).trim() || "markdown"
741+
const format = node.textNode.text.substring(1, node.textNode.text.indexOf("\n")).trim() || "text"
753742
blocks.push({
754743
id: randomId("text-"),
755744
type: "text",
@@ -775,11 +764,14 @@ function toolDefToString(tool: ToolDef) {
775764
if (tool.description) {
776765
toolInfo.push(`Description: ${tool.description}`)
777766
}
778-
if (tool.tools && tool.tools.length > 0) {
767+
if (tool.globalTools?.length) {
768+
toolInfo.push(`Global Tools: ${tool.globalTools.join(", ")}`)
769+
}
770+
if (tool.tools?.length > 0) {
779771
toolInfo.push(`Tools: ${tool.tools.join(", ")}`)
780772
}
781773
if (tool.maxTokens !== undefined) {
782-
toolInfo.push(`Max tokens: ${tool.maxTokens}`)
774+
toolInfo.push(`Max Tokens: ${tool.maxTokens}`)
783775
}
784776
if (tool.modelName) {
785777
toolInfo.push(`Model: ${tool.modelName}`)
@@ -799,9 +791,11 @@ function toolDefToString(tool: ToolDef) {
799791
}
800792
}
801793
if (tool.internalPrompt) {
802-
toolInfo.push(`Internal prompt: ${tool.internalPrompt}`)
794+
toolInfo.push(`Internal Prompt: ${tool.internalPrompt}`)
803795
}
796+
804797
if (tool.instructions) {
798+
toolInfo.push("")
805799
toolInfo.push(tool.instructions)
806800
}
807801

@@ -810,4 +804,4 @@ function toolDefToString(tool: ToolDef) {
810804

811805
function randomId(prefix: string): string {
812806
return prefix + Math.random().toString(36).substring(2, 12)
813-
}
807+
}

0 commit comments

Comments
 (0)