Skip to content

Commit

Permalink
threading, readline fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
frdel committed Sep 4, 2024
1 parent e000433 commit a4937de
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
10 changes: 7 additions & 3 deletions python/helpers/defer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@
class DeferredTask:
def __init__(self, func, *args, **kwargs):
self._loop = asyncio.new_event_loop()
# self._thread = None
self._task = None
self._future = Future()
self._task_initialized = threading.Event() # Event to signal task initialization
self._start_task(func, *args, **kwargs)

def _start_task(self, func, *args, **kwargs):
def run_in_thread(loop, func, args, kwargs):
asyncio.set_event_loop(loop)
self._task = loop.create_task(self._run(func, *args, **kwargs))
self._task_initialized.set() # Signal that the task has been initialized
loop.run_forever()

self._thread = threading.Thread(target=run_in_thread, args=(self._loop, func, args, kwargs))
Expand All @@ -32,15 +33,18 @@ def is_ready(self):
return self._future.done()

async def result(self, timeout=None):
if self._task is None:
if not self._task_initialized.wait(timeout): # Wait until the task is initialized
raise RuntimeError("Task was not initialized properly.")

try:
return await asyncio.wait_for(asyncio.wrap_future(self._future), timeout)
except asyncio.TimeoutError:
raise TimeoutError("The task did not complete within the specified timeout.")

def result_sync(self, timeout=None):
if not self._task_initialized.wait(timeout): # Wait until the task is initialized
raise RuntimeError("Task was not initialized properly.")

try:
return self._future.result(timeout)
except TimeoutError:
Expand Down
3 changes: 2 additions & 1 deletion python/helpers/timed_input.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import sys
from inputimeout import inputimeout, TimeoutOccurred

def timeout_input(prompt, timeout=10):
try:
import readline
if sys.platform != "win32": import readline
user_input = inputimeout(prompt=prompt, timeout=timeout)
return user_input
except TimeoutOccurred:
Expand Down
7 changes: 4 additions & 3 deletions run_cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import sys
import threading, time, models, os
from ansio import application_keypad, mouse_input, raw_input
from ansio.input import InputEvent, get_input_event
Expand All @@ -24,13 +25,13 @@ async def chat(context: AgentContext):
timeout = context.agent0.get_data("timeout") # how long the agent is willing to wait
if not timeout: # if agent wants to wait for user input forever
PrintStyle(background_color="#6C3483", font_color="white", bold=True, padding=True).print(f"User message ('e' to leave):")
import readline # this fixes arrow keys in terminal
if sys.platform != "win32": import readline # this fixes arrow keys in terminal
user_input = input("> ")
PrintStyle(font_color="white", padding=False, log_only=True).print(f"> {user_input}")

else: # otherwise wait for user input with a timeout
PrintStyle(background_color="#6C3483", font_color="white", bold=True, padding=True).print(f"User message ({timeout}s timeout, 'w' to wait, 'e' to leave):")
import readline # this fixes arrow keys in terminal
if sys.platform != "win32": import readline # this fixes arrow keys in terminal
# user_input = timed_input("> ", timeout=timeout)
user_input = timeout_input("> ", timeout=timeout)

Expand Down Expand Up @@ -62,7 +63,7 @@ def intervention():
context.paused = True # stop agent streaming
PrintStyle(background_color="#6C3483", font_color="white", bold=True, padding=True).print(f"User intervention ('e' to leave, empty to continue):")

import readline # this fixes arrow keys in terminal
if sys.platform != "win32": import readline # this fixes arrow keys in terminal
user_input = input("> ").strip()
PrintStyle(font_color="white", padding=False, log_only=True).print(f"> {user_input}")

Expand Down

0 comments on commit a4937de

Please sign in to comment.