Skip to content

Commit 3041aee

Browse files
committed
fix: allow retry of failed runs
1 parent 0c8c0f1 commit 3041aee

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/gptscript.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -238,25 +238,25 @@ export class Run {
238238
}
239239

240240
nextChat(input: string = ""): Run {
241-
if (this.state === RunState.Finished || this.state === RunState.Error) {
242-
throw (new Error("Run already finished"))
241+
if (this.state !== RunState.Continue && this.state !== RunState.Creating && this.state !== RunState.Error) {
242+
throw (new Error(`Run must in creating, continue or error state, not ${this.state}`))
243243
}
244244

245245
let run = this
246246
if (run.state !== RunState.Creating) {
247247
run = new (this.constructor as any)(this.requestPath, this.filePath, this.content, this.opts, this.gptscriptURL)
248248
}
249249

250-
if (this.chatState) {
251-
run.chatState = this.chatState
252-
} else if (this.opts.chatState) {
253-
run.chatState = this.opts.chatState
250+
if (this.chatState && this.state === RunState.Continue) {
251+
// Only update the chat state if the previous run didn't error.
252+
// The chat state on opts will be the chat state for the last successful run.
253+
this.opts.chatState = this.chatState
254254
}
255255
run.opts.input = input
256256
if (run.content !== "") {
257-
run.request({content: this.content, chatState: run.chatState})
257+
run.request({content: this.content, ...this.opts})
258258
} else {
259-
run.request({file: this.filePath, chatState: run.chatState})
259+
run.request({file: this.filePath, ...this.opts})
260260
}
261261

262262
return run

tests/gptscript.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as gptscript from "../src/gptscript"
2+
import {RunState} from "../src/gptscript"
23
import path from "path"
34
import {fileURLToPath} from "url"
45

@@ -470,4 +471,23 @@ describe("gptscript module", () => {
470471
expect(run.err).toContain("prompt occurred")
471472
expect(promptFound).toBeFalsy()
472473
})
474+
475+
test("retry failed run", async () => {
476+
const t = {
477+
instructions: "say hello"
478+
}
479+
480+
let run = await client.evaluate(t as any)
481+
await run.text()
482+
483+
expect(run.err).toEqual("")
484+
485+
// Set the run to an error state, so we can retry it.
486+
run.state = RunState.Error
487+
run = run.nextChat()
488+
489+
await run.text()
490+
491+
expect(run.err).toEqual("")
492+
})
473493
})

0 commit comments

Comments
 (0)