-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathclaude.py
794 lines (654 loc) · 35.4 KB
/
claude.py
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
import os
from anthropic import Anthropic
from datetime import datetime, time, timedelta
import pytz
import requests
from bs4 import BeautifulSoup
from google.cloud import storage
import io
import uuid
import json
import wikipedia
from PIL import Image
from openai import OpenAI
import re
import time
from vertexai.preview.vision_models import ImageGenerationModel
from anthropic_tools.base_tool import BaseTool
from anthropic_tools.tool_user import ToolUser
google_api_key = os.getenv("GOOGLE_API_KEY")
google_cse_id = os.getenv("GOOGLE_CSE_ID")
google_cse_id1 = os.getenv("GOOGLE_CSE_ID1")
anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")
openai_api_key = os.getenv('OPENAI_API_KEY')
claude_client = Anthropic(
# This is the default and can be omitted
api_key=anthropic_api_key,
)
i_prompt = ""
user_id = []
message_id = []
bucket_name = []
file_age = []
public_img_url = ""
public_img_url_s = ""
gaccount_access_token = ""
gaccount_refresh_token = ""
CORE_IMAGE_TYPE = ""
VERTEX_IMAGE_MODEL = ""
class Clock(BaseTool):
def use_tool(self):
jst = pytz.timezone('Asia/Tokyo')
nowDate = datetime.now(jst)
nowDateStr = nowDate.strftime('%Y/%m/%d %H:%M:%S %Z')
return "SYSTEM:現在時刻は" + nowDateStr + "です。"
class Googlesearch(BaseTool):
def use_tool(self, words):
num = 3
start_index = 1
search_lang = 'lang_ja'
base_url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": google_api_key,
"cx": google_cse_id,
"q": words, # 結合された検索クエリ
"num": num,
"start": start_index,
"lr": search_lang
}
response = requests.get(base_url, params=params)
response.raise_for_status()
search_results = response.json()
# 検索結果を文字列に整形
formatted_results = ""
for item in search_results.get("items", []):
title = item.get("title")
link = item.get("link")
snippet = item.get("snippet")
formatted_results += f"タイトル: {title}\nリンク: {link}\n概要: {snippet}\n\n"
return f"SYSTEM:Webページを検索しました。{words}と関係のありそうなURLを読み込んでください。\n" + formatted_results
class Customsearch1(BaseTool):
def use_tool(self, words):
num = 3
start_index = 1
search_lang = 'lang_ja'
base_url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": google_api_key,
"cx": google_cse_id1,
"q": words,
"num": num,
"start": start_index,
"lr": search_lang
}
response = requests.get(base_url, params=params)
response.raise_for_status()
search_results = response.json()
# 検索結果を文字列に整形
formatted_results = ""
for item in search_results.get("items", []):
title = item.get("title")
link = item.get("link")
snippet = item.get("snippet")
formatted_results += f"タイトル: {title}\nリンク: {link}\n概要: {snippet}\n\n"
return f"SYSTEM:Webページを検索しました。{words}と関係のありそうなURLを読み込んでください。\n" + formatted_results
class Wikipediasearch(BaseTool):
def use_tool(self, words):
try:
wikipedia.set_lang("ja")
search_result = wikipedia.page(words)
summary = search_result.summary
page_url = search_result.url
# 結果を1000文字に切り詰める
if len(summary) > 2000:
summary = summary[:2000] + "..."
return f"SYSTEM: 以下は{page_url}の読み込み結果です。情報を提示するときは情報とともに参照元URLアドレスも案内してください。\n{summary}"
except wikipedia.exceptions.DisambiguationError as e:
return f"SYSTEM: 曖昧さ解消が必要です。オプション: {e.options}"
except wikipedia.exceptions.PageError:
return "SYSTEM: ページが見つかりませんでした。"
class Scraping(BaseTool):
def use_tool(self, URL):
contents = ""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
}
try:
response = requests.get(URL, headers=headers, timeout=5)
response.raise_for_status()
response.encoding = response.apparent_encoding # または特定のエンコーディングを指定
html = response.text
except requests.RequestException as e:
return f"SYSTEM: リンクの読み込み中にエラーが発生しました: {e}"
soup = BeautifulSoup(html, features="html.parser")
# Remove all 'a' tags
for a in soup.findAll('a'):
a.decompose()
content = soup.select_one("article, .post, .content")
if content is None or content.text.strip() == "":
content = soup.select_one("body")
if content is not None:
contents = ' '.join(content.text.split()).replace("。 ", "。\n").replace("! ", "!\n").replace("? ", "?\n").strip()
# 結果を1000文字に切り詰める
if len(contents) > 2000:
contents = contents[:2000] + "..."
return f"SYSTEM:以下はURL「{URL}」の読み込み結果です。情報を提示するときは情報とともにURLも案内してください。\n" + contents
def set_bucket_lifecycle(bucket_name, age):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
rule = {
'action': {'type': 'Delete'},
'condition': {'age': age} # The number of days after object creation
}
bucket.lifecycle_rules = [rule]
bucket.patch()
return
def bucket_exists(bucket_name):
"""Check if a bucket exists."""
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
return bucket.exists()
def download_image(image_url, filename):
""" PNG画像をダウンロードしてファイルに保存する """
response = requests.get(image_url)
with open(filename, 'wb') as file:
file.write(response.content)
return filename
def create_preview_image(original_image_stream):
""" 画像のサイズを縮小してプレビュー用画像を生成する """
image = Image.open(original_image_stream)
image.thumbnail((640, 640)) # 画像の最大サイズを1024x1024に制限
preview_image = io.BytesIO()
image.save(preview_image, format='PNG')
preview_image.seek(0)
return preview_image
def upload_blob(bucket_name, source_stream_or_path, destination_blob_name, content_type='image/png'):
"""Uploads a file to the bucket from either a file path or a byte stream."""
try:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
if isinstance(source_stream_or_path, (str, bytes, os.PathLike)):
# ファイルパスが渡された場合、ファイルを開く
with open(source_stream_or_path, 'rb') as file_obj:
blob.upload_from_file(file_obj, content_type=content_type)
else:
# BytesIOが渡された場合、そのままアップロード
blob.upload_from_file(source_stream_or_path, content_type=content_type)
public_url = f"https://storage.googleapis.com/{bucket_name}/{destination_blob_name}"
return public_url
except Exception as e:
print(f"Failed to upload file: {e}")
raise
def save_image_locally(image_result):
# ユニークなファイル名を生成
filename = f"{uuid.uuid4()}.png"
# 画像をローカルに保存
image_result.save(filename) # saveメソッドを使用して画像を保存
# 保存した画像のファイルパスを返す
return filename
class Generateimage(BaseTool):
def use_tool(self, sentence):
global public_img_url, public_img_url_s
filename = str(uuid.uuid4())
blob_path = f'{user_id}/{message_id}.png'
preview_blob_path = f'{user_id}/{message_id}_s.png'
client = OpenAI(api_key=openai_api_key)
prompt = " ".join(sentence) + "\n" + i_prompt
public_img_url = ""
public_img_url_s = ""
image_result = None
png_image = None
try:
if CORE_IMAGE_TYPE == "Vertex":
image_model = ImageGenerationModel.from_pretrained(VERTEX_IMAGE_MODEL)
response = image_model.generate_images(
prompt=prompt,
number_of_images=1,
guidance_scale=float("1024"),
aspect_ratio="1:1",
language="ja",
seed=None,
)
png_image = save_image_locally(response[0])
else:
response = client.images.generate(
model="dall-e-3",
prompt=prompt,
size="1024x1024",
quality="standard",
n=1,
)
image_result = response.data[0].url
png_image = f"{uuid.uuid4()}.png" # Generate a unique file name
download_image(image_result, png_image) # Save image to file
if bucket_exists(bucket_name):
set_bucket_lifecycle(bucket_name, file_age)
else:
print(f"Bucket {bucket_name} does not exist.")
return "SYSTEM:バケットが存在しません。"
preview_image = create_preview_image(png_image)
# 画像をアップロード
public_img_url = upload_blob(bucket_name, png_image, blob_path)
public_img_url_s = upload_blob(bucket_name, preview_image, preview_blob_path)
time.sleep(2)
return f"SYSTEM:{prompt}のキーワードで画像を生成し、表示しました。画像が生成された旨をメッセージで伝えてください。"
except Exception as e:
print(f"generate_image error: {e}" )
return f"SYSTEM: 画像生成にエラーが発生しました。エラーの理由は以下になります。\n{e}"
def create_credentials(gaccount_access_token, gaccount_refresh_token):
return Credentials(
token=gaccount_access_token,
refresh_token=gaccount_refresh_token,
client_id=google_client_id,
client_secret=google_client_secret,
token_uri='https://oauth2.googleapis.com/token'
)
class Getcalendar(BaseTool):
def use_tool(self, max_chars=1000):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
# トークン更新をチェック
if credentials.expired:
credentials.refresh(Request())
# Google Calendar APIのserviceオブジェクトを構築
service = build('calendar', 'v3', credentials=credentials)
# 現在時刻
jst = pytz.timezone('Asia/Tokyo')
now = datetime.now(jst).isoformat()
# Google Calendar APIを呼び出して、直近のイベントを取得
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=50, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
gaccount_access_token = credentials.token
gaccount_refresh_token = credentials.refresh_token
return "直近のイベントはありません。"
# イベントの詳細を結合して最大1000文字までの文字列を生成
events_str = ""
for event in events:
event_id = event['id']
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date'))
summary = event.get('summary', '無題')
description = event.get('description', '説明なし')
location = event.get('location', '場所なし')
event_str = f"ID: {event_id}, Summary: {summary}, Start: {start}, End: {end}, Description: {description}, Location: {location}\n"
if len(events_str) + len(event_str) > max_chars:
break # 最大文字数を超えたらループを抜ける
events_str += event_str
gaccount_access_token = credentials.token
gaccount_refresh_token = credentials.refresh_token
return "SYSTEM:カレンダーのイベントを取得しました。イベント内容を要約してください。" + events_str[:max_chars]
except Exception as e:
print(f"Error during calendar event retrieval: {e}")
return f"SYSTEM: カレンダーのイベント取得にエラーが発生しました。{e}"
class Addcalendar(BaseTool):
def use_tool(self, summary, start_time, end_time, description=None, location=None):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
# トークン更新をチェック
if credentials.expired:
credentials.refresh(Request())
# Google Calendar APIのserviceオブジェクトを構築
service = build('calendar', 'v3', credentials=credentials)
# イベントの情報を設定
event = {
'summary': summary,
'location': location,
'description': description,
'start': {
'dateTime': start_time,
'timeZone': 'Asia/Tokyo',
},
'end': {
'dateTime': end_time,
'timeZone': 'Asia/Tokyo',
},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
# イベントをカレンダーに追加
event_result = service.events().insert(calendarId='primary', body=event).execute()
# 成功した場合、イベントの詳細を含むメッセージを返す
gaccount_access_token = credentials.token
gaccount_refresh_token = credentials.refresh_token
return f"次のイベントが追加されました: summary={summary}, start_time={start_time}, end_time={end_time}, description={description}, location={location}"
except Exception as e:
return f"イベント追加に失敗しました: {e}"
class Updatecalendar(BaseTool):
def use_tool(self, event_id, summary=None, start_time=None, end_time=None, description=None, location=None):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
if credentials.expired:
credentials.refresh(Request())
service = build('calendar', 'v3', credentials=credentials)
# 現在のイベント情報を取得
current_event = service.events().get(calendarId='primary', eventId=event_id).execute()
# 更新が提供されていない項目は現在の情報をそのまま使用
updated_event = {
'summary': summary if summary is not None else current_event.get('summary'),
'location': location if location is not None else current_event.get('location'),
'description': description if description is not None else current_event.get('description'),
'start': {'dateTime': start_time, 'timeZone': 'Asia/Tokyo'} if start_time is not None else current_event.get('start'),
'end': {'dateTime': end_time, 'timeZone': 'Asia/Tokyo'} if end_time is not None else current_event.get('end'),
}
# イベントを更新
updated_event_result = service.events().update(calendarId='primary', eventId=event_id, body=updated_event).execute()
gaccount_access_token = credentials.token
gaccount_refresh_token = credentials.refresh_token
return f"イベントが更新されました: {updated_event_result['summary']}"
except Exception as e:
return f"イベント更新に失敗しました: {e}"
class Deletecalendar(BaseTool):
def use_tool(self, event_id):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
if credentials.expired:
credentials.refresh(Request())
service = build('calendar', 'v3', credentials=credentials)
# 削除するイベントの詳細を取得(特にsummaryを含む)
event_to_delete = service.events().get(calendarId='primary', eventId=event_id).execute()
event_summary = event_to_delete.get('summary', '無題のイベント') # イベントにsummaryがない場合のデフォルト値
# イベントを削除
service.events().delete(calendarId='primary', eventId=event_id).execute()
gaccount_access_token = credentials.token
gaccount_refresh_token = credentials.refresh_token
return f"イベント「{event_summary}」が削除された旨をユーザーに伝えてください。"
except Exception as e:
return f"イベント削除に失敗しました: {e}"
class Getgmaillist(BaseTool):
def use_tool(self, max_results=20):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
if credentials.expired:
credentials.refresh(Request())
service = build('gmail', 'v1', credentials=credentials)
# maxResultsを20に設定して20件のメールを取得
results = service.users().messages().list(userId='me', maxResults=max_results).execute()
messages = results.get('messages', [])
updated_access_token = credentials.token
if not messages:
return "SYSTEM: 直近のメッセージはありません。", updated_access_token, credentials.refresh_token
messages_details = []
for msg in messages:
msg_detail = service.users().messages().get(userId='me', id=msg['id'], format='metadata').execute()
headers = msg_detail.get('payload', {}).get('headers', [])
# 必要な情報をヘッダーから取得
subject = next((i['value'] for i in headers if i['name'].lower() == 'subject'), "No Subject")
from_email = next((i['value'] for i in headers if i['name'].lower() == 'from'), "Unknown Sender")
date_received = next((i['value'] for i in headers if i['name'].lower() == 'date'), "No Date")
date_parsed = parser.parse(date_received).strftime('%Y-%m-%d %H:%M:%S')
messages_details.append({
'id': msg['id'],
'from': from_email,
'subject': subject,
'date_received': date_parsed
})
messages_str = "\n".join([f"From: {m['from']}, Subject: {m['subject']}, Date: {m['date_received']}" for m in messages_details])
return f"SYSTEM: メール一覧を受信しました。一覧の内容をユーザーに伝えてください。\n{messages_str}", updated_access_token, credentials.refresh_token
except Exception as e:
print(f"e: {e}")
return f"SYSTEM: メール一覧の取得にエラーが発生しました。{e}", gaccount_access_token, gaccount_refresh_token
class Getgmailcontent(BaseTool):
def use_tool(self, search_query, max_results=5):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
if credentials.expired:
credentials.refresh(Request())
service = build('gmail', 'v1', credentials=credentials)
# メールを検索するためのクエリを使用
results = service.users().messages().list(userId='me', q=search_query, maxResults=max_results).execute()
messages = results.get('messages', [])
updated_access_token = credentials.token
emails_content = []
for msg in messages:
txt = service.users().messages().get(userId='me', id=msg['id'], format='full').execute()
payload = txt.get('payload', {})
headers = payload.get('headers', [])
subject = next((i['value'] for i in headers if i['name'].lower() == 'subject'), "No Subject")
from_email = next((i['value'] for i in headers if i['name'].lower() == 'from'), "Unknown Sender")
date_received = next((i['value'] for i in headers if i['name'].lower() == 'date'), "No Date")
# メール本文の取得
body = ""
if 'parts' in payload:
for part in payload['parts']:
if part['mimeType'] == 'text/plain' or part['mimeType'] == 'text/html':
body_data = part['body'].get('data', '')
body = base64.urlsafe_b64decode(body_data).decode('utf-8')
if len(body) > 500:
body = body[:500] # 本文を500文字にカット
break
else:
body_data = payload.get('body', {}).get('data', '')
if body_data:
body = base64.urlsafe_b64decode(body_data).decode('utf-8')
if len(body) > 500:
body = body[:500] # 本文を500文字にカット
emails_content.append({
'subject': subject,
'from': from_email,
'date_received': date_received,
'body': body
})
# メールの内容を文字列に変換
emails_content_str = "\n".join([f"Subject: {email['subject']}, From: {email['from']}, Date: {email['date_received']}, Body: {email['body'][:500]}" for email in emails_content])
return "SYSTEM: 検索条件に一致するメールを受信しました。メールの内容をユーザーに伝えてください。\n" + emails_content_str, updated_access_token, credentials.refresh_token
except Exception as e:
print(f"e: {e}")
return f"SYSTEM: メールの検索にエラーが発生しました。{e}", gaccount_access_token, gaccount_refresh_token
class Sendgmailcontent(BaseTool):
def use_tool(self, to_email, subject, body):
global gaccount_access_token, gaccount_refresh_token
try:
credentials = create_credentials(
gaccount_access_token,
gaccount_refresh_token
)
if credentials.expired:
credentials.refresh(Request())
service = build('gmail', 'v1', credentials=credentials)
# メールのメッセージを作成
message = email.message.EmailMessage()
message.set_content(body)
message['To'] = to_email
message['From'] = 'me'
message['Subject'] = subject
# メッセージをbase64でエンコード
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
# Gmail APIを使用してメッセージを送信
send_message = {
'raw': encoded_message
}
send_result = service.users().messages().send(userId='me', body=send_message).execute()
updated_access_token = credentials.token
return f"SYSTEM: 次の内容のメールを送信しました。メール送信が完了した旨をユーザーに伝えてください。\nTo: {to_email}\nSubject: {subject}\nBody: {body}", updated_access_token, credentials.refresh_token
except Exception as e:
print(f"e: {e}")
return f"SYSTEM: メール送信にエラーが発生しました。{e}", gaccount_access_token, gaccount_refresh_token
def run_conversation(CLAUDE_MODEL, SYSTEM_PROMPT, messages):
try:
response = claude_client.messages.create(
max_tokens=1024,
system=SYSTEM_PROMPT,
messages=messages,
model=CLAUDE_MODEL,
)
return response # レスポンス全体を返す
except Exception as e:
print(f"An error occurred: {e}")
return None # エラー時には None を返す
def run_conversation_f(CLAUDE_MODEL, FUNCTIONS, messages, GOOGLE_DESCRIPTION, CUSTOM_DESCRIPTION):
try:
clock_tool_name = "perform_clock"
clock_tool_description = "useful for when you need to know what time it is."
clock_tool_parameters = [
]
googlesearch_tool_name = "perform_googlesearch"
googlesearch_tool_description = GOOGLE_DESCRIPTION
googlesearch_tool_parameters = [
{"name": "words", "type": "str", "description": "a search key word"}
]
customsearch1_tool_name = "perform_customsearch1"
customsearch1_tool_description = CUSTOM_DESCRIPTION
customsearch1_tool_parameters = [
{"name": "words", "type": "str", "description": "a search key word"}
]
wikipediasearch_tool_name = "perform_wikipediasearch"
wikipediasearch_tool_description = "useful for when you need to Read dictionary page by specifying the word."
wikipediasearch_tool_parameters = [
{"name": "words", "type": "str", "description": "a search key word"}
]
scraping_tool_name = "perform_scraping"
scraping_tool_description = "useful for when you need to read a web page by specifying the URL."
scraping_tool_parameters = [
{"name": "URL", "type": "str", "description": "a URL for scraping"}
]
generateimage_tool_name = "perform_generateimage"
generateimage_tool_description = "useful for when you need to generate an image by the sentence."
generateimage_tool_parameters = [
{"name": "sentence", "type": "str", "description": "a text for image generation"}
]
getcalendar_tool_name = "perform_getcalendar"
getcalendar_tool_description = "You can add schedules."
getcalendar_tool_parameters = [
]
addcalendar_tool_name = "perform_addcalendar"
addcalendar_tool_description = "You can add schedules."
addcalendar_tool_parameters = [
{"name": "summary", "type": "str", "description": "スケジュールのサマリー(必須)"},
{"name": "start_time", "type": "str", "description": "スケジュールの開始時間をRFC3339フォーマットの日本時間で指定(必須)"},
{"name": "end_time", "type": "str", "description": "スケジュールの終了時間をRFC3339フォーマットの日本時間で指定(必須)"},
{"name": "description", "type": "str", "description": "スケジュールした内容の詳細な説明(必須)"},
{"name": "location", "type": "str", "description": "スケジュールの内容を実施する場所(必須)"}
]
updatecalendar_tool_name = "perform_updatecalendar"
updatecalendar_tool_description = "You can update schedules by the event ID of the schedule."
updatecalendar_tool_parameters = [
{"name": "event_id", "type": "str", "description": "スケジュールのイベントID(必須)"},
{"name": "summary", "type": "str", "description": "更新後のスケジュールのサマリー(必須)"},
{"name": "start_time", "type": "str", "description": "更新後のスケジュールの開始時間をRFC3339フォーマットの日本時間で指定(必須)"},
{"name": "end_time", "type": "str", "description": "更新後のスケジュールの終了時間をRFC3339フォーマットの日本時間で指定(必須)"},
{"name": "description", "type": "str", "description": "更新後のスケジュールした内容の詳細な説明(必須)"},
{"name": "location", "type": "str", "description": "更新後のスケジュールの内容を実施する場所(必須)"},
]
deletecalendar_tool_name = "perform_deletecalendar"
deletecalendar_tool_description = "You can delete schedules by the event ID of the schedule."
deletecalendar_tool_parameters = [
{"name": "event_id", "type": "str", "description": "削除対象のスケジュールのイベントID(必須)"}
]
getgmaillist_tool_name = "perform_getgmaillist"
getgmaillist_tool_description = "You can get Gmail latest list."
getgmaillist_tool_parameters = [
]
getgmailcontent_tool_name = "perform_getgmailcontent"
getgmailcontent_tool_description = "You can read Gmail content by a search query."
getgmailcontent_tool_parameters = [
{"name": "search_query", "type": "str", "description": "検索文字列(必須)"}
]
sendgmailcontent_tool_name = "perform_sendgmailcontent"
sendgmailcontent_tool_description = "You send Gmail content by a email and a subject and a content."
sendgmailcontent_tool_parameters = [
{"name": "to_email", "type": "str", "description": "送信先メールアドレス(必須)"},
{"name": "subject", "type": "str", "description": "作成するメールの題名(必須)"},
{"name": "search_query", "type": "str", "description": "作成するメールの内容(必須)"}
]
clock_tool = Clock(clock_tool_name, clock_tool_description, clock_tool_parameters)
googlesearch_tool = Googlesearch(googlesearch_tool_name, googlesearch_tool_description, googlesearch_tool_parameters)
customsearch1_tool = Customsearch1(customsearch1_tool_name, customsearch1_tool_description, customsearch1_tool_parameters)
wikipediasearch_tool = Wikipediasearch(wikipediasearch_tool_name, wikipediasearch_tool_description, wikipediasearch_tool_parameters)
scraping_tool = Scraping(scraping_tool_name, scraping_tool_description, scraping_tool_parameters)
generateimage_tool = Generateimage(generateimage_tool_name, generateimage_tool_description, generateimage_tool_parameters)
getcalendar_tool = Getcalendar(getcalendar_tool_name, getcalendar_tool_description, getcalendar_tool_parameters)
addcalendar_tool = Addcalendar(addcalendar_tool_name, addcalendar_tool_description, addcalendar_tool_parameters)
updatecalendar_tool = Updatecalendar(updatecalendar_tool_name, updatecalendar_tool_description, updatecalendar_tool_parameters)
deletecalendar_tool = Deletecalendar(deletecalendar_tool_name, deletecalendar_tool_description, deletecalendar_tool_parameters)
getgmaillist_tool = Getgmaillist(getgmaillist_tool_name, getgmaillist_tool_description, getgmaillist_tool_parameters)
getgmailcontent_tool = Getgmailcontent(getgmailcontent_tool_name, getgmailcontent_tool_description, getgmailcontent_tool_parameters)
sendgmailcontent_tool = Sendgmailcontent(sendgmailcontent_tool_name, sendgmailcontent_tool_description, sendgmailcontent_tool_parameters)
functions = []
functions.append(clock_tool)
if "googlesearch" in FUNCTIONS:
functions.append(googlesearch_tool)
if "customsearch" in FUNCTIONS:
functions.append(customsearch1_tool)
if "wikipedia" in FUNCTIONS:
functions.append(wikipediasearch_tool)
if "scraping" in FUNCTIONS:
functions.append(scraping_tool)
if "generateimage" in FUNCTIONS:
functions.append(generateimage_tool)
if "googlecalendar" in FUNCTIONS:
functions.append(getcalendar_tool)
functions.append(addcalendar_tool)
functions.append(updatecalendar_tool)
functions.append(deletecalendar_tool)
if "googlemail" in FUNCTIONS:
functions.append(getgmaillist_tool)
functions.append(getgmailcontent_tool)
functions.append(sendgmailcontent_tool)
all_tool_user = ToolUser(functions, CLAUDE_MODEL)
response = all_tool_user.use_tools(messages, execution_mode='automatic')
# re.DOTALLフラグを使って、改行を含むテキストもマッチさせる
result_match = re.search(r'<result>(.*?)</result>', response, re.DOTALL)
if result_match:
result_content = result_match.group(1) # タグ内の文字列を取得
return result_content.strip() # 先頭と末尾の空白文字を削除
else:
return response
except Exception as e:
print(f"An error occurred: {e}")
return None # エラー時には None を返す
def claude_functions(CLAUDE_MODEL, FUNCTIONS, SYSTEM_PROMPT ,messages_for_api, USER_ID, MESSAGE_ID, ERROR_MESSAGE, PAINT_PROMPT, BUCKET_NAME, FILE_AGE, GOOGLE_DESCRIPTION, CUSTOM_DESCRIPTION, i_gaccount_access_token="", i_gaccount_refresh_token="", i_CORE_IMAGE_TYPE="", i_VERTEX_IMAGE_MODEL="" , max_attempts=5):
global i_prompt, user_id, message_id, bucket_name, file_age
global public_img_url, public_img_url_s
global gaccount_access_token, gaccount_refresh_token
global CORE_IMAGE_TYPE, VERTEX_IMAGE_MODEL
gaccount_access_token = i_gaccount_access_token
gaccount_refresh_token = i_gaccount_refresh_token
CORE_IMAGE_TYPE = i_CORE_IMAGE_TYPE
VERTEX_IMAGE_MODEL = i_VERTEX_IMAGE_MODEL
public_img_url = None
public_img_url_s = None
i_prompt = PAINT_PROMPT
user_id = USER_ID
message_id = MESSAGE_ID
bucket_name = BUCKET_NAME
file_age = FILE_AGE
i_messages_for_api = messages_for_api.copy()
last_messages_for_api = i_messages_for_api[-1]
head_messages_for_api= [{'role': 'user', 'content': SYSTEM_PROMPT}]
head_messages_for_api.extend(i_messages_for_api)
response = run_conversation_f(CLAUDE_MODEL, FUNCTIONS, head_messages_for_api, GOOGLE_DESCRIPTION, CUSTOM_DESCRIPTION)
bot_reply = response
return bot_reply, public_img_url, public_img_url_s, gaccount_access_token, gaccount_refresh_token