File size: 8,892 Bytes
cb3f557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# # example_usage.py
# import asyncio
# import traceback
# from agents import Runner, RunContextWrapper
# from agents.exceptions import InputGuardrailTripwireTriggered
# from openai.types.responses import ResponseTextDeltaEvent
# from chatbot.chatbot_agent import innscribe_assistant

# async def query_innscribe_bot(user_message: str, stream: bool = True):
#     """
#     Query the Innoscribe bot with optional streaming (ChatGPT-style chunk-by-chunk output).
    
#     Args:
#         user_message: The user's message/query
#         stream: If True, stream responses chunk by chunk like ChatGPT. If False, wait for complete response.
    
#     Returns:
#         The final output from the agent
#     """
#     try:
#         ctx = RunContextWrapper(context={})
        
#         if stream:
#             # ChatGPT-style streaming: clean output, text appears chunk by chunk
#             result = Runner.run_streamed(
#                 innscribe_assistant,
#                 input=user_message,
#                 context=ctx.context
#             )
            
#             # Stream text chunk by chunk in real-time (like ChatGPT)
#             async for event in result.stream_events():
#                 if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
#                     delta = event.data.delta
#                     if delta:
#                         # Print each chunk immediately as it arrives (ChatGPT-style)
#                         print(delta, end="", flush=True)
            
#             print("\n")  # New line after streaming completes
#             return result.final_output
#         else:
#             # Non-streaming mode: wait for complete response
#             response = await Runner.run(
#                 innscribe_assistant,
#                 input=user_message,
#                 context=ctx.context
#             )
#             return response.final_output
            
#     except InputGuardrailTripwireTriggered as e:
#         print(f"\n⚠️  Guardrail blocked the query: {e}")
#         if hasattr(e, 'result') and hasattr(e.result, 'output_info'):
#             print(f"Guardrail reason: {e.result.output_info}")
#         print("The query was determined to be unrelated to Innoscribe services.")
#         return None
#     except Exception as e:
#         print(f"\n❌ Error: {e}")
#         print(traceback.format_exc())
#         raise

# async def interactive_chat():
#     """
#     Interactive ChatGPT-style conversation loop.
#     Type 'exit', 'quit', or 'bye' to end the conversation.
#     """
#     print("=" * 60)
#     print("πŸ€– Innoscribe Assistant - ChatGPT-style Chat")
#     print("Type 'exit', 'quit', or 'bye' to end the conversation")
#     print("=" * 60)
#     print()
    
#     while True:
#         try:
#             user_message = input("πŸ‘€ You: ").strip()
            
#             # Check for exit commands
#             if user_message.lower() in ['exit', 'quit', 'bye', '']:
#                 print("\nπŸ‘‹ Goodbye! Have a great day!")
#                 break
            
#             # Display assistant prefix and stream response
#             print("πŸ€– Assistant: ", end="", flush=True)
            
#             # Stream response chunk by chunk (ChatGPT-style)
#             response = await query_innscribe_bot(user_message, stream=True)
            
#             print()  # Empty line between messages
            
#         except KeyboardInterrupt:
#             print("\n\nπŸ‘‹ Conversation interrupted. Goodbye!")
#             break
#         except Exception as e:
#             print(f"\n❌ Error: {e}")
#             print("Please try again or type 'exit' to quit.\n")

# async def main():
#     try:
#         # Option 1: Single message example (ChatGPT-style streaming)
#         user_message = "Hello, how can I help you?"
        
#         print(f"πŸ‘€ You: {user_message}\n")
#         print("πŸ€– Assistant: ", end="", flush=True)
        
#         # Stream response chunk by chunk (ChatGPT-style)
#         response = await query_innscribe_bot(user_message, stream=True)
        
#         # Option 2: Uncomment below to use interactive chat mode instead
#         # await interactive_chat()
        
#     except Exception as e:
#         print(f"\n❌ Error: {e}")
#         print(traceback.format_exc())

