|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from poet_chat.agent import poet_runner |
| 4 | +from poet_chat.config import ( |
| 5 | + AGENT_OPTIONS, |
| 6 | + fishjam_client, |
| 7 | +) |
| 8 | +from poet_chat.notifier import make_notifier |
| 9 | + |
| 10 | +from fishjam.agent import OutgoingAudioTrackOptions |
| 11 | + |
| 12 | + |
| 13 | +async def main(): |
| 14 | + room = fishjam_client.create_room() |
| 15 | + _, token = fishjam_client.create_peer(room.id) |
| 16 | + print(f"Join the chat with the following token: {token}") |
| 17 | + |
| 18 | + agent = fishjam_client.create_agent(room.id, AGENT_OPTIONS) |
| 19 | + async with ( |
| 20 | + agent.connect() as fishjam_session, |
| 21 | + await poet_runner.run() as openai_session, |
| 22 | + ): |
| 23 | + track = await fishjam_session.add_track( |
| 24 | + OutgoingAudioTrackOptions( |
| 25 | + sample_rate=24000, metadata={"type": "microphone"} |
| 26 | + ) |
| 27 | + ) |
| 28 | + |
| 29 | + async def _openai_recv(): |
| 30 | + msg = "" |
| 31 | + async for event in openai_session: |
| 32 | + if event.type == "audio": |
| 33 | + audio = event.audio.data |
| 34 | + await track.send_chunk(audio) |
| 35 | + elif event.type == "audio_interrupted": |
| 36 | + await track.interrupt() |
| 37 | + elif event.type == "raw_model_event": |
| 38 | + if event.data.type == "input_audio_transcription_completed": |
| 39 | + print(f"Peer said:\n{event.data.transcript}\n") |
| 40 | + elif event.data.type == "transcript_delta": |
| 41 | + msg += event.data.delta |
| 42 | + elif event.data.type == "turn_ended": |
| 43 | + print(f"Agent said:\n{msg}\n") |
| 44 | + msg = "" |
| 45 | + elif event.data.type == "exception": |
| 46 | + raise event.data.exception |
| 47 | + elif event.data.type == "raw_server_event": |
| 48 | + match event.data.data: |
| 49 | + case {"response": {"status": "failed"}}: |
| 50 | + print(event.data.data) |
| 51 | + raise RuntimeError("Raw server error from OpenAI API!") |
| 52 | + |
| 53 | + async def _fishjam_recv(): |
| 54 | + async for event in fishjam_session.receive(): |
| 55 | + await openai_session.send_audio(event.data) |
| 56 | + |
| 57 | + async with asyncio.TaskGroup() as tg: |
| 58 | + tg.create_task(make_notifier(openai_session).connect()) |
| 59 | + tg.create_task(_openai_recv()) |
| 60 | + tg.create_task(_fishjam_recv()) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + asyncio.run(main()) |
0 commit comments