Romanchello-bit commited on
Commit
7b43e9f
·
1 Parent(s): 3519f60

gemini api added

Browse files
Files changed (3) hide show
  1. benchmark_results.png +0 -0
  2. sellme_pro.py +1 -1
  3. sellme_smart.py +168 -0
benchmark_results.png CHANGED
sellme_pro.py CHANGED
@@ -104,7 +104,7 @@ def main():
104
 
105
  # Configure Gemini
106
  genai.configure(api_key=api_key)
107
- model = genai.GenerativeModel('gemini-1.5-pro')
108
 
109
  print("\n[INFO] Gemini configured successfully!")
110
  print("[INFO] Loading sales script...\n")
 
104
 
105
  # Configure Gemini
106
  genai.configure(api_key=api_key)
107
+ model = genai.GenerativeModel('gemini-2.5-flash')
108
 
109
  print("\n[INFO] Gemini configured successfully!")
110
  print("[INFO] Loading sales script...\n")
sellme_smart.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+ import google.generativeai as genai
5
+ from graph_module import Graph
6
+ from algorithms import bellman_ford_list
7
+
8
+ # --- ФІКС КОДУВАННЯ ДЛЯ WINDOWS ---
9
+ sys.stdout.reconfigure(encoding='utf-8')
10
+
11
+ # --- ТВОЯ МОДЕЛЬ ---
12
+ MODEL_NAME = "gemini-2.5-flash"
13
+
14
+ def configure_genai():
15
+ """Налаштування API ключа"""
16
+ api_key = os.environ.get("GOOGLE_API_KEY")
17
+ if not api_key:
18
+ print("--- Налаштування API ---")
19
+ api_key = input("Встав свій Google API Key (права кнопка миші -> Paste): ").strip()
20
+
21
+ try:
22
+ genai.configure(api_key=api_key)
23
+ return True
24
+ except Exception as e:
25
+ print(f"Error configuring Gemini: {e}")
26
+ return False
27
+
28
+ def load_data():
29
+ """Завантажує скрипт і будує граф"""
30
+ script_file = "sales_script_learned.json" if os.path.exists("sales_script_learned.json") else "sales_script.json"
31
+
32
+ with open(script_file, "r", encoding="utf-8") as f:
33
+ data = json.load(f)
34
+
35
+ nodes = data["nodes"]
36
+ edges = data["edges"]
37
+
38
+ node_to_id = {name: i for i, name in enumerate(nodes.keys())}
39
+ id_to_node = {i: name for i, name in enumerate(nodes.keys())}
40
+
41
+ graph = Graph(len(nodes), directed=True)
42
+
43
+ for edge in edges:
44
+ u, v = edge["from"], edge["to"]
45
+ if u in node_to_id and v in node_to_id:
46
+ graph.add_edge(node_to_id[u], node_to_id[v], edge["weight"])
47
+
48
+ return graph, node_to_id, id_to_node, nodes
49
+
50
+ def analyze_intent(model, user_input, current_step_text):
51
+ """
52
+ Визначає наміри клієнта (MOVE або STAY).
53
+ """
54
+ prompt = f"""
55
+ ROLE: Sales Logic Engine.
56
+ CONTEXT:
57
+ Bot said: "{current_step_text}"
58
+ User said: "{user_input}"
59
+
60
+ TASK: Determine if the user allows moving forward.
61
+ RULES:
62
+ - Agreement / Positive answer / Neutral info -> RETURN 'MOVE'
63
+ - Objection / Question / Confusion / Anger -> RETURN 'STAY'
64
+ - "Stop" / "Bye" -> RETURN 'EXIT'
65
+
66
+ OUTPUT: Just one word: MOVE, STAY, or EXIT.
67
+ """
68
+ try:
69
+ # Використовуємо саме твою модель
70
+ response = model.generate_content(prompt)
71
+ decision = response.text.strip().upper()
72
+
73
+ if "EXIT" in decision: return "EXIT"
74
+ if "MOVE" in decision: return "MOVE"
75
+ return "STAY"
76
+ except Exception as e:
77
+ print(f"[API Error on Intent: {e}]")
78
+ return "STAY"
79
+
80
+ def generate_smart_response(model, context, user_input, intent):
81
+ """Генерує відповідь"""
82
+ if intent == "STAY":
83
+ prompt = f"""
84
+ Role: Polite Sales Assistant.
85
+ Context: You are at step "{context}". User objected: "{user_input}".
86
+ Task: Handle the objection politely. Do NOT move to the next step.
87
+ Language: Ukrainian.
88
+ """
89
+ else:
90
+ prompt = f"""
91
+ Role: Sales Assistant.
92
+ Goal: Transition to: "{context}". User said: "{user_input}".
93
+ Task: Create a natural bridge phrase.
94
+ Language: Ukrainian.
95
+ """
96
+
97
+ try:
98
+ response = model.generate_content(prompt)
99
+ return response.text.strip()
100
+ except Exception as e:
101
+ return f"[API Error on Generation: {e}]"
102
+
103
+ def main():
104
+ if not configure_genai(): return
105
+
106
+ print(f"\n[INFO] Connecting to model: {MODEL_NAME}...")
107
+ try:
108
+ model = genai.GenerativeModel(MODEL_NAME)
109
+ except Exception as e:
110
+ print(f"[CRITICAL ERROR] Could not initialize {MODEL_NAME}: {e}")
111
+ return
112
+
113
+ try:
114
+ graph, node_to_id, id_to_node, node_texts = load_data()
115
+ except FileNotFoundError:
116
+ print("Помилка: Не знайдено sales_script.json")
117
+ return
118
+
119
+ current_node = "start"
120
+
121
+ print("\n" + "="*50)
122
+ print(f"🚀 SellMe Smart Bot ({MODEL_NAME})")
123
+ print("="*50 + "\n")
124
+
125
+ print(f"Bot: {node_texts[current_node]}")
126
+
127
+ while True:
128
+ user_input = input("\nYou: ").strip()
129
+ if not user_input: continue
130
+
131
+ # 1. АНАЛІЗ
132
+ print(f"... ({MODEL_NAME} думає) ...")
133
+ intent = analyze_intent(model, user_input, node_texts[current_node])
134
+
135
+ if intent == "EXIT":
136
+ print("Bot: До побачення!")
137
+ break
138
+
139
+ elif intent == "STAY":
140
+ print(f" [🛑 Логіка: Заперечення -> Стоїмо на '{current_node}']")
141
+ response = generate_smart_response(model, node_texts[current_node], user_input, "STAY")
142
+ print(f"Bot: {response}")
143
+
144
+ elif intent == "MOVE":
145
+ print(f" [✅ Логіка: Згода -> Рухаємось далі]")
146
+
147
+ curr_id = node_to_id[current_node]
148
+ best_next = None
149
+ min_w = float('inf')
150
+
151
+ for neighbor, weight in graph.adj_list[curr_id]:
152
+ if weight < min_w:
153
+ min_w = weight
154
+ best_next = neighbor
155
+
156
+ if best_next is None:
157
+ print("Bot: Дякую за розмову!")
158
+ break
159
+
160
+ current_node = id_to_node[best_next]
161
+ response = generate_smart_response(model, node_texts[current_node], user_input, "MOVE")
162
+ print(f"Bot: {response}")
163
+
164
+ if current_node in ["close_deal", "exit_bad"]:
165
+ break
166
+
167
+ if __name__ == "__main__":
168
+ main()