DeepCoreB4 commited on
Commit
a03306c
·
verified ·
1 Parent(s): 4652745

Upload tools.py

Browse files
Files changed (1) hide show
  1. tools.py +526 -538
tools.py CHANGED
@@ -1,538 +1,526 @@
1
- """
2
- Elite Agent Tools – Alle Function Tools für den Webstark KI-Agenten.
3
- Modular aufgebaut, damit agent.py schlank bleibt.
4
- """
5
- import os
6
- import json
7
- import logging
8
- import aiohttp
9
- from datetime import datetime
10
- from livekit.agents import RunContext, function_tool
11
- from livekit.agents.llm import ToolError
12
-
13
- logger = logging.getLogger("livekit-agent")
14
-
15
-
16
- # ============================================================
17
- # TOOL 1: Websuche via Tavily API
18
- # Ermöglicht Elite, aktuelle Infos aus dem Internet zu holen.
19
- # ============================================================
20
- @function_tool()
21
- async def search_web(context: RunContext, query: str) -> str:
22
- """Durchsuche das Internet nach aktuellen Informationen.
23
- Nutze dieses Tool, wenn der Nutzer nach aktuellen Trends,
24
- Webseiten-Infos oder Branchenwissen fragt.
25
-
26
- Args:
27
- query: Die Suchanfrage, z.B. 'Webdesign Trends 2025 Schweiz'
28
- """
29
- tavily_key = os.environ.get("TAVILY_API_KEY")
30
- if not tavily_key:
31
- raise ToolError("Websuche ist momentan nicht verfügbar. Bitte kontaktiere info@webstark.org.")
32
-
33
- try:
34
- from tavily import AsyncTavilyClient
35
- client = AsyncTavilyClient(api_key=tavily_key)
36
- result = await client.search(query=query, max_results=3, search_depth="basic")
37
-
38
- # Ergebnisse für die KI aufbereiten
39
- summary_parts = []
40
- for item in result.get("results", []):
41
- title = item.get("title", "")
42
- content = item.get("content", "")[:300]
43
- url = item.get("url", "")
44
- summary_parts.append(f"**{title}**\n{content}\nQuelle: {url}")
45
-
46
- if not summary_parts:
47
- return "Keine relevanten Ergebnisse gefunden."
48
-
49
- return "\n\n".join(summary_parts)
50
-
51
- except Exception as e:
52
- logger.error(f"Tavily-Sucherror: {e}")
53
- raise ToolError("Die Websuche ist fehlgeschlagen. Bitte versuche es später erneut.")
54
-
55
-
56
- # ============================================================
57
- # TOOL 2: Lead speichern
58
- # Speichert Kontaktdaten von Interessenten als JSON-Datei.
59
- # ============================================================
60
- @function_tool()
61
- async def save_lead(
62
- context: RunContext,
63
- name: str,
64
- email: str,
65
- interest: str,
66
- phone: str = "",
67
- ) -> str:
68
- """Speichere die Kontaktdaten eines interessierten Kunden.
69
- Nutze dieses Tool, wenn der Nutzer seinen Namen und seine E-Mail
70
- hinterlassen möchte oder Interesse an einem Paket bekundet.
71
- Frage aktiv nach Name und E-Mail, bevor du dieses Tool aufrufst.
72
-
73
- Args:
74
- name: Vollständiger Name des Kunden
75
- email: E-Mail-Adresse des Kunden
76
- interest: Woran ist der Kunde interessiert (z.B. 'Starter-Paket', 'SEO-Optimierung')
77
- phone: Telefonnummer (optional)
78
- """
79
- if not name or not email:
80
- raise ToolError("Name und E-Mail sind erforderlich, um den Lead zu speichern.")
81
- if "@" not in email:
82
- raise ToolError("Die E-Mail-Adresse scheint ungültig zu sein. Bitte erneut fragen.")
83
-
84
- # Unterbrechungen verbieten – wir schreiben Daten
85
- context.disallow_interruptions()
86
-
87
- lead_data = {
88
- "name": name,
89
- "email": email,
90
- "phone": phone,
91
- "interest": interest,
92
- "created_at": datetime.utcnow().isoformat(),
93
- }
94
-
95
- # Lead als JSON-Datei speichern
96
- leads_dir = os.path.join(os.path.dirname(__file__), "leads")
97
- os.makedirs(leads_dir, exist_ok=True)
98
-
99
- timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
100
- safe_name = name.replace(" ", "_").lower()[:20]
101
- filename = f"lead_{safe_name}_{timestamp}.json"
102
- filepath = os.path.join(leads_dir, filename)
103
-
104
- with open(filepath, "w", encoding="utf-8") as f:
105
- json.dump(lead_data, f, ensure_ascii=False, indent=2)
106
-
107
- logger.info(f"Lead gespeichert: {filepath}")
108
-
109
- # Benachrichtigungs-E-Mail an Webstark senden (wenn Resend konfiguriert)
110
- await _notify_new_lead(lead_data)
111
-
112
- return f"Kontaktdaten von {name} wurden erfolgreich gespeichert. Wir melden uns in Kürze per E-Mail bei {email}."
113
-
114
-
115
- # ============================================================
116
- # TOOL 3: Kostenvoranschlag berechnen
117
- # ============================================================
118
- @function_tool()
119
- async def calculate_quote(
120
- context: RunContext,
121
- package: str,
122
- extra_pages: int = 0,
123
- seo_hours: int = 0,
124
- chatbot: bool = False,
125
- ) -> str:
126
- """Berechne einen Kostenvoranschlag für ein Webstark-Projekt.
127
- Nutze dieses Tool, wenn der Nutzer nach einem Preis oder Angebot fragt.
128
-
129
- Args:
130
- package: Das gewählte Paket ('starter', 'professional', 'enterprise')
131
- extra_pages: Anzahl zusätzlicher Unterseiten (über die im Paket enthaltenen hinaus)
132
- seo_hours: Gewünschte SEO-Optimierungsstunden
133
- chatbot: Ob ein KI-Chatbot gewünscht ist (im Starter bereits enthalten)
134
- """
135
- # Webstark Preisliste (Stand: webstark.org)
136
- packages = {
137
- "starter": {
138
- "name": "Starter (AI-Enhanced)",
139
- "base_price": 890,
140
- "included_pages": 1,
141
- "includes_chatbot": True,
142
- "description": "KI-generiertes Design, Automatisches Basis-SEO, Responsive One-Page, Chatbot-Integration (Basis)"
143
- },
144
- "professional": {
145
- "name": "Professional (AI-Powered)",
146
- "base_price": 1490,
147
- "included_pages": 5,
148
- "includes_chatbot": True,
149
- "description": "Alles aus Starter, Content-Automation Engine, Predictive Analytics, A/B-Testing AI, Erweiterter KI-Support"
150
- },
151
- "enterprise": {
152
- "name": "Enterprise (AI-First)",
153
- "base_price": 0,
154
- "included_pages": 0,
155
- "includes_chatbot": True,
156
- "is_custom": True,
157
- "description": "Custom AI-Workflows, Dedicated AI-Team, 24/7 Priority Support, On-site Workshops"
158
- }
159
- }
160
-
161
- EXTRA_PAGE_PRICE = 200
162
- SEO_HOUR_PRICE = 120
163
- CHATBOT_ADDON_PRICE = 350
164
-
165
- pkg_key = package.lower().strip()
166
- if pkg_key not in packages:
167
- return (
168
- f"Das Paket '{package}' ist nicht verfügbar. "
169
- f"Verfügbare Pakete: Starter (890 CHF), Professional (1.490 CHF), Enterprise (Individuell)."
170
- )
171
-
172
- pkg = packages[pkg_key]
173
-
174
- # Enterprise = individuell
175
- if pkg.get("is_custom"):
176
- return (
177
- f"Das {pkg['name']}-Paket ist massgeschneidert und wird individuell kalkuliert.\n"
178
- f"Enthält: {pkg['description']}\n\n"
179
- f"Bitte kontaktiere uns unter info@webstark.org oder hinterlasse deine Kontaktdaten."
180
- )
181
-
182
- total = pkg["base_price"]
183
- breakdown = [f"{pkg['name']}: {pkg['base_price']} CHF"]
184
-
185
- if extra_pages > 0:
186
- page_cost = extra_pages * EXTRA_PAGE_PRICE
187
- total += page_cost
188
- breakdown.append(f"{extra_pages} Zusatzseiten: {page_cost} CHF")
189
-
190
- if seo_hours > 0:
191
- seo_cost = seo_hours * SEO_HOUR_PRICE
192
- total += seo_cost
193
- breakdown.append(f"{seo_hours} SEO-Stunden: {seo_cost} CHF")
194
-
195
- if chatbot and not pkg["includes_chatbot"]:
196
- total += CHATBOT_ADDON_PRICE
197
- breakdown.append(f"KI-Chatbot Add-on: {CHATBOT_ADDON_PRICE} CHF")
198
-
199
- result = f"Kostenvoranschlag für {pkg['name']}:\n"
200
- result += "\n".join(f" • {item}" for item in breakdown)
201
- result += f"\n\nGesamtpreis: {total} CHF (zzgl. MwSt.)"
202
- result += f"\n\nInklusive: {pkg['description']}"
203
-
204
- return result
205
-
206
-
207
- # ============================================================
208
- # TOOL 4: E-Mail senden via Resend API
209
- # Elite kann Zusammenfassungen oder Angebote per E-Mail senden.
210
- # ============================================================
211
- @function_tool()
212
- async def send_email(
213
- context: RunContext,
214
- to_email: str,
215
- message: str,
216
- subject: str = "Zusammenfassung von Webstark Elite",
217
- ) -> str:
218
- """Sende eine E-Mail an den Kunden oder an Webstark.
219
- Nutze dieses Tool, um dem Kunden eine Zusammenfassung, ein Angebot
220
- oder wichtige Infos per E-Mail zu schicken.
221
- Frage den Kunden vorher um Erlaubnis, bevor du eine E-Mail sendest.
222
-
223
- Args:
224
- to_email: Empfänger E-Mail-Adresse
225
- subject: Betreff der E-Mail
226
- message: Inhalt der E-Mail (Klartext)
227
- """
228
- resend_key = os.environ.get("RESEND_API_KEY")
229
- if not resend_key:
230
- raise ToolError("E-Mail-Versand ist momentan nicht konfiguriert. Bitte wende dich an info@webstark.org.")
231
-
232
- if "@" not in to_email:
233
- raise ToolError("Die E-Mail-Adresse scheint ungültig zu sein.")
234
-
235
- # Unterbrechungen verbieten – E-Mail wird gesendet
236
- context.disallow_interruptions()
237
-
238
- # HTML-formatierte E-Mail erstellen
239
- html_body = f"""
240
- <div style="font-family: -apple-system, sans-serif; max-width: 600px; margin: 0 auto; padding: 30px;">
241
- <div style="text-align: center; margin-bottom: 30px;">
242
- <h1 style="color: #ff0080; font-size: 24px; margin: 0;">Webstark</h1>
243
- <p style="color: #888; font-size: 12px; margin: 5px 0 0;">Powered by Elite KI</p>
244
- </div>
245
- <div style="background: #f9f9f9; border-radius: 12px; padding: 24px; margin-bottom: 20px;">
246
- <p style="color: #333; line-height: 1.6; white-space: pre-wrap;">{message}</p>
247
- </div>
248
- <div style="text-align: center; color: #999; font-size: 11px;">
249
- <p>Diese E-Mail wurde von Elite gesendet, dem KI-Agenten von Webstark.</p>
250
- <p><a href="https://webstark.org" style="color: #ff0080;">webstark.org</a></p>
251
- </div>
252
- </div>
253
- """
254
-
255
- resend_from_name = os.environ.get("RESEND_FROM_NAME", "Elite")
256
- resend_from_email = os.environ.get("RESEND_FROM_EMAIL", "elite@webstark.org")
257
-
258
- try:
259
- async with aiohttp.ClientSession() as session:
260
- async with session.post(
261
- "https://api.resend.com/emails",
262
- headers={
263
- "Authorization": f"Bearer {resend_key}",
264
- "Content-Type": "application/json",
265
- "Accept-Encoding": "identity",
266
- },
267
- json={
268
- "from": f"{resend_from_name} <{resend_from_email}>",
269
- "to": [to_email],
270
- "subject": subject,
271
- "html": html_body,
272
- },
273
- timeout=aiohttp.ClientTimeout(total=10),
274
- ) as resp:
275
- if resp.status in (200, 201):
276
- logger.info(f"E-Mail gesendet an {to_email}: {subject}")
277
- return f"E-Mail wurde erfolgreich an {to_email} gesendet."
278
- else:
279
- error_text = await resp.text()
280
- logger.error(f"Resend-Fehler: {resp.status} – {error_text}")
281
- raise ToolError("E-Mail konnte nicht gesendet werden. Bitte versuche es später.")
282
- except aiohttp.ClientError as e:
283
- logger.error(f"HTTP-Fehler beim E-Mail-Versand: {e}")
284
- raise ToolError("E-Mail-Versand fehlgeschlagen. Netzwerkfehler.")
285
-
286
-
287
- # ============================================================
288
- # TOOL 5: Termin-Link vorschlagen
289
- # Gibt dem Kunden einen direkten Buchungslink.
290
- # ============================================================
291
- @function_tool()
292
- async def suggest_appointment(
293
- context: RunContext,
294
- topic: str,
295
- ) -> str:
296
- """Schlage dem Kunden einen Beratungstermin vor.
297
- Nutze dieses Tool, wenn der Kunde ein tiefergehendes Gespräch möchte,
298
- eine komplexe Anfrage hat, oder du das Enterprise-Paket empfiehlst.
299
-
300
- Args:
301
- topic: Worum geht es im Termin (z.B. 'SEO-Beratung', 'Webdesign-Projekt', 'Enterprise-Angebot')
302
- """
303
- # Termin-Link (anpassbar – Cal.com, Calendly, etc.)
304
- booking_url = os.environ.get("BOOKING_URL", "https://webstark.org/kontakt")
305
-
306
- return (
307
- f"Gerne! Für eine ausführliche Beratung zum Thema '{topic}' "
308
- f"kannst du direkt einen Termin buchen:\n\n"
309
- f"📅 Termin buchen: {booking_url}\n\n"
310
- f"Alternativ erreichst du uns auch unter info@webstark.org."
311
- )
312
-
313
-
314
- # ============================================================
315
- # TOOL 6: FAQ-Wissensbasis durchsuchen
316
- # Lokale Wissensbasis für häufige Fragen (ohne API-Kosten).
317
- # ============================================================
318
-
319
- # FAQ-Datenbank – schnelle Antworten ohne LLM-Kosten
320
- FAQ_DATABASE = [
321
- {
322
- "keywords": ["dauer", "wie lange", "zeitraum", "fertig"],
323
- "question": "Wie lange dauert ein Website-Projekt?",
324
- "answer": "Ein Starter-Projekt ist in ca. 1-2 Wochen fertig. Professional-Projekte dauern 3-5 Wochen, Enterprise-Projekte werden individuell geplant."
325
- },
326
- {
327
- "keywords": ["zahlung", "bezahlen", "rechnung", "anzahlung"],
328
- "question": "Wie läuft die Zahlung?",
329
- "answer": "Wir arbeiten mit 50% Anzahlung bei Projektstart und 50% bei Fertigstellung. Ratenzahlung ist bei grösseren Projekten möglich."
330
- },
331
- {
332
- "keywords": ["hosting", "server", "domain", "online"],
333
- "question": "Ist Hosting inklusive?",
334
- "answer": "Hosting wird separat berechnet. Wir empfehlen Vercel (kostenlos für kleine Projekte) oder managed Hosting ab 15 CHF/Monat. Die Domain-Registrierung können wir ebenfalls übernehmen."
335
- },
336
- {
337
- "keywords": ["änderung", "revision", "korrektur", "anpassen"],
338
- "question": "Wie viele Änderungen sind inklusive?",
339
- "answer": "Im Starter-Paket sind 2 Korrekturschleifen inklusive, im Professional-Paket 5. Zusätzliche Änderungen werden zum Stundensatz von 120 CHF berechnet."
340
- },
341
- {
342
- "keywords": ["garantie", "geld zurück", "zufriedenheit", "unzufrieden"],
343
- "question": "Gibt es eine Zufriedenheitsgarantie?",
344
- "answer": "Ja! Wir bieten eine 30-Tage Geld-zurück-Garantie. Wenn du nicht zufrieden bist, erstatten wir den vollen Betrag."
345
- },
346
- {
347
- "keywords": ["seo", "google", "ranking", "suchmaschine", "auffindbar"],
348
- "question": "Was beinhaltet die SEO-Optimierung?",
349
- "answer": "Basis-SEO (im Starter inklusive) umfasst: Meta-Tags, Seitengeschwindigkeit, Mobile-Optimierung und strukturierte Daten. Erweitertes SEO (Professional) beinhaltet zusätzlich Keyword-Analyse, Content-Strategie und monatliches Reporting."
350
- },
351
- {
352
- "keywords": ["chatbot", "ki", "bot", "automatisch", "chat"],
353
- "question": "Was kann der Chatbot?",
354
- "answer": "Der Basis-Chatbot (im Starter) beantwortet häufige Fragen automatisch. Der erweiterte KI-Support (Professional) lernt aus Gesprächen und kann komplexere Anfragen bearbeiten."
355
- },
356
- {
357
- "keywords": ["kontakt", "erreichen", "email", "telefon", "support"],
358
- "question": "Wie erreiche ich Webstark?",
359
- "answer": "Du erreichst uns per E-Mail unter info@webstark.org oder über den Live-Chat auf webstark.org. Telefon-Support ist aktuell nicht verfügbar."
360
- },
361
- ]
362
-
363
-
364
- @function_tool()
365
- async def lookup_faq(context: RunContext, question: str) -> str:
366
- """Suche in der Webstark FAQ-Wissensbasis nach einer Antwort.
367
- Nutze dieses Tool ZUERST, bevor du search_web verwendest.
368
- Es enthält häufig gestellte Fragen zu Preisen, Abläufen und Services.
369
-
370
- Args:
371
- question: Die Frage des Kunden, z.B. 'Wie lange dauert ein Projekt?'
372
- """
373
- question_lower = question.lower()
374
-
375
- # Relevanz-Score berechnen basierend auf Keyword-Matches
376
- best_match = None
377
- best_score = 0
378
-
379
- for faq in FAQ_DATABASE:
380
- score = sum(1 for kw in faq["keywords"] if kw in question_lower)
381
- if score > best_score:
382
- best_score = score
383
- best_match = faq
384
-
385
- if best_match and best_score > 0:
386
- return f"FAQ: {best_match['question']}\n\n{best_match['answer']}"
387
-
388
- return "Keine passende FAQ gefunden. Nutze search_web für eine Internet-Recherche oder verweise auf info@webstark.org."
389
-
390
-
391
- # ============================================================
392
- # TOOL 7: Gesprächs-Zusammenfassung erstellen
393
- # Erstellt eine strukturierte Zusammenfassung am Ende des Gesprächs.
394
- # ============================================================
395
- @function_tool()
396
- async def create_conversation_summary(
397
- context: RunContext,
398
- customer_name: str,
399
- topics_discussed: str,
400
- action_items: str,
401
- interest_level: str = "mittel",
402
- ) -> str:
403
- """Erstelle eine Zusammenfassung des Gesprächs.
404
- Nutze dieses Tool am Ende eines Gesprächs oder wenn der Kunde
405
- sich verabschiedet, um alle wichtigen Punkte festzuhalten.
406
-
407
- Args:
408
- customer_name: Name des Kunden (oder 'Unbekannt')
409
- topics_discussed: Komma-getrennte Liste der besprochenen Themen
410
- action_items: Nächste Schritte oder offene Aufgaben
411
- interest_level: Wie interessiert ist der Kunde? ('hoch', 'mittel', 'niedrig')
412
- """
413
- context.disallow_interruptions()
414
-
415
- summary = {
416
- "customer_name": customer_name,
417
- "timestamp": datetime.utcnow().isoformat(),
418
- "topics": topics_discussed,
419
- "action_items": action_items,
420
- "interest_level": interest_level,
421
- }
422
-
423
- # Zusammenfassung speichern
424
- summaries_dir = os.path.join(os.path.dirname(__file__), "summaries")
425
- os.makedirs(summaries_dir, exist_ok=True)
426
-
427
- timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
428
- filename = f"summary_{timestamp}.json"
429
- filepath = os.path.join(summaries_dir, filename)
430
-
431
- with open(filepath, "w", encoding="utf-8") as f:
432
- json.dump(summary, f, ensure_ascii=False, indent=2)
433
-
434
- logger.info(f"Gesprächs-Zusammenfassung gespeichert: {filepath}")
435
-
436
- # Falls Resend konfiguriert, Zusammenfassung an Webstark senden
437
- await _notify_summary(summary)
438
-
439
- return (
440
- f"Zusammenfassung gespeichert!\n"
441
- f"Kunde: {customer_name}\n"
442
- f"Themen: {topics_discussed}\n"
443
- f"Nächste Schritte: {action_items}\n"
444
- f"Interesse: {interest_level}"
445
- )
446
-
447
-
448
- # ============================================================
449
- # INTERNE HILFSFUNKTIONEN (nicht als Tool exponiert)
450
- # ============================================================
451
- async def _notify_new_lead(lead_data: dict) -> None:
452
- """Sendet eine Benachrichtigungs-E-Mail an Webstark bei neuem Lead."""
453
- resend_key = os.environ.get("RESEND_API_KEY")
454
- notify_email = os.environ.get("NOTIFY_EMAIL", "info@webstark.org")
455
- if not resend_key:
456
- logger.info("Kein RESEND_API_KEY – Lead-Benachrichtigung übersprungen.")
457
- return
458
-
459
- resend_from_name = os.environ.get("RESEND_FROM_NAME", "Elite")
460
- resend_from_email = os.environ.get("RESEND_FROM_EMAIL", "elite@webstark.org")
461
-
462
- try:
463
- async with aiohttp.ClientSession() as session:
464
- await session.post(
465
- "https://api.resend.com/emails",
466
- headers={
467
- "Authorization": f"Bearer {resend_key}",
468
- "Content-Type": "application/json",
469
- "Accept-Encoding": "identity",
470
- },
471
- json={
472
- "from": f"{resend_from_name} <{resend_from_email}>",
473
- "to": [notify_email],
474
- "subject": f"🔥 Neuer Lead: {lead_data['name']} – {lead_data['interest']}",
475
- "html": f"""
476
- <h2>Neuer Lead von Elite</h2>
477
- <p><b>Name:</b> {lead_data['name']}</p>
478
- <p><b>E-Mail:</b> {lead_data['email']}</p>
479
- <p><b>Telefon:</b> {lead_data.get('phone', '-')}</p>
480
- <p><b>Interesse:</b> {lead_data['interest']}</p>
481
- <p><b>Zeitpunkt:</b> {lead_data['created_at']}</p>
482
- """,
483
- },
484
- timeout=aiohttp.ClientTimeout(total=10),
485
- )
486
- logger.info(f"Lead-Benachrichtigung gesendet an {notify_email}")
487
- except Exception as e:
488
- logger.warning(f"Lead-Benachrichtigung fehlgeschlagen: {e}")
489
-
490
-
491
- async def _notify_summary(summary: dict) -> None:
492
- """Sendet eine Gesprächs-Zusammenfassung per E-Mail an Webstark."""
493
- resend_key = os.environ.get("RESEND_API_KEY")
494
- notify_email = os.environ.get("NOTIFY_EMAIL", "info@webstark.org")
495
- if not resend_key:
496
- return
497
-
498
- resend_from_name = os.environ.get("RESEND_FROM_NAME", "Elite")
499
- resend_from_email = os.environ.get("RESEND_FROM_EMAIL", "elite@webstark.org")
500
-
501
- try:
502
- async with aiohttp.ClientSession() as session:
503
- await session.post(
504
- "https://api.resend.com/emails",
505
- headers={
506
- "Authorization": f"Bearer {resend_key}",
507
- "Content-Type": "application/json",
508
- "Accept-Encoding": "identity",
509
- },
510
- json={
511
- "from": f"{resend_from_name} <{resend_from_email}>",
512
- "to": [notify_email],
513
- "subject": f"📝 Gesprächs-Zusammenfassung: {summary['customer_name']}",
514
- "html": f"""
515
- <h2>Gesprächs-Zusammenfassung</h2>
516
- <p><b>Kunde:</b> {summary['customer_name']}</p>
517
- <p><b>Themen:</b> {summary['topics']}</p>
518
- <p><b>Nächste Schritte:</b> {summary['action_items']}</p>
519
- <p><b>Interesse:</b> {summary['interest_level']}</p>
520
- <p><b>Zeitpunkt:</b> {summary['timestamp']}</p>
521
- """,
522
- },
523
- timeout=aiohttp.ClientTimeout(total=10),
524
- )
525
- except Exception as e:
526
- logger.warning(f"Zusammenfassungs-Benachrichtigung fehlgeschlagen: {e}")
527
-
528
-
529
- # Alle Tools als Liste exportieren (wird in agent.py importiert)
530
- ALL_TOOLS = [
531
- search_web,
532
- save_lead,
533
- calculate_quote,
534
- send_email,
535
- suggest_appointment,
536
- lookup_faq,
537
- create_conversation_summary,
538
- ]
 
