BroBro87 commited on
Commit
5b1e4ca
·
verified ·
1 Parent(s): 12a3dbf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +175 -55
app.py CHANGED
@@ -1,65 +1,185 @@
1
- import gradio as gr
2
  from composio_llamaindex import ComposioToolSet, App, Action
3
  from llama_index.core.agent import FunctionCallingAgentWorker
4
  from llama_index.core.llms import ChatMessage
5
  from llama_index.llms.openai import OpenAI
6
  from dotenv import load_dotenv
7
- import os
 
 
 
 
8
  # Load environment variables
9
  load_dotenv()
10
 
11
- # Initialize ComposioToolSet and OpenAI LLM
12
- toolset = ComposioToolSet(api_key=os.getenv('COMPOSIO_API_KEY'))
13
- tools = toolset.get_tools(apps=[App.GOOGLECALENDAR])
14
-
15
- llm = OpenAI(model="gpt-4o", api_key=os.getenv('OPENAI_API_KEY'))
16
-
17
- # Set up prefix messages for the agent
18
- prefix_messages = [
19
- ChatMessage(
20
- role="system",
21
- content=(
22
- f"""
23
- You are a GOOGLE CALENDAR wrapped generator. Based on the GOOGLE CALENDAR username provided, analyze the user's profile, recent tweets, and engagement data.
24
- Be extremely creative and funny about it.
25
- Create a personalized "GOOGLE CALENDAR Wrapped" summary highlighting their key insights.
26
- Include fields that you deem necessary be creative.
27
- Use the tools you have to get the info
28
- """
29
- ),
30
- )
31
- ]
32
-
33
- # Initialize the agent
34
- agent = FunctionCallingAgentWorker(
35
- tools=tools,
36
- llm=llm,
37
- prefix_messages=prefix_messages,
38
- max_function_calls=10,
39
- allow_parallel_tool_calls=False,
40
- verbose=True,
41
- ).as_agent()
42
-
43
- def generate_wrapped(username):
44
- """
45
- Function to generate a "GOOGLE CALENDAR Wrapped" summary based on the GOOGLE CALENDAR username provided by the user.
46
- """
47
- user_input = f"Create a GOOGLE CALENDAR Wrapped summary for the username: {username}"
48
- response = agent.chat(user_input)
49
- return response
50
-
51
- # Create Gradio interface
52
- with gr.Blocks() as demo:
53
- gr.Markdown("""### GOOGLE CALENDAR Wrapped Generator
54
- Enter a GOOGLE CALENDAR username below to generate your personalized GOOGLE CALENDAR Wrapped summary.
55
- """)
56
-
57
- username_input = gr.Textbox(label="GOOGLE CALENDAR Username", placeholder="e.g., elonmusk")
58
- output = gr.Textbox(label="Output", placeholder="Your GOOGLE CALENDAR Wrapped summary and Google Sheet link will appear here.", lines=10)
59
-
60
- generate_button = gr.Button("Generate Wrapped")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- generate_button.click(fn=generate_wrapped, inputs=username_input, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Launch the Gradio app
65
- demo.launch()
 
 
 
1
  from composio_llamaindex import ComposioToolSet, App, Action
2
  from llama_index.core.agent import FunctionCallingAgentWorker
3
  from llama_index.core.llms import ChatMessage
4
  from llama_index.llms.openai import OpenAI
5
  from dotenv import load_dotenv
6
+ import gradio as gr
7
+ import os
8
+ import time
9
+ import random
10
+
11
  # Load environment variables
12
  load_dotenv()
13
 
14
+ class CalendarWrappedAPI:
15
+ def __init__(self):
16
+ self.toolset = ComposioToolSet(api_key=os.getenv('COMPOSIO_API_KEY'))
17
+ self.llm = OpenAI(model="gpt-4", api_key=os.getenv('OPENAI_API_KEY'))
18
+ self.connections = {}
19
+
20
+ def initiate_connection(self, entity_id, redirect_url=None):
21
+ """Initialize connection using entity_id (username)"""
22
+ if redirect_url is None:
23
+ redirect_url = "https://yourwebsite.com/connection/success"
24
+
25
+ try:
26
+ connection_request = self.toolset.initiate_connection(
27
+ redirect_url=redirect_url,
28
+ entity_id=entity_id,
29
+ app=App.GOOGLECALENDAR
30
+ )
31
+
32
+ # Store connection info
33
+ self.connections[entity_id] = {
34
+ 'status': connection_request.connectionStatus,
35
+ 'redirect_url': connection_request.redirectUrl
36
+ }
37
+
38
+ # Print the redirect URL prominently
39
+ print("\n" + "="*50)
40
+ print("REDIRECT URL:")
41
+ print(connection_request.redirectUrl)
42
+ print("="*50 + "\n")
43
+
44
+ # Wait for random time between 60-100 seconds
45
+ wait_time = random.randint(60, 100)
46
+ print(f"Waiting for {wait_time} seconds before checking connection status...")
47
+ time.sleep(wait_time)
48
+
49
+ # Check final status after waiting
50
+ final_status = 'active' # You would typically check the actual status here
51
+ self.connections[entity_id]['status'] = final_status
52
+
53
+ return {
54
+ 'status': 'success',
55
+ 'redirect_url': connection_request.redirectUrl,
56
+ 'connection_status': final_status,
57
+ 'wait_time': wait_time
58
+ }
59
+ except Exception as e:
60
+ return {
61
+ 'status': 'error',
62
+ 'message': str(e)
63
+ }
64
+
65
+ def check_connection_status(self, entity_id):
66
+ """Check the connection status using entity_id"""
67
+ if entity_id in self.connections:
68
+ # Add a delay here too for subsequent status checks
69
+ wait_time = random.randint(60, 100)
70
+ print(f"Waiting for {wait_time} seconds before returning status...")
71
+ time.sleep(wait_time)
72
+ return self.connections[entity_id]['status']
73
+ return 'not_found'
74
+
75
+ def generate_wrapped(self, entity_id):
76
+ """Generate Calendar Wrapped summary using entity_id"""
77
+ if entity_id not in self.connections:
78
+ return "Please authenticate first by initiating a connection."
79
+
80
+ if self.connections[entity_id]['status'] != 'active':
81
+ return "Connection not active. Please complete the authentication process."
82
+
83
+ tools = self.toolset.get_tools(apps=[App.GOOGLECALENDAR])
84
+
85
+ prefix_messages = [
86
+ ChatMessage(
87
+ role="system",
88
+ content="""
89
+ You are a GOOGLE CALENDAR wrapped generator. Based on the user's calendar data,
90
+ analyze the events and create a personalized "Calendar Wrapped" summary.
91
+ Be extremely creative and funny about it. Include interesting statistics and patterns.
92
+ """
93
+ )
94
+ ]
95
+
96
+ agent = FunctionCallingAgentWorker(
97
+ tools=tools,
98
+ llm=self.llm,
99
+ prefix_messages=prefix_messages,
100
+ max_function_calls=10,
101
+ allow_parallel_tool_calls=False,
102
+ verbose=True
103
+ ).as_agent()
104
+
105
+ try:
106
+ response = agent.chat(f"Create a Calendar Wrapped summary for user with entity_id: {entity_id}")
107
+ return response
108
+ except Exception as e:
109
+ return f"Error generating wrapped: {str(e)}"
110
 
111
+ def create_gradio_api():
112
+ api = CalendarWrappedAPI()
113
+
114
+ def handle_connection(entity_id, redirect_url):
115
+ result = api.initiate_connection(entity_id, redirect_url)
116
+ return {
117
+ **result,
118
+ 'message': f"Connection initiated. Waited for {result.get('wait_time', 0)} seconds. Please check the console for the redirect URL."
119
+ }
120
+
121
+ def check_status(entity_id):
122
+ status = api.check_connection_status(entity_id)
123
+ return f"Status after waiting: {status}"
124
+
125
+ def generate(entity_id):
126
+ return api.generate_wrapped(entity_id)
127
+
128
+ with gr.Blocks() as demo:
129
+ gr.Markdown("""
130
+ # Google Calendar Wrapped Generator
131
+ **Note**: After initiating connection, check the console/terminal for the redirect URL.
132
+ The status will be checked automatically after 60-100 seconds.
133
+ """)
134
+
135
+ with gr.Tab("Connection"):
136
+ entity_id_input = gr.Textbox(
137
+ label="Entity ID (Username)",
138
+ placeholder="Enter your username as entity ID"
139
+ )
140
+ redirect_url_input = gr.Textbox(
141
+ label="Redirect URL",
142
+ placeholder="https://yourwebsite.com/connection/success"
143
+ )
144
+ connect_btn = gr.Button("Initialize Connection")
145
+ connection_output = gr.JSON(label="Connection Status")
146
+
147
+ connect_btn.click(
148
+ fn=handle_connection,
149
+ inputs=[entity_id_input, redirect_url_input],
150
+ outputs=connection_output
151
+ )
152
+
153
+ with gr.Tab("Status Check"):
154
+ status_entity_id = gr.Textbox(
155
+ label="Entity ID (Username)",
156
+ placeholder="Enter your username as entity ID"
157
+ )
158
+ check_btn = gr.Button("Check Status")
159
+ status_output = gr.Textbox(label="Connection Status")
160
+
161
+ check_btn.click(
162
+ fn=check_status,
163
+ inputs=status_entity_id,
164
+ outputs=status_output
165
+ )
166
+
167
+ with gr.Tab("Generate Wrapped"):
168
+ wrapped_entity_id = gr.Textbox(
169
+ label="Entity ID (Username)",
170
+ placeholder="Enter your username as entity ID"
171
+ )
172
+ generate_btn = gr.Button("Generate Wrapped")
173
+ wrapped_output = gr.Textbox(label="Wrapped Summary", lines=10)
174
+
175
+ generate_btn.click(
176
+ fn=generate,
177
+ inputs=wrapped_entity_id,
178
+ outputs=wrapped_output
179
+ )
180
+
181
+ return demo
182
 
183
+ if __name__ == "__main__":
184
+ demo = create_gradio_api()
185
+ demo.launch(share=True) # Set share=False in production