fudii0921 commited on
Commit
9a1fdaa
·
verified ·
1 Parent(s): 331169c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -0
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+ from autogen import AssistantAgent, UserProxyAgent
6
+ from autogen.coding import LocalCommandLineCodeExecutor
7
+ import gradio as gr
8
+ from autogen import ConversableAgent
9
+ from autogen import register_function
10
+ import mysql.connector
11
+ import random
12
+ import requests
13
+ from groq import Groq
14
+ from dotenv import load_dotenv
15
+ import urllib.parse
16
+
17
+
18
+ #tool_resp = ""
19
+ tool_topic = ""
20
+
21
+ js = """
22
+ function createGradioAnimation() {
23
+ var container = document.createElement('div');
24
+ container.id = 'gradio-animation';
25
+ container.style.fontSize = '2em';
26
+ container.style.fontWeight = 'bold';
27
+ container.style.textAlign = 'center';
28
+ container.style.marginBottom = '20px';
29
+
30
+ var text = 'wiki分析';
31
+ for (var i = 0; i < text.length; i++) {
32
+ (function(i){
33
+ setTimeout(function(){
34
+ var letter = document.createElement('span');
35
+ var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
36
+ letter.style.color = randomColor;
37
+ letter.style.opacity = '0';
38
+ letter.style.transition = 'opacity 0.5s';
39
+ letter.innerText = text[i];
40
+
41
+ container.appendChild(letter);
42
+
43
+ setTimeout(function() {
44
+ letter.style.opacity = '1';
45
+ }, 50);
46
+
47
+ // Blink the text 3 times
48
+ for (var j = 0; j < 3; j++) {
49
+ setTimeout(function() {
50
+ letter.style.opacity = '0';
51
+ }, 500 + j * 1000);
52
+ setTimeout(function() {
53
+ letter.style.opacity = '1';
54
+ }, 1000 + j * 1000);
55
+ }
56
+ }, i * 250);
57
+ })(i);
58
+ }
59
+
60
+ var gradioContainer = document.querySelector('.gradio-container');
61
+ gradioContainer.insertBefore(container, gradioContainer.firstChild);
62
+
63
+ return 'Animation created';
64
+ }
65
+ """
66
+
67
+ load_dotenv(verbose=True)
68
+
69
+ conn = mysql.connector.connect(
70
+ host=os.environ.get("HOST"),
71
+ user=os.environ.get("USER_NAME"),
72
+ password=os.environ.get("PASSWORD"),
73
+ port=os.environ.get("PORT"),
74
+ database=os.environ.get("DB"),
75
+ ssl_disabled=True
76
+ )
77
+
78
+ cursor = conn.cursor(dictionary=True)
79
+
80
+ def get_rounrobin():
81
+ select_one_data_query = "select api from agentic_apis_count order by counts ASC"
82
+ cursor.execute(select_one_data_query)
83
+ result = cursor.fetchall()
84
+ first_api = result[0]['api']
85
+ return first_api
86
+
87
+ # MySQLに接続
88
+ def get_api_keys():
89
+ token = get_rounrobin()
90
+ os.environ["GROQ_API_KEY"] = token
91
+
92
+ return token
93
+
94
+ # Configure Groq
95
+ config_list = [{
96
+ "model": "llama-3.3-70b-versatile",
97
+ "api_key": os.environ["GROQ_API_KEY"],
98
+ "api_type": "groq"
99
+ }]
100
+
101
+
102
+ # Create a directory to store code files from code executor
103
+ work_dir = Path("coding")
104
+ work_dir.mkdir(exist_ok=True)
105
+ code_executor = LocalCommandLineCodeExecutor(work_dir=work_dir)
106
+
107
+ # Define wiki tool
108
+ def get_wiki_content(topic):
109
+ """Get the info for some material"""
110
+
111
+ global tool_topic
112
+ print("parms:",tool_topic)
113
+ tmp_url = urllib.parse.unquote('https://ja.wikipedia.org/api/rest_v1/page/summary/'+tool_topic)
114
+ #print("tmp_url:",tmp_url)
115
+ data = requests.get(tmp_url)
116
+ #print('request:',data.content.decode("utf-8"))
117
+ # 元のデータ
118
+ datas = json.loads(data.content.decode("utf-8"))
119
+ #print('jload:',datas)
120
+
121
+
122
+ # 指定された形式に変換
123
+ #revenue_data = {item["title"]: {"revenue": item["extract"]} for item in datas}
124
+ #print("revenue data:",revenue_data)
125
+
126
+ jdump = json.dumps({
127
+ "title": datas["title"],
128
+ "content": datas["extract"],
129
+ })
130
+ #print("jdump:",jdump)
131
+ return jdump
132
+
133
+ # Create an AI assistant that uses the kpi tool
134
+ assistant = AssistantAgent(
135
+ #assistant = ConversableAgent(
136
+ name="groq_assistant",
137
+ system_message="""あなたは、次のことができる役に立つAIアシスタントです。
138
+ - 情報検索ツールを使用する
139
+ - 結果を分析して自然言語のみで説明する""",
140
+ llm_config={"config_list": config_list}
141
+ )
142
+
143
+ # Create a user proxy agent that only handles code execution
144
+ user_proxy = UserProxyAgent(
145
+ #user_proxy = ConversableAgent(
146
+ name="user_proxy",
147
+ human_input_mode="NEVER",
148
+ code_execution_config={"work_dir":"coding", "use_docker":False},
149
+ max_consecutive_auto_reply=2,
150
+ #llm_config={"config_list": config_list}
151
+ )
152
+
153
+
154
+ # Register weather tool with the assistant
155
+ @user_proxy.register_for_execution()
156
+ @assistant.register_for_llm(description="extractの内容")
157
+ def revenue_analysis(
158
+ title: Annotated[str, "title"],
159
+ topic: Annotated[str, "topic"]
160
+ ) -> str:
161
+ #global tool_topic
162
+ print("parameters:",title,topic)
163
+ wiki_details = get_wiki_content(title)
164
+ wikis = json.loads(wiki_details)
165
+ print("myRevenue:",wikis)
166
+
167
+ return f"{wikis['title']}の内容は{wikis['content']}"
168
+
169
+
170
+ def get_wiki_and_respond(prompt,topic):
171
+ get_api_keys()
172
+
173
+ print("mytopic-is:",topic)
174
+ global tool_topic
175
+ tool_topic = topic
176
+
177
+ # Start the conversation
178
+ resp = user_proxy.initiate_chat(
179
+ assistant,
180
+ message=f"""3つのことをやってみましょう:
181
+ 1. {prompt}の内容をtoolを利用して抽出します。
182
+ 2. toolを利用して抽出された内容を詳しく分析します。
183
+ 3. 日本語で説明してください。
184
+ """
185
+ )
186
+
187
+ total_tokens = resp.cost['usage_including_cached_inference']['llama-3.3-70b-versatile']['total_tokens']
188
+
189
+ groq_assistant_contents = [entry['content'] for entry in resp.chat_history if entry['role'] == 'user' and entry['name'] == 'groq_assistant']
190
+
191
+ usages = "使用トークン数: "+str(total_tokens)
192
+ return groq_assistant_contents,usages
193
+
194
+ # Create Gradio interface
195
+ iface = gr.Interface(
196
+ js=js,
197
+ fn=get_wiki_and_respond,
198
+ inputs=[gr.Textbox(label="プロンプト",value="アユタヤ王朝とは何ですか?"),gr.Textbox(label="topic",value="アユタヤ王朝")],
199
+ outputs=[gr.Textbox(label="結果"),gr.Textbox(label="Usageデータ")],
200
+ title="資料の分析",
201
+ description="プロンプトを入力してデータを取得し、内容を分析します。",
202
+ submit_btn="実行",
203
+ clear_btn="クリア",
204
+ flagging_mode="never"
205
+ )
206
+
207
+ iface.launch()