1
+ """
2
+ Elite Agent Tools – Alle Function Tools für den Webstark KI-Agenten.
3
+ Modular aufgebaut, damit agent.py schlank bleibt.
4
+ """
5
+ import os
6
+ import json
7
+ import logging
8
+ import aiohttp
9
+ from datetime import datetime
10
+ from livekit.agents import RunContext, function_tool
11
+ from livekit.agents.llm import ToolError
12
+
13
+ logger = logging.getLogger("livekit-agent")
14
+
15
+
16
+ # ============================================================
17
+ # TOOL 1: Websuche via Tavily API
18
+ # Ermöglicht Elite, aktuelle Infos aus dem Internet zu holen.
19
+ # ============================================================
20
+ @function_tool()
21
+ async def search_web(context: RunContext, query: str) -> str:
22
+ """Durchsuche das Internet nach aktuellen Informationen.
23
+ Nutze dieses Tool, wenn der Nutzer nach aktuellen Trends,
24
+ Webseiten-Infos oder Branchenwissen fragt.
25
+
26
+ Args:
27
+ query: Die Suchanfrage, z.B. 'Webdesign Trends 2025 Schweiz'
28
+ """
29
+ tavily_key = os.environ.get("TAVILY_API_KEY")
30
+ if not tavily_key:
31
+ raise ToolError("Websuche ist momentan nicht verfügbar. Bitte kontaktiere info@webstark.org.")
32
+
33
+ try:
34
+ from tavily import AsyncTavilyClient
35
+ client = AsyncTavilyClient(api_key=tavily_key)
36
+ result = await client.search(query=query, max_results=3, search_depth="basic")
37
+
38
+ # Ergebnisse für die KI aufbereiten
39
+ summary_parts = []
40
+ for item in result.get("results", []):
41
+ title = item.get("title", "")
42
+ content = item.get("content", "")[:300]
43
+ url = item.get("url", "")
44
+ summary_parts.append(f"**{title}**\n{content}\nQuelle: {url}")
45
+
46
+ if not summary_parts:
47
+ return "Keine relevanten Ergebnisse gefunden."
48
+
49
+ return "\n\n".join(summary_parts)
50
+
51
+ except Exception as e:
52
+ logger.error(f"Tavily-Sucherror: {e}")
53
+ raise ToolError("Die Websuche ist fehlgeschlagen. Bitte versuche es später erneut.")
54
+
55
+
56
+ # ============================================================
57
+ # TOOL 2: Lead speichern
58
+ # Speichert Kontaktdaten von Interessenten als JSON-Datei.
59
+ # ============================================================
60
+ @function_tool()
61
+ async def save_lead(
62
+ context: RunContext,
63
+ name: str,
64
+ email: str,
65
+ interest: str,
66
+ phone: str = "",
67
+ ) -> str:
68
+ """Speichere die Kontaktdaten eines interessierten Kunden.
69
+ Nutze dieses Tool, wenn der Nutzer seinen Namen und seine E-Mail
70
+ hinterlassen möchte oder Interesse an einem Paket bekundet.
71
+ Frage aktiv nach Name und E-Mail, bevor du dieses Tool aufrufst.
72
+
73
+ Args:
74
+ name: Vollständiger Name des Kunden
75
+ email: E-Mail-Adresse des Kunden
76
+ interest: Woran ist der Kunde interessiert (z.B. 'Starter-Paket', 'SEO-Optimierung')
77
+ phone: Telefonnummer (optional)
78
+ """
79
+ if not name or not email:
80
+ raise ToolError("Name und E-Mail sind erforderlich, um den Lead zu speichern.")
81
+ if "@" not in email:
82
+ raise ToolError("Die E-Mail-Adresse scheint ungültig zu sein. Bitte erneut fragen.")
83
+
84
+ # Unterbrechungen verbieten – wir schreiben Daten
85
+ context.disallow_interruptions()
86
+
87
+ lead_data = {
88
+ "name": name,
89
+ "email": email,
90
+ "phone": phone,
91
+ "interest": interest,
92
+ "created_at": datetime.utcnow().isoformat(),
93
+ }
94
+
95
+ # Lead als JSON-Datei speichern
96
+ leads_dir = os.path.join(os.path.dirname(__file__), "leads")
97
+ os.makedirs(leads_dir, exist_ok=True)
98
+
99
+ timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
100
+ safe_name = name.replace(" ", "_").lower()[:20]
101
+ filename = f"lead_{safe_name}_{timestamp}.json"
102
+ filepath = os.path.join(leads_dir, filename)
103
+
104
+ with open(filepath, "w", encoding="utf-8") as f:
105
+ json.dump(lead_data, f, ensure_ascii=False, indent=2)
106
+
107
+ logger.info(f"Lead gespeichert: {filepath}")
108
+
109
+ # Benachrichtigungs-E-Mail an Webstark senden (wenn Resend konfiguriert)
110
+ await _notify_new_lead(lead_data)
111
+
112
+ return f"Kontaktdaten von {name} wurden erfolgreich gespeichert. Wir melden uns in Kürze per E-Mail bei {email}."
113
+
114
+
115
+ # ============================================================
116
+ # TOOL 3: Kostenvoranschlag berechnen
117
+ # ============================================================
118
+ @function_tool()
119
+ async def calculate_quote(
120
+ context: RunContext,
121
+ package: str,
122
+ extra_pages: int = 0,
123
+ seo_hours: int = 0,
124
+ chatbot: bool = False,
125
+ ) -> str:
126
+ """Berechne einen Kostenvoranschlag für ein Webstark-Projekt.
127
+ Nutze dieses Tool, wenn der Nutzer nach einem Preis oder Angebot fragt.
128
+
129
+ Args:
130
+ package: Das gewählte Paket ('starter', 'professional', 'enterprise')
131
+ extra_pages: Anzahl zusätzlicher Unterseiten (über die im Paket enthaltenen hinaus)
132
+ seo_hours: Gewünschte SEO-Optimierungsstunden
133
+ chatbot: Ob ein KI-Chatbot gewünscht ist (im Starter bereits enthalten)
134
+ """
135
+ # Webstark Preisliste (Stand: webstark.org)
136
+ packages = {
137
+ "starter": {
138
+ "name": "Starter (AI-Enhanced)",
139
+ "base_price": 890,
140
+ "included_pages": 1,
141
+ "includes_chatbot": True,
142
+ "description": "KI-generiertes Design, Automatisches Basis-SEO, Responsive One-Page, Chatbot-Integration (Basis)"
143
+ },
144
+ "professional": {
145
+ "name": "Professional (AI-Powered)",
146
+ "base_price": 1490,
147
+ "included_pages": 5,
148
+ "includes_chatbot": True,
149
+ "description": "Alles aus Starter, Content-Automation Engine, Predictive Analytics, A/B-Testing AI, Erweiterter KI-Support"
150
+ },
151
+ "enterprise": {
152
+ "name": "Enterprise (AI-First)",
153
+ "base_price": 0,
154
+ "included_pages": 0,
155
+ "includes_chatbot": True,
156
+ "is_custom": True,
157
+ "description": "Custom AI-Workflows, Dedicated AI-Team, 24/7 Priority Support, On-site Workshops"
158
+ }
159
+ }
160
+
161
+ EXTRA_PAGE_PRICE = 200
162
+ SEO_HOUR_PRICE = 120
163
+ CHATBOT_ADDON_PRICE = 350
164
+
165
+ pkg_key = package.lower().strip()
166
+ if pkg_key not in packages:
167
+ return (
168
+ f"Das Paket '{package}' ist nicht verfügbar. "
169
+ f"Verfügbare Pakete: Starter (890 CHF), Professional (1.490 CHF), Enterprise (Individuell)."
170
+ )
171
+
172
+ pkg = packages[pkg_key]
173
+
174
+ # Enterprise = individuell
175
+ if pkg.get("is_custom"):
176
+ return (
177
+ f"Das {pkg['name']}-Paket ist massgeschneidert und wird individuell kalkuliert.\n"
178
+ f"Enthält: {pkg['description']}\n\n"
179
+ f"Bitte kontaktiere uns unter info@webstark.org oder hinterlasse deine Kontaktdaten."
180
+ )
181
+
182
+ total = pkg["base_price"]
183
+ breakdown = [f"{pkg['name']}: {pkg['base_price']} CHF"]
184
+
185
+ if extra_pages > 0:
186
+ page_cost = extra_pages * EXTRA_PAGE_PRICE
187
+ total += page_cost
188
+ breakdown.append(f"{extra_pages} Zusatzseiten: {page_cost} CHF")
189
+
190
+ if seo_hours > 0:
191
+ seo_cost = seo_hours * SEO_HOUR_PRICE
192
+ total += seo_cost
193
+ breakdown.append(f"{seo_hours} SEO-Stunden: {seo_cost} CHF")
194
+
195
+ if chatbot and not pkg["includes_chatbot"]:
196
+ total += CHATBOT_ADDON_PRICE
197
+ breakdown.append(f"KI-Chatbot Add-on: {CHATBOT_ADDON_PRICE} CHF")
198
+
199
+ result = f"Kostenvoranschlag für {pkg['name']}:\n"
200
+ result += "\n".join(f" • {item}" for item in breakdown)
201
+ result += f"\n\nGesamtpreis: {total} CHF (zzgl. MwSt.)"
202
+ result += f"\n\nInklusive: {pkg['description']}"
203
+
204
+ return result
205
+
206
+
207
+ # ============================================================
208
+ # TOOL 4: E-Mail senden via Resend API
209
+ # Elite kann Zusammenfassungen oder Angebote per E-Mail senden.
210
+ # ============================================================
211
+ @function_tool()
212
+ async def send_email(
213
+ context: RunContext,
214
+ to_email: str,
215
+ subject: str,
216
+ message: str,
217
+ ) -> str:
218
+ """Sende eine E-Mail an den Kunden oder an Webstark.
219
+ Nutze dieses Tool, um dem Kunden eine Zusammenfassung, ein Angebot
220
+ oder wichtige Infos per E-Mail zu schicken.
221
+ Frage den Kunden vorher um Erlaubnis, bevor du eine E-Mail sendest.
222
+
223
+ Args:
224
+ to_email: Empfänger E-Mail-Adresse
225
+ subject: Betreff der E-Mail
226
+ message: Inhalt der E-Mail (Klartext)
227
+ """
228
+ resend_key = os.environ.get("RESEND_API_KEY")
229
+ if not resend_key:
230
+ raise ToolError("E-Mail-Versand ist momentan nicht konfiguriert. Bitte wende dich an info@webstark.org.")
231
+
232
+ if "@" not in to_email:
233
+ raise ToolError("Die E-Mail-Adresse scheint ungültig zu sein.")
234
+
235
+ # Unterbrechungen verbieten – E-Mail wird gesendet
236
+ context.disallow_interruptions()
237
+
238
+ # HTML-formatierte E-Mail erstellen
239
+ html_body = f"""
240
+ <div style="font-family: -apple-system, sans-serif; max-width: 600px; margin: 0 auto; padding: 30px;">
241
+ <div style="text-align: center; margin-bottom: 30px;">
242
+ <h1 style="color: #ff0080; font-size: 24px; margin: 0;">Webstark</h1>
243
+ <p style="color: #888; font-size: 12px; margin: 5px 0 0;">Powered by Elite KI</p>
244
+ </div>
245
+ <div style="background: #f9f9f9; border-radius: 12px; padding: 24px; margin-bottom: 20px;">
246
+ <p style="color: #333; line-height: 1.6; white-space: pre-wrap;">{message}</p>
247
+ </div>
248
+ <div style="text-align: center; color: #999; font-size: 11px;">
249
+ <p>Diese E-Mail wurde von Elite gesendet, dem KI-Agenten von Webstark.</p>
250
+ <p><a href="https://webstark.org" style="color: #ff0080;">webstark.org</a></p>
251
+ </div>
252
+ </div>
253
+ """
254
+
255
+ try:
256
+ async with aiohttp.ClientSession() as session:
257
+ async with session.post(
258
+ "https://api.resend.com/emails",
259
+ headers={
260
+ "Authorization": f"Bearer {resend_key}",
261
+ "Content-Type": "application/json",
262
+ },
263
+ json={
264
+ "from": "Elite <elite@webstark.org>",
265
+ "to": [to_email],
266
+ "subject": subject,
267
+ "html": html_body,
268
+ },
269
+ timeout=aiohttp.ClientTimeout(total=10),
270
+ ) as resp:
271
+ if resp.status in (200, 201):
272
+ logger.info(f"E-Mail gesendet an {to_email}: {subject}")
273
+ return f"E-Mail wurde erfolgreich an {to_email} gesendet."
274
+ else:
275
+ error_text = await resp.text()
276
+ logger.error(f"Resend-Fehler: {resp.status} – {error_text}")
277
+ raise ToolError("E-Mail konnte nicht gesendet werden. Bitte versuche es später.")
278
+ except aiohttp.ClientError as e:
279
+ logger.error(f"HTTP-Fehler beim E-Mail-Versand: {e}")
280
+ raise ToolError("E-Mail-Versand fehlgeschlagen. Netzwerkfehler.")
281
+
282
+
283
+ # ============================================================
284
+ # TOOL 5: Termin-Link vorschlagen
285
+ # Gibt dem Kunden einen direkten Buchungslink.
286
+ # ============================================================
287
+ @function_tool()
288
+ async def suggest_appointment(
289
+ context: RunContext,
290
+ topic: str,
291
+ ) -> str:
292
+ """Schlage dem Kunden einen Beratungstermin vor.
293
+ Nutze dieses Tool, wenn der Kunde ein tiefergehendes Gespräch möchte,
294
+ eine komplexe Anfrage hat, oder du das Enterprise-Paket empfiehlst.
295
+
296
+ Args:
297
+ topic: Worum geht es im Termin (z.B. 'SEO-Beratung', 'Webdesign-Projekt', 'Enterprise-Angebot')
298
+ """
299
+ # Termin-Link (anpassbar – Cal.com, Calendly, etc.)
300
+ booking_url = os.environ.get("BOOKING_URL", "https://webstark.org/kontakt")
301
+
302
+ return (
303
+ f"Gerne! Für eine ausführliche Beratung zum Thema '{topic}' "
304
+ f"kannst du direkt einen Termin buchen:\n\n"
305
+ f"📅 Termin buchen: {booking_url}\n\n"
306
+ f"Alternativ erreichst du uns auch unter info@webstark.org."
307
+ )
308
+
309
+
310
+ # ============================================================
311
+ # TOOL 6: FAQ-Wissensbasis durchsuchen
312
+ # Lokale Wissensbasis für häufige Fragen (ohne API-Kosten).
313
+ # ============================================================
314
+
315
+ # FAQ-Datenbank – schnelle Antworten ohne LLM-Kosten
316
+ FAQ_DATABASE = [
317
+ {
318
+ "keywords": ["dauer", "wie lange", "zeitraum", "fertig"],
319
+ "question": "Wie lange dauert ein Website-Projekt?",
320
+ "answer": "Ein Starter-Projekt ist in ca. 1-2 Wochen fertig. Professional-Projekte dauern 3-5 Wochen, Enterprise-Projekte werden individuell geplant."
321
+ },
322
+ {
323
+ "keywords": ["zahlung", "bezahlen", "rechnung", "anzahlung"],
324
+ "question": "Wie läuft die Zahlung?",
325
+ "answer": "Wir arbeiten mit 50% Anzahlung bei Projektstart und 50% bei Fertigstellung. Ratenzahlung ist bei grösseren Projekten möglich."
326
+ },
327
+ {
328
+ "keywords": ["hosting", "server", "domain", "online"],
329
+ "question": "Ist Hosting inklusive?",
330
+ "answer": "Hosting wird separat berechnet. Wir empfehlen Vercel (kostenlos für kleine Projekte) oder managed Hosting ab 15 CHF/Monat. Die Domain-Registrierung können wir ebenfalls übernehmen."
331
+ },
332
+ {
333
+ "keywords": ["änderung", "revision", "korrektur", "anpassen"],
334
+ "question": "Wie viele Änderungen sind inklusive?",
335
+ "answer": "Im Starter-Paket sind 2 Korrekturschleifen inklusive, im Professional-Paket 5. Zusätzliche Änderungen werden zum Stundensatz von 120 CHF berechnet."
336
+ },
337
+ {
338
+ "keywords": ["garantie", "geld zurück", "zufriedenheit", "unzufrieden"],
339
+ "question": "Gibt es eine Zufriedenheitsgarantie?",
340
+ "answer": "Ja! Wir bieten eine 30-Tage Geld-zurück-Garantie. Wenn du nicht zufrieden bist, erstatten wir den vollen Betrag."
341
+ },
342
+ {
343
+ "keywords": ["seo", "google", "ranking", "suchmaschine", "auffindbar"],
344
+ "question": "Was beinhaltet die SEO-Optimierung?",
345
+ "answer": "Basis-SEO (im Starter inklusive) umfasst: Meta-Tags, Seitengeschwindigkeit, Mobile-Optimierung und strukturierte Daten. Erweitertes SEO (Professional) beinhaltet zusätzlich Keyword-Analyse, Content-Strategie und monatliches Reporting."
346
+ },
347
+ {
348
+ "keywords": ["chatbot", "ki", "bot", "automatisch", "chat"],
349
+ "question": "Was kann der Chatbot?",
350
+ "answer": "Der Basis-Chatbot (im Starter) beantwortet häufige Fragen automatisch. Der erweiterte KI-Support (Professional) lernt aus Gesprächen und kann komplexere Anfragen bearbeiten."
351
+ },
352
+ {
353
+ "keywords": ["kontakt", "erreichen", "email", "telefon", "support"],
354
+ "question": "Wie erreiche ich Webstark?",
355
+ "answer": "Du erreichst uns per E-Mail unter info@webstark.org oder über den Live-Chat auf webstark.org. Telefon-Support ist aktuell nicht verfügbar."
356
+ },
357
+ ]
358
+
359
+
360
+ @function_tool()
361
+ async def lookup_faq(context: RunContext, question: str) -> str:
362
+ """Suche in der Webstark FAQ-Wissensbasis nach einer Antwort.
363
+ Nutze dieses Tool ZUERST, bevor du search_web verwendest.
364
+ Es enthält häufig gestellte Fragen zu Preisen, Abläufen und Services.
365
+
366
+ Args:
367
+ question: Die Frage des Kunden, z.B. 'Wie lange dauert ein Projekt?'
368
+ """
369
+ question_lower = question.lower()
370
+
371
+ # Relevanz-Score berechnen basierend auf Keyword-Matches
372
+ best_match = None
373
+ best_score = 0
374
+
375
+ for faq in FAQ_DATABASE:
376
+ score = sum(1 for kw in faq["keywords"] if kw in question_lower)
377
+ if score > best_score:
378
+ best_score = score
379
+ best_match = faq
380
+
381
+ if best_match and best_score > 0:
382
+ return f"FAQ: {best_match['question']}\n\n{best_match['answer']}"
383
+
384
+ return "Keine passende FAQ gefunden. Nutze search_web für eine Internet-Recherche oder verweise auf info@webstark.org."
385
+
386
+
387
+ # ============================================================
388
+ # TOOL 7: Gesprächs-Zusammenfassung erstellen
389
+ # Erstellt eine strukturierte Zusammenfassung am Ende des Gesprächs.
390
+ # ============================================================
391
+ @function_tool()
392
+ async def create_conversation_summary(
393
+ context: RunContext,
394
+ customer_name: str,
395
+ topics_discussed: str,
396
+ action_items: str,
397
+ interest_level: str = "mittel",
398
+ ) -> str:
399
+ """Erstelle eine Zusammenfassung des Gesprächs.
400
+ Nutze dieses Tool am Ende eines Gesprächs oder wenn der Kunde
401
+ sich verabschiedet, um alle wichtigen Punkte festzuhalten.
402
+
403
+ Args:
404
+ customer_name: Name des Kunden (oder 'Unbekannt')
405
+ topics_discussed: Komma-getrennte Liste der besprochenen Themen
406
+ action_items: Nächste Schritte oder offene Aufgaben
407
+ interest_level: Wie interessiert ist der Kunde? ('hoch', 'mittel', 'niedrig')
408
+ """
409
+ context.disallow_interruptions()
410
+
411
+ summary = {
412
+ "customer_name": customer_name,
413
+ "timestamp": datetime.utcnow().isoformat(),
414
+ "topics": topics_discussed,
415
+ "action_items": action_items,
416
+ "interest_level": interest_level,
417
+ }
418
+
419
+ # Zusammenfassung speichern
420
+ summaries_dir = os.path.join(os.path.dirname(__file__), "summaries")
421
+ os.makedirs(summaries_dir, exist_ok=True)
422
+
423
+ timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
424
+ filename = f"summary_{timestamp}.json"
425
+ filepath = os.path.join(summaries_dir, filename)
426
+
427
+ with open(filepath, "w", encoding="utf-8") as f:
428
+ json.dump(summary, f, ensure_ascii=False, indent=2)
429
+
430
+ logger.info(f"Gesprächs-Zusammenfassung gespeichert: {filepath}")
431
+
432
+ # Falls Resend konfiguriert, Zusammenfassung an Webstark senden
433
+ await _notify_summary(summary)
434
+
435
+ return (
436
+ f"Zusammenfassung gespeichert!\n"
437
+ f"Kunde: {customer_name}\n"
438
+ f"Themen: {topics_discussed}\n"
439
+ f"Nächste Schritte: {action_items}\n"
440
+ f"Interesse: {interest_level}"
441
+ )
442
+
443
+
444
+ # ============================================================
445
+ # INTERNE HILFSFUNKTIONEN (nicht als Tool exponiert)
446
+ # ============================================================
447
+ async def _notify_new_lead(lead_data: dict) -> None:
448
+ """Sendet eine Benachrichtigungs-E-Mail an Webstark bei neuem Lead."""
449
+ resend_key = os.environ.get("RESEND_API_KEY")
450
+ notify_email = os.environ.get("NOTIFY_EMAIL", "info@webstark.org")
451
+ if not resend_key:
452
+ logger.info("Kein RESEND_API_KEY – Lead-Benachrichtigung übersprungen.")
453
+ return
454
+
455
+ try:
456
+ async with aiohttp.ClientSession() as session:
457
+ await session.post(
458
+ "https://api.resend.com/emails",
459
+ headers={
460
+ "Authorization": f"Bearer {resend_key}",
461
+ "Content-Type": "application/json",
462
+ },
463
+ json={
464
+ "from": "Elite <elite@webstark.org>",
465
+ "to": [notify_email],
466
+ "subject": f"🔥 Neuer Lead: {lead_data['name']} – {lead_data['interest']}",
467
+ "html": f"""
468
+ <h2>Neuer Lead von Elite</h2>
469
+ <p><b>Name:</b> {lead_data['name']}</p>
470
+ <p><b>E-Mail:</b> {lead_data['email']}</p>
471
+ <p><b>Telefon:</b> {lead_data.get('phone', '-')}</p>
472
+ <p><b>Interesse:</b> {lead_data['interest']}</p>
473
+ <p><b>Zeitpunkt:</b> {lead_data['created_at']}</p>
474
+ """,
475
+ },
476
+ timeout=aiohttp.ClientTimeout(total=10),
477
+ )
478
+ logger.info(f"Lead-Benachrichtigung gesendet an {notify_email}")
479
+ except Exception as e:
480
+ logger.warning(f"Lead-Benachrichtigung fehlgeschlagen: {e}")
481
+
482
+
483
+ async def _notify_summary(summary: dict) -> None:
484
+ """Sendet eine Gesprächs-Zusammenfassung per E-Mail an Webstark."""
485
+ resend_key = os.environ.get("RESEND_API_KEY")
486
+ notify_email = os.environ.get("NOTIFY_EMAIL", "info@webstark.org")
487
+ if not resend_key:
488
+ return
489
+
490
+ try:
491
+ async with aiohttp.ClientSession() as session:
492
+ await session.post(
493
+ "https://api.resend.com/emails",
494
+ headers={
495
+ "Authorization": f"Bearer {resend_key}",
496
+ "Content-Type": "application/json",
497
+ },
498
+ json={
499
+ "from": "Elite <elite@webstark.org>",
500
+ "to": [notify_email],
501
+ "subject": f"📝 Gesprächs-Zusammenfassung: {summary['customer_name']}",
502
+ "html": f"""
503
+ <h2>Gesprächs-Zusammenfassung</h2>
504
+ <p><b>Kunde:</b> {summary['customer_name']}</p>
505
+ <p><b>Themen:</b> {summary['topics']}</p>
506
+ <p><b>Nächste Schritte:</b> {summary['action_items']}</p>
507
+ <p><b>Interesse:</b> {summary['interest_level']}</p>
508
+ <p><b>Zeitpunkt:</b> {summary['timestamp']}</p>
509
+ """,
510
+ },
511
+ timeout=aiohttp.ClientTimeout(total=10),
512
+ )
513
+ except Exception as e:
514
+ logger.warning(f"Zusammenfassungs-Benachrichtigung fehlgeschlagen: {e}")
515
+
516
+
517
+ # Alle Tools als Liste exportieren (wird in agent.py importiert)
518
+ ALL_TOOLS = [
519
+ search_web,
520
+ save_lead,
521
+ calculate_quote,
522
+ send_email,
523
+ suggest_appointment,
524
+ lookup_faq,
525
+ create_conversation_summary,
526
+ ]