Skip to content

fix: await event_handlers to ensure errors are processed #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion gptscript/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def __init__(self, subCommand: str, tools: Union[ToolDef | list[ToolDef] | str],
self._rawOutput: Any = None
self._task: Awaitable | None = None
self._resp: httpx.Response | None = None
self._event_tasks: list[Awaitable[None]] = []

def program(self):
return self._program
Expand Down Expand Up @@ -157,7 +158,7 @@ async def _request(self, tool: Any):
self._parentCallID = event.id
if self.event_handlers is not None:
for event_handler in self.event_handlers:
asyncio.create_task(event_handler(self, event))
self._event_tasks.append(asyncio.create_task(event_handler(self, event)))

self._resp = None
if self._err != "":
Expand All @@ -167,6 +168,14 @@ async def _request(self, tool: Any):
else:
self._state = RunState.Continue

for task in self._event_tasks:
try:
await task
except Exception as e:
print(f"error during event processing: {e}")

self._event_tasks = []

async def aclose(self):
if self._task is None or self._resp is None:
raise Exception("run not started")
Expand Down
5 changes: 3 additions & 2 deletions tests/test_gptscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def gptscript():
pytest.fail("OPENAI_API_KEY not set", pytrace=False)
try:
gptscript = GPTScript(GlobalOptions(apiKey=os.getenv("OPENAI_API_KEY")))
return gptscript
yield gptscript
gptscript.close()
except Exception as e:
pytest.fail(e, pytrace=False)

Expand Down Expand Up @@ -387,7 +388,7 @@ async def process_event(r: Run, frame: CallFrame | RunFrame | PromptFrame):
nonlocal confirm_event_found, event_content
if frame.type == RunEventType.callConfirm:
confirm_event_found = True
assert '"ls"' in frame.input or '"dir"' in frame.input, "Unexpected confirm input: " + frame.input
assert '"ls' in frame.input or '"dir' in frame.input, "Unexpected confirm input: " + frame.input
await gptscript.confirm(AuthResponse(frame.id, True))
elif frame.type == RunEventType.callProgress:
for output in frame.output:
Expand Down