# if __name__ == "__main__":
#     try:
#         asyncio.run(main())
#     except Exception as e:
#         print(f"Fatal error: {e}")
#         print(traceback.format_exc())
# example_usage.py
import asyncio
import traceback
from agents import Runner, RunContextWrapper
from agents.exceptions import InputGuardrailTripwireTriggered
from openai.types.responses import ResponseTextDeltaEvent
from chatbot.chatbot_agent import jobobike_assistant

async def query_jobobike_bot(user_message: str, stream: bool = True):
    """
    Query the JOBObike bot with optional streaming (ChatGPT-style chunk-by-chunk output).
    
    Args:
        user_message: The user's message/query
        stream: If True, stream responses chunk by chunk like ChatGPT. If False, wait for complete response.
    
    Returns:
        The final output from the agent
    """
    try:
        ctx = RunContextWrapper(context={})
        
        if stream:
            # ChatGPT-style streaming: clean output, text appears chunk by chunk
            result = Runner.run_streamed(
                jobobike_assistant,
                input=user_message,
                context=ctx.context
            )
            
            # Stream text chunk by chunk in real-time (like ChatGPT)
            async for event in result.stream_events():
                if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
                    delta = event.data.delta
                    if delta:
                        # Print each chunk immediately as it arrives (ChatGPT-style)
                        print(delta, end="", flush=True)
            
            print("\n")  # New line after streaming completes
            return result.final_output
        else:
            # Non-streaming mode: wait for complete response
            response = await Runner.run(
                jobobike_assistant,
                input=user_message,
                context=ctx.context
            )
            return response.final_output
            
    except InputGuardrailTripwireTriggered as e:
        print(f"\n⚠️  Guardrail blocked the query: {e}")
        if hasattr(e, 'result') and hasattr(e.result, 'output_info'):
            print(f"Guardrail reason: {e.result.output_info}")
        print("The query was determined to be unrelated to JOBObike services.")
        return None
    except Exception as e:
        print(f"\n❌ Error: {e}")
        print(traceback.format_exc())
        raise

async def interactive_chat():
    """
    Interactive ChatGPT-style conversation loop.
    Type 'exit', 'quit', or 'bye' to end the conversation.
    """
    print("=" * 60)
    print("πŸ€– JOBObike Assistant - ChatGPT-style Chat")
    print("Type 'exit', 'quit', or 'bye' to end the conversation")
    print("=" * 60)
    print()
    
    while True:
        try:
            user_message = input("πŸ‘€ You: ").strip()
            
            # Check for exit commands
            if user_message.lower() in ['exit', 'quit', 'bye', '']:
                print("\nπŸ‘‹ Goodbye! Have a great day!")
                break
            
            # Display assistant prefix and stream response
            print("πŸ€– Assistant: ", end="", flush=True)
            
            # Stream response chunk by chunk (ChatGPT-style)
            response = await query_jobobike_bot(user_message, stream=True)
            
            print()  # Empty line between messages
            
        except KeyboardInterrupt:
            print("\n\nπŸ‘‹ Conversation interrupted. Goodbye!")
            break
        except Exception as e:
            print(f"\n❌ Error: {e}")
            print("Please try again or type 'exit' to quit.\n")

async def main():
    try:
        # Option 1: Single message example (ChatGPT-style streaming)
        user_message = "Hello, tell me about your services."
        
        print(f"πŸ‘€ You: {user_message}\n")
        print("πŸ€– Assistant: ", end="", flush=True)
        
        # Stream response chunk by chunk (ChatGPT-style)
        response = await query_jobobike_bot(user_message, stream=True)
        
        # Option 2: Uncomment below to use interactive chat mode instead
        # await interactive_chat()
        
    except Exception as e:
        print(f"\n❌ Error: {e}")
        print(traceback.format_exc())

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(f"Fatal error: {e}")
        print(traceback.format_exc())