|
| 1 | +import argparse |
| 2 | +import asyncio |
| 3 | + |
| 4 | +from temporalio.client import ( |
| 5 | + Client, |
| 6 | + WorkflowQueryRejectedError, |
| 7 | + WorkflowUpdateFailedError, |
| 8 | +) |
| 9 | +from temporalio.common import QueryRejectCondition |
| 10 | +from temporalio.contrib.openai_agents.open_ai_data_converter import ( |
| 11 | + open_ai_data_converter, |
| 12 | +) |
| 13 | +from temporalio.service import RPCError, RPCStatusCode |
| 14 | + |
| 15 | +from openai_agents.workflows.customer_service_workflow import ( |
| 16 | + CustomerServiceWorkflow, |
| 17 | + ProcessUserMessageInput, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +async def main(): |
| 22 | + parser = argparse.ArgumentParser() |
| 23 | + parser.add_argument("--conversation-id", type=str, required=True) |
| 24 | + args = parser.parse_args() |
| 25 | + |
| 26 | + # Create client connected to server at the given address |
| 27 | + client = await Client.connect( |
| 28 | + "localhost:7233", |
| 29 | + data_converter=open_ai_data_converter, |
| 30 | + ) |
| 31 | + |
| 32 | + handle = client.get_workflow_handle(args.conversation_id) |
| 33 | + |
| 34 | + # Query the workflow for the chat history |
| 35 | + # If the workflow is not open, start a new one |
| 36 | + start = False |
| 37 | + try: |
| 38 | + history = await handle.query( |
| 39 | + CustomerServiceWorkflow.get_chat_history, |
| 40 | + reject_condition=QueryRejectCondition.NOT_OPEN, |
| 41 | + ) |
| 42 | + except WorkflowQueryRejectedError as e: |
| 43 | + start = True |
| 44 | + except RPCError as e: |
| 45 | + if e.status == RPCStatusCode.NOT_FOUND: |
| 46 | + start = True |
| 47 | + else: |
| 48 | + raise e |
| 49 | + if start: |
| 50 | + await client.start_workflow( |
| 51 | + CustomerServiceWorkflow.run, |
| 52 | + id=args.conversation_id, |
| 53 | + task_queue="openai-agents-task-queue", |
| 54 | + ) |
| 55 | + history = [] |
| 56 | + print(*history, sep="\n") |
| 57 | + |
| 58 | + # Loop to send messages to the workflow |
| 59 | + while True: |
| 60 | + user_input = input("Enter your message: ") |
| 61 | + message_input = ProcessUserMessageInput( |
| 62 | + user_input=user_input, chat_length=len(history) |
| 63 | + ) |
| 64 | + try: |
| 65 | + new_history = await handle.execute_update( |
| 66 | + CustomerServiceWorkflow.process_user_message, message_input |
| 67 | + ) |
| 68 | + history.extend(new_history) |
| 69 | + print(*new_history, sep="\n") |
| 70 | + except WorkflowUpdateFailedError: |
| 71 | + print("** Stale conversation. Reloading...") |
| 72 | + length = len(history) |
| 73 | + history = await handle.query( |
| 74 | + CustomerServiceWorkflow.get_chat_history, |
| 75 | + reject_condition=QueryRejectCondition.NOT_OPEN, |
| 76 | + ) |
| 77 | + print(*history[length:], sep="\n") |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + asyncio.run(main()) |
0 commit comments