Skip to content
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ async def main():
agent = Agent(client, agent_id=agent_id, tts_model='neu_hq')

await agent.start()
# await agent.stop() # use this to stop the agent

asyncio.run(main())
```
Expand Down
58 changes: 40 additions & 18 deletions pyneuphonic/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def __init__(
)

self.on_message_hook = on_message
self._tasks = []

async def on_message(self, message: APIResponse[AgentResponse]):
"""
Expand All @@ -83,30 +84,36 @@ async def start(self):
self.ws.on(WebsocketEvents.MESSAGE, self.on_message)
self.ws.on(WebsocketEvents.CLOSE, self.on_close)

if not self.mute:
await self.player.open()
await self.ws.open(self.config)
async def run_agent():
if not self.mute:
await self.player.open()
await self.ws.open(self.config)

if 'asr' in self.config.mode:
await self.recorder.record()
if 'asr' in self.config.mode:
await self.recorder.record()

try:
try:
while True:
await asyncio.sleep(0.01)
except KeyboardInterrupt:
await self.close()

else:
while True:
await asyncio.sleep(0.01)
except KeyboardInterrupt:
await self.ws.close()
user_text = await aioconsole.ainput(
"\nEnter text to speak (or 'quit' to exit): "
)

if user_text.lower() == 'quit':
break

else:
while True:
user_text = await aioconsole.ainput(
"\nEnter text to speak (or 'quit' to exit): "
)
await self.ws.send({'text': user_text})
await asyncio.sleep(1) # simply for formatting

if user_text.lower() == 'quit':
break
await self.close()

await self.ws.send({'text': user_text})
await asyncio.sleep(1) # simply for formatting
run_task = asyncio.create_task(run_agent())
self._tasks.append(run_task)

async def on_close(self):
"""
Expand All @@ -116,3 +123,18 @@ async def on_close(self):
await self.player.close()
if 'asr' in self.config.mode:
await self.recorder.close()

async def stop(self):
"""
Close the agent, including websocket and any active resources.
"""
for task in self._tasks:
task.cancel()

try:
await task
except asyncio.CancelledError:
pass

await self.ws.close()
await self.on_close()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# POETRY CONFIG
[tool.poetry]
name = "pyneuphonic"
version = "1.5.7"
version = "1.5.8"
description = "A python SDK for the Neuphonic TTS Engine."
authors = ["Neuphonic <support@neuphonic.com>"]
readme = "README.md"
Expand Down
Loading