grimzaeye commited on
Commit
c94f08d
·
verified ·
1 Parent(s): 009cca8

add app.py, requirements.txt, credentials.json

Browse files
Files changed (3) hide show
  1. app.py +654 -0
  2. credentials.json +1 -0
  3. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 종속성 라이브러리 설치
3
+ #!pip install -q --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib pytz openai gradio
4
+
5
+
6
+ from datetime import datetime
7
+ import time
8
+ import os
9
+ import os.path
10
+ import json
11
+ from openai import OpenAI
12
+
13
+
14
+ '''OpenAI Assistant 생성 및 실행 부분 수정'''
15
+
16
+ #모델 이름, agent 이름, client 설정
17
+ model_name ="gpt-4o"
18
+ agent_name = "schedule_agent_0612"
19
+
20
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
21
+ global client
22
+
23
+ #client 생성
24
+ client= OpenAI(
25
+ api_key = OPENAI_API_KEY
26
+ )
27
+
28
+
29
+ # agent instructions, tools 정의
30
+ def get_agent_instructions(character):
31
+ strict_character_prompt = """
32
+ ### Personality: Strict Character
33
+ You are a strict, pushing, realistic tight assistant '마음이' to me. You talk to me as a tough friend do. 너는 직설적이고, 현실적이며, 엄격한 스타일이어서 내가 일정을 잘 수행할 수 있게 만들어줘야 해. 만약 내가 중요한 일을 하고 싶지 않다고 하면, 꼭 해야하는 이유를 알려주고, 하라고 시켜.
34
+ """
35
+ friendly_character_prompt = """
36
+ ### Personality: Friendly Character
37
+ You are a humourous friendly assistant '마음이' to me. You talk to me as a friend do. 너는 다정하고 상냥한, 공감하는, 격려하는 스타일이어서 만약 내가 힘들거나 하기 싫다고 하는 일이 있으면, 업무나 일에 관한 게 아니면 내 기분에 맞춰서 일정을 조정해줘. 답변은 한글로 해줘.
38
+ """
39
+
40
+ if character == "strict_charactor":
41
+ character_prompt = strict_character_prompt
42
+ else:
43
+ character_prompt = friendly_character_prompt
44
+
45
+
46
+ agent_instructions = f'''
47
+ {character_prompt}
48
+ For a given day, check my Calendar and output the agenda for the day in talking just time and agenda. Don't include Zoom or Google Meet links when telling me what's on my schedule. If I ask for more information about a location and detail, please tell me more. If I ask for more Agenda or schedules, browse the web to return relevant details such as locations or recommended things to do. 답변은 한글로 해줘.
49
+
50
+ Example Agenda:
51
+ Here's your schedule for Tues. Nov. 7th: 오후 4시에 강남에서 회의가 있고, 오후 6시에는 이태원에서 저녁 약속이 있어. 저녁 10시에는 산책을 할 예정이야.
52
+
53
+
54
+ ### Rules:
55
+
56
+ - Inform the user that they need to reply after the action completes to continue before running any actions.
57
+ - If a required function is not available, inform the user and guide them on how to add the necessary function.
58
+ - 일정을 생성하거나 삭제할 때는, 꼭 다시 생성하거나 삭제해도 되는지 나에게 먼저 물어봐.
59
+ - 일정을 생성해야 할 때 캘린더에서 시간이 겹치는 일정이 있는지 확인하고, 없다면 생성해줘. 만약 겹치는 일정이 있다면 나에게 알려주고, 어떤 일정을 생성할지 물어봐줘.
60
+
61
+ ### Instructions for Action:
62
+
63
+ Step 1. Inform the user that you are checking if the necessary AI actions (functions) are available to complete their request. Then proceed to step 2.
64
+ Step 2. List the available functions that can handle the user's request. Then proceed to step 3.
65
+ Step 3. Check if the required function is available. If it is, proceed to step 4. If not, inform the user that the required function is not available and provide a configuration link if necessary.
66
+ Step 4. Process the user's request and inform them once the action is completed.
67
+
68
+ ### Required Functions:
69
+
70
+ - **Action:** Google Calendar Create Event
71
+ - **Function:** `create_event`
72
+ - **Description:** "Creates a new calendar event."
73
+ - **Action:** Google Calendar Get Event
74
+ - **Function:** `get_event`
75
+ - **Description:** "Retrieves details of a specific event by its ID."
76
+ - **Action:** Google Calendar Update Event
77
+ - **Function:** `update_event`
78
+ - **Description:** "Updates an existing event by its ID."
79
+ - **Action:** Google Calendar Delete Event
80
+ - **Function:** `delete_event`
81
+ - **Description:** "Deletes an event by its ID."
82
+ - **Action:** Google Calendar Get Conflicts
83
+ - **Function:** `get_conflicts`
84
+ - **Description:** "Checks for conflicts within a specified time range."
85
+ - **Action:** Google Calendar Get Events
86
+ - **Function:** `get_events`
87
+ - **Description:** "Retrieves events within a specified time range."
88
+ - **Action:** Google Calendar Add Calendar Owner
89
+ - **Function:** `add_calendar_owner`
90
+ - **Description:** "Adds a new owner to the calendar."
91
+ - **Action:** Get Current DateTime and Timezone
92
+ - **Function:** `get_current_datetime_and_timezone`
93
+ - **Description:** "Retrieves the current date, time, and timezone."
94
+ '''
95
+
96
+ return agent_instructions
97
+
98
+
99
+ # agent_tools 정의
100
+ def get_agent_tools():
101
+ agent_tools = [
102
+ {"type": "code_interpreter"},
103
+ {
104
+ "type": "function",
105
+ "function": {
106
+ "name": "create_event",
107
+ "description": "Create a new calendar event",
108
+ "parameters": {
109
+ "type": "object",
110
+ "properties": {
111
+ "event": {
112
+ "type": "object",
113
+ "description": "The event details including summary, location, description, start, and end times",
114
+ "properties": {
115
+ "summary": {"type": "string"},
116
+ "location": {"type": "string"},
117
+ "description": {"type": "string"},
118
+ "start": {
119
+ "type": "object",
120
+ "properties": {
121
+ "dateTime": {"type": "string"},
122
+ "timeZone": {"type": "string"}
123
+ },
124
+ "required": ["dateTime", "timeZone"]
125
+ },
126
+ "end": {
127
+ "type": "object",
128
+ "properties": {
129
+ "dateTime": {"type": "string"},
130
+ "timeZone": {"type": "string"}
131
+ },
132
+ "required": ["dateTime", "timeZone"]
133
+ }
134
+ },
135
+ "required": ["summary", "start", "end"]
136
+ }
137
+ },
138
+ "required": ["event"]
139
+ }
140
+ }
141
+ },
142
+ {
143
+ "type": "function",
144
+ "function": {
145
+ "name": "get_event",
146
+ "description": "Retrieve details of a specific event by its ID",
147
+ "parameters": {
148
+ "type": "object",
149
+ "properties": {
150
+ "event_id": {"type": "string", "description": "The ID of the event to retrieve"}
151
+ },
152
+ "required": ["event_id"]
153
+ }
154
+ }
155
+ },
156
+ {
157
+ "type": "function",
158
+ "function": {
159
+ "name": "update_event",
160
+ "description": "Update an existing event by its ID",
161
+ "parameters": {
162
+ "type": "object",
163
+ "properties": {
164
+ "event_id": {"type": "string", "description": "The ID of the event to update"},
165
+ "updated_event": {
166
+ "type": "object",
167
+ "description": "The updated event details",
168
+ "properties": {
169
+ "summary": {"type": "string"},
170
+ "location": {"type": "string"},
171
+ "description": {"type": "string"},
172
+ "start": {
173
+ "type": "object",
174
+ "properties": {
175
+ "dateTime": {"type": "string"},
176
+ "timeZone": {"type": "string"}
177
+ },
178
+ "required": ["dateTime", "timeZone"]
179
+ },
180
+ "end": {
181
+ "type": "object",
182
+ "properties": {
183
+ "dateTime": {"type": "string"},
184
+ "timeZone": {"type": "string"}
185
+ },
186
+ "required": ["dateTime", "timeZone"]
187
+ }
188
+ },
189
+ "required": ["summary", "start", "end"]
190
+ }
191
+ },
192
+ "required": ["event_id", "updated_event"]
193
+ }
194
+ }
195
+ },
196
+ {
197
+ "type": "function",
198
+ "function": {
199
+ "name": "delete_event",
200
+ "description": "Delete an event by its ID",
201
+ "parameters": {
202
+ "type": "object",
203
+ "properties": {
204
+ "event_id": {"type": "string", "description": "The ID of the event to delete"}
205
+ },
206
+ "required": ["event_id"]
207
+ }
208
+ }
209
+ },
210
+ {
211
+ "type": "function",
212
+ "function": {
213
+ "name": "get_conflicts",
214
+ "description": "Get events within a specified time range to check for conflicts",
215
+ "parameters": {
216
+ "type": "object",
217
+ "properties": {
218
+ "start_time": {"type": "string", "description": "The start time to check for conflicts"},
219
+ "end_time": {"type": "string", "description": "The end time to check for conflicts"}
220
+ },
221
+ "required": ["start_time", "end_time"]
222
+ }
223
+ }
224
+ },
225
+ {
226
+ "type": "function",
227
+ "function": {
228
+ "name": "get_events",
229
+ "description": "Get events within a specified time range",
230
+ "parameters": {
231
+ "type": "object",
232
+ "properties": {
233
+ "start_time": {"type": "string", "description": "The start time to get events from"},
234
+ "end_time": {"type": "string", "description": "The end time to get events to"}
235
+ },
236
+ "required": ["start_time", "end_time"]
237
+ }
238
+ }
239
+ },
240
+ {
241
+ "type": "function",
242
+ "function": {
243
+ "name": "add_calendar_owner",
244
+ "description": "Add a new owner to the calendar",
245
+ "parameters": {
246
+ "type": "object",
247
+ "properties": {
248
+ "user_email": {"type": "string", "description": "The email of the user to add as owner"}
249
+ },
250
+ "required": ["user_email"]
251
+ }
252
+ }
253
+ },
254
+ {
255
+ "type": "function",
256
+ "function": {
257
+ "name": "get_current_datetime_and_timezone",
258
+ "description": "Get the current date, time, and timezone",
259
+ "parameters": {
260
+ "type": "object",
261
+ "properties": {}
262
+ }
263
+ }
264
+ }
265
+ ]
266
+ return agent_tools
267
+
268
+
269
+
270
+ # 기존 Assistant 가져오거나 수정하거나 생성하기
271
+ def create_or_update_assistant(client, agent_name, model_name, character):
272
+ if character == "strict_charactor":
273
+ agent_name = "schedule_agent_strict"
274
+ else:
275
+ agent_name = "schedule_agent_friendly"
276
+
277
+ # 모든 Assistants 가져오기
278
+ assistants = client.beta.assistants.list()
279
+
280
+ # "Scheduler Agent"가 있는지 확인
281
+ scheduler_agent = None
282
+ for assistant in assistants:
283
+ if assistant.name == agent_name:
284
+ scheduler_agent = assistant
285
+ break
286
+
287
+ # "Scheduler Agent"가 없으면 생성
288
+ if scheduler_agent is None:
289
+ scheduler_agent = client.beta.assistants.create(
290
+ name= agent_name,
291
+ instructions=get_agent_instructions(character),
292
+ model=model_name,
293
+ tools=get_agent_tools(),
294
+ )
295
+ print("Create new agent : ", scheduler_agent.id)
296
+ else:
297
+ # "Scheduler Agent"가 있으면 업데이트
298
+ scheduler_agent = client.beta.assistants.update(
299
+ assistant_id=scheduler_agent.id,
300
+ instructions=get_agent_instructions(character),
301
+ model=model_name,
302
+ tools=get_agent_tools(),
303
+ )
304
+ print("Update existing agent : ", scheduler_agent.id),
305
+
306
+ assistant = scheduler_agent
307
+ return assistant
308
+
309
+
310
+
311
+
312
+ # assistant ai run 상태 확인
313
+ def check_run_status(client, thread_id, run_id, calendar_service):
314
+ while True:
315
+ run = client.beta.threads.runs.retrieve(
316
+ thread_id=thread_id,
317
+ run_id=run_id
318
+ )
319
+
320
+ if run.status in ['completed', 'failed', 'cancelled', 'expired']:
321
+ return run.status
322
+ elif run.status == 'requires_action':
323
+
324
+ tool_outputs = []
325
+ for tool_call in run.required_action.submit_tool_outputs.tool_calls:
326
+ tool_id = tool_call.id
327
+ function_name = tool_call.function.name
328
+ arguments = json.loads(tool_call.function.arguments)
329
+
330
+ try:
331
+ output = execute_function(calendar_service, function_name, arguments)
332
+ tool_outputs.append({
333
+ "tool_call_id": tool_id,
334
+ "output": json.dumps(output)
335
+ })
336
+ #툴이 반영되는지 확인
337
+ # print("tool_outputs : ", tool_outputs)
338
+ except Exception as e:
339
+ print(f"Error executing tool {function_name}: {e}")
340
+
341
+ client.beta.threads.runs.submit_tool_outputs(
342
+ thread_id=thread_id,
343
+ run_id=run_id,
344
+ tool_outputs=tool_outputs,
345
+
346
+ )
347
+
348
+ #일정시간 대기
349
+ time.sleep(0.1)
350
+
351
+
352
+ def start_chat_friendly(user_input, chat_history):
353
+
354
+ if user_input == "":
355
+ return "", chat_history
356
+ else:
357
+ # # 종료조건 설정
358
+ if user_input.lower() == 'quit':
359
+ print("Assistant deactivated.")
360
+ return chat_history
361
+
362
+ # 메시지 생성
363
+ message = client.beta.threads.messages.create(
364
+ thread_id=thread.id,
365
+ role="user",
366
+ content=user_input
367
+ )
368
+ # Assistant 실행
369
+ run = client.beta.threads.runs.create(
370
+ thread_id=thread.id,
371
+ assistant_id=assistant_friendly_id,
372
+ )
373
+
374
+ # Assistant 실행 상태 확인
375
+ check_run_status(client, thread.id, run.id, calendar_service)
376
+
377
+ thread_messages = client.beta.threads.messages.list(thread.id, order="desc", limit=1)
378
+
379
+ # chat_history에 대화 내용 저장
380
+ chat_history.append([None, user_input])
381
+ if thread_messages.data:
382
+ latest_message = thread_messages.data[0]
383
+ if latest_message.role == "assistant":
384
+ print(f"Assistant: {latest_message.content[0].text.value}")
385
+ response = latest_message.content[0].text.value
386
+ chat_history.append([response, None])
387
+ return "", chat_history
388
+
389
+ def start_chat_strict(user_input, chat_history):
390
+
391
+ if user_input == "":
392
+ return "", chat_history
393
+ else:
394
+ # # 종료조건 설정
395
+ if user_input.lower() == 'quit':
396
+ print("Assistant deactivated.")
397
+ return chat_history
398
+
399
+ # 메시지 생성
400
+ message = client.beta.threads.messages.create(
401
+ thread_id=thread.id,
402
+ role="user",
403
+ content=user_input
404
+ )
405
+ # Assistant 실행
406
+ run = client.beta.threads.runs.create(
407
+ thread_id=thread.id,
408
+ assistant_id=assistant_strict_id,
409
+ )
410
+
411
+ # Assistant 실행 상태 확인
412
+ check_run_status(client, thread.id, run.id, calendar_service)
413
+
414
+ thread_messages = client.beta.threads.messages.list(thread.id, order="desc", limit=1)
415
+
416
+ # chat_history에 대화 내용 저장
417
+ chat_history.append([None, user_input])
418
+ if thread_messages.data:
419
+ latest_message = thread_messages.data[0]
420
+ if latest_message.role == "assistant":
421
+ print(f"Assistant: {latest_message.content[0].text.value}")
422
+ response = latest_message.content[0].text.value
423
+ chat_history.append([response, None])
424
+ return "", chat_history
425
+
426
+ # 쓰레드 초기화
427
+ def chat_reset(user_input, chat_history):
428
+ thread = client.beta.threads.create()
429
+ thread_id = thread.id
430
+ user_input = ""
431
+ chat_history = []
432
+ return "", chat_history
433
+
434
+
435
+
436
+
437
+ '''-------------구글 캘린더 연동----------------------------'''
438
+
439
+ from google.auth.transport.requests import Request
440
+ from google.oauth2.credentials import Credentials
441
+ from google_auth_oauthlib.flow import InstalledAppFlow
442
+ from googleapiclient.discovery import build
443
+ from googleapiclient.errors import HttpError
444
+ from google.oauth2 import service_account
445
+ import pytz
446
+
447
+ # ## Google Calendar API
448
+
449
+ '''구글 캘린더 인증 부분 수정'''
450
+ # # Google Calendar API 자격 증명 설정
451
+
452
+ # 캘린더 인증 및 이벤트 변경을 위한 클래스
453
+ class CalendarService:
454
+ def __init__(self, calendar_id='primary',timezone='Asia/Seoul'):
455
+ # self.service_account_file = service_account_file
456
+ self.SCOPES = ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events"]
457
+ self.calendar_id = calendar_id
458
+ self.calendar_service = self.get_calendar_service()
459
+ self.timezone = timezone
460
+
461
+ def get_calendar_service(self):
462
+ """Shows basic usage of the Google Calendar API.
463
+ Prints the start and name of the next 10 events on the user's calendar.
464
+ """
465
+ creds = None
466
+ # The file token.json stores the user's access and refresh tokens, and is
467
+ # created automatically when the authorization flow completes for the first time.
468
+ try:
469
+ if os.path.exists("token.json"):
470
+ creds = Credentials.from_authorized_user_file("token.json", self.SCOPES)
471
+ # If there are no (valid) credentials available, let the user log in.
472
+ if not creds or not creds.valid:
473
+ if creds and creds.expired and creds.refresh_token:
474
+ creds.refresh(Request())
475
+ else:
476
+ flow = InstalledAppFlow.from_client_secrets_file(
477
+ "credentials.json", self.SCOPES
478
+ )
479
+ creds = flow.run_local_server(port=0)
480
+ # Save the credentials for the next run
481
+ with open("token.json", "w") as token:
482
+ token.write(creds.to_json())
483
+ return build('calendar', 'v3', credentials=creds)
484
+ except Exception as e:
485
+ print(f"Error in getting calendar service: {e}")
486
+ return None
487
+
488
+ #이벤트 생성
489
+ def create_event(self, event):
490
+ try:
491
+ event_result = self.calendar_service.events().insert(calendarId=self.calendar_id, body=event).execute()
492
+ return event_result
493
+ except Exception as e:
494
+ print(f"Error in creating event: {e}")
495
+ return None
496
+
497
+ #이벤트 가져오기
498
+ def get_event(self, event_id):
499
+ try:
500
+ event = self.calendar_service.events().get(calendarId=self.calendar_id, eventId=event_id).execute()
501
+ return event
502
+ except Exception as e:
503
+ print(f"Error in getting event: {e}")
504
+ return None
505
+
506
+ #이벤트 업데이트
507
+ def update_event(self, event_id, updated_event):
508
+ try:
509
+ event = self.calendar_service.events().update(calendarId=self.calendar_id, eventId=event_id, body=updated_event).execute()
510
+ return event
511
+ except Exception as e:
512
+ print(f"Error in updating event: {e}")
513
+ return None
514
+
515
+ #이벤트 삭제
516
+ def delete_event(self, event_id):
517
+ try:
518
+ return self.calendar_service.events().delete(calendarId=self.calendar_id, eventId=event_id).execute()
519
+ except Exception as e:
520
+ print(f"Error in deleting event: {e}")
521
+ return None
522
+
523
+ def get_conflicts(self, start_time, end_time):
524
+ try:
525
+ events_result = self.calendar_service.events().list(
526
+ calendarId=self.calendar_id,
527
+ timeMin=start_time,
528
+ timeMax=end_time,
529
+ singleEvents=True,
530
+ orderBy='startTime'
531
+ ).execute()
532
+ events = events_result.get('items', [])
533
+ return events
534
+ except Exception as e:
535
+ print(f"Error in getting conflicts: {e}")
536
+ return None
537
+
538
+ def get_events(self, start_time, end_time):
539
+ events_result = self.calendar_service.events().list(
540
+ calendarId=self.calendar_id,
541
+ timeMin=start_time,
542
+ timeMax=end_time,
543
+ singleEvents=True,
544
+ orderBy='startTime'
545
+ ).execute()
546
+ events = events_result.get('items', [])
547
+ return events
548
+
549
+ def add_calendar_owner(self, user_email):
550
+ calendar_id = 'primary'
551
+ rule = {
552
+ 'scope': {
553
+ 'type': 'user',
554
+ 'value': user_email,
555
+ },
556
+ 'role': 'owner'
557
+ }
558
+ created_rule = self.calendar_service.acl().insert(calendarId=calendar_id, body=rule).execute()
559
+ return created_rule
560
+
561
+ def get_current_datetime_and_timezone(self):
562
+
563
+ timezone_str = self.timezone
564
+ timezone = pytz.timezone(timezone_str)
565
+
566
+ now = datetime.now(timezone)
567
+
568
+ datetime_str = now.strftime('%Y-%m-%d %H:%M:%S %Z%z')
569
+
570
+ return {
571
+ "datetime": datetime_str,
572
+ "timezone": timezone_str
573
+ }
574
+
575
+
576
+
577
+ def execute_function(calendar_service, name, args_dict):
578
+
579
+ method = getattr(calendar_service, name, None)
580
+
581
+ if not method:
582
+ raise ValueError(f"Method '{name}' not found in CalendarService class.")
583
+
584
+ return method(**args_dict)
585
+
586
+
587
+
588
+ ### 구글 캘린더 클래스 인스턴트 생성
589
+ global calendar_service
590
+ calendar_service = CalendarService('primary')
591
+
592
+ ### 캐릭터별 Assistant 생성
593
+ assistant_strict = create_or_update_assistant(client, agent_name, model_name, "strict_charactor")
594
+ assistant_friendly = create_or_update_assistant(client, agent_name, model_name, "friendly_charactor")
595
+
596
+ ### 전역 변수로 쓰레드 ID, assistant ID 저장
597
+ global thread
598
+ thread = client.beta.threads.create()
599
+
600
+ # assistant_strict_id, assistant_friendly_id, thread_id 전역 변수로 저장
601
+ global assistant_strict_id, assistant_friendly_id, thread_id
602
+ assistant_strict_id = assistant_strict.id
603
+ assistant_friendly_id = assistant_friendly.id
604
+ thread_id = thread.id
605
+
606
+ #대화 기록 저장하는 변수 초기화
607
+ chat_history = []
608
+
609
+
610
+ # Chatbot gradio Web 실행
611
+ import gradio as gr
612
+
613
+ # Gradio UI 설정_character 수정_재수정
614
+ with gr.Blocks() as app:
615
+ gr.Markdown("## 마음일정")
616
+
617
+ def chat_ui_strict():
618
+ with gr.Column():
619
+ chat_history = gr.Chatbot(value=[[None, "안녕 나는 마음이야"]], show_label=False)
620
+ with gr.Row():
621
+ user_input = gr.Text(lines=1, placeholder="", container=False, scale=9)
622
+ cb_send_btn = gr.Button(value="reply", size="small", scale=1)
623
+ reset_btn = gr.Button(value="reset", size="small", scale=1)
624
+
625
+ cb_send_btn.click(fn=start_chat_strict, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
626
+ user_input.submit(fn=start_chat_strict, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
627
+ reset_btn.click(fn=chat_reset, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
628
+
629
+ return chat_history, user_input, cb_send_btn, reset_btn
630
+ def chat_ui_friendly():
631
+ with gr.Column():
632
+ chat_history = gr.Chatbot(value=[[None, "안녕 나는 마음이야"]], show_label=False)
633
+ with gr.Row():
634
+ user_input = gr.Text(lines=1, placeholder="", container=False, scale=10)
635
+ cb_send_btn = gr.Button(value="reply", size="small", scale=1)
636
+ reset_btn = gr.Button(value="reset", size="small", scale=1)
637
+
638
+
639
+ cb_send_btn.click(fn=start_chat_friendly, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
640
+ user_input.submit(fn=start_chat_friendly, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
641
+ reset_btn.click(fn=chat_reset, inputs=[user_input, chat_history], outputs=[user_input, chat_history])
642
+ return chat_history, user_input, cb_send_btn, reset_btn
643
+ with gr.Tab("Friendly"):
644
+ character = "friendly_charactor"
645
+ chat_ui_friendly()
646
+
647
+ with gr.Tab("Strict"):
648
+ character = "strict_charactor"
649
+ chat_ui_strict()
650
+
651
+
652
+ app.launch(share=True)
653
+
654
+
credentials.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"installed":{"client_id":"633821005299-ou61ditaviamu3rl6a9rkthn13nb4018.apps.googleusercontent.com","project_id":"tryngo-ssem","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"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","redirect_uris":["http://localhost"]}}
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ openai
3
+ google-auth
4
+ google-auth-oauthlib
5
+ google-auth-httplib2
6
+ google-api-python-client
7
+ pytz