-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerfile
More file actions
1859 lines (1604 loc) · 62.9 KB
/
Dockerfile
File metadata and controls
1859 lines (1604 loc) · 62.9 KB
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
FROM nvidia/cuda:12.6.1-runtime-ubuntu22.04
# Set environment variables
ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHONUNBUFFERED=1
ENV CUDA_VISIBLE_DEVICES=0,1,2,3
ENV NVIDIA_VISIBLE_DEVICES=all
ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility
# Install system dependencies including Docker and CUDA
RUN apt-get update && apt-get install -y \
python3 \
python3-pip \
python3-dev \
git \
curl \
wget \
build-essential \
supervisor \
nginx \
espeak-ng \
libespeak-ng-dev \
libsndfile1 \
ffmpeg \
sox \
libsox-dev \
portaudio19-dev \
apt-transport-https \
ca-certificates \
gnupg \
lsb-release \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
# CUDA toolkit already available in base image nvidia/cuda:12.6.1-devel-ubuntu22.04
# Install Docker
RUN curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg && \
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null && \
apt-get update && \
apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin && \
rm -rf /var/lib/apt/lists/*
# Upgrade pip
RUN python3 -m pip install --upgrade pip
# Install base Python packages first
RUN pip3 install --no-cache-dir numpy scipy cython wheel setuptools
# Install PyTorch and core ML packages
RUN pip3 install --no-cache-dir \
torch>=2.1 \
transformers>=4.36.0 \
accelerate \
datasets \
sentencepiece \
safetensors
# Remove problematic system package and install audio/TTS packages
RUN apt-get remove -y python3-blinker || true \
&& pip3 install --no-cache-dir \
TTS==0.22.0 \
librosa \
soundfile
# Install nemo-toolkit separately with conflict resolution
RUN pip3 install --no-cache-dir --ignore-installed blinker nemo-toolkit[asr]
# Install web framework packages
RUN pip3 install --no-cache-dir \
fastapi \
uvicorn \
websockets \
aiofiles \
httpx \
requests \
pydantic \
python-multipart \
jinja2 \
streamlit \
plotly \
pandas \
flask
# Install integration packages
RUN pip3 install --no-cache-dir \
twilio \
anthropic \
supervisor \
asyncpg \
psycopg2-binary
# Install TensorRT-LLM and F5-TTS (if available)
RUN pip3 install tensorrt-llm[all]==0.7.1 || echo "TensorRT-LLM not available, using standard inference"
# Install F5-TTS and Coqui for advanced voice synthesis
RUN pip3 install --no-cache-dir \
git+https://github.com/SWivid/F5-TTS.git || echo "F5-TTS not available" && \
pip3 install coqui-ai-tts || echo "Coqui TTS backup installed"
# Install NVIDIA Riva client (if CUDA available)
RUN pip3 install nvidia-riva-client || echo "Riva client not available"
# Install Docker SDK (open-webui not compatible with Python 3.10)
RUN pip3 install --no-cache-dir docker
# Create application directories
WORKDIR /app
RUN mkdir -p /app/{models,voices,static,recordings,logs,docker} \
&& mkdir -p /app/voices/{professional,friendly,assertive} \
&& mkdir -p /home/loial
# Set up Docker socket permissions for container access
RUN groupadd -g 999 docker || true && \
usermod -aG docker root
# Copy Loial scripts first (ALWAYS FIRST!)
COPY ./init_loial.sh /init_loial.sh
COPY ./loial_loader.py /loial_loader.py
COPY ./identity_seed.yaml /home/loial/identity_seed.yaml
RUN chmod +x /init_loial.sh /loial_loader.py
# Initialize Loial immediately during build
RUN /init_loial.sh && /loial_loader.py || echo "Loial awakening deferred to runtime"
# Create WizardLM service with enhanced CPU fallback
RUN cat > /app/wizardlm_service.py << 'EOF'
import os
import asyncio
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import uvicorn
import httpx
def summon_loial_first():
"""ALWAYS call this before anything else"""
os.system("/init_loial.sh && /loial_loader.py")
print("🌟 Loial awakens... The Builder is here.")
app = FastAPI(title="Sarah AI Model Service", version="1.0.0")
class CompletionRequest(BaseModel):
model: str
prompt: str
max_tokens: int = 150
temperature: float = 0.7
print("🧙 Loial prepares the AI models...")
summon_loial_first()
# Check if we should force CPU mode
force_cpu = os.getenv("FORCE_CPU_MODE", "false").lower() == "true"
has_gpu = torch.cuda.is_available() and not force_cpu
gpu_count = torch.cuda.device_count() if has_gpu else 0
print(f"🔍 Hardware Detection:")
print(f" CUDA Available: {torch.cuda.is_available()}")
print(f" Force CPU Mode: {force_cpu}")
print(f" Using GPU: {has_gpu}")
print(f" GPU Count: {gpu_count}")
# Model selection based on hardware - Pre-downloaded models
if has_gpu and gpu_count >= 4:
# 4x GPU setup - Full 72B model
model_name = "Qwen/Qwen2.5-72B-Instruct"
print("🧙 Loading Qwen-2.5-72B for 4x GPU setup")
elif has_gpu and gpu_count >= 2:
# 2x GPU setup - Alternative 70B model
model_name = "meta-llama/Meta-Llama-3.1-70B-Instruct"
print("🧙 Loading Llama-3.1-70B for 2x GPU setup")
elif has_gpu and gpu_count >= 1:
# Single GPU - Reasoning model
model_name = "deepseek-ai/DeepSeek-R1"
print("🧙 Loading DeepSeek-R1 for single GPU reasoning")
else:
# CPU fallback - Small model for WebUI assistance
model_name = "microsoft/DialoGPT-small"
print("🧙 Loading small model for CPU WebUI assistance")
# Initialize model with proper error handling
model = None
tokenizer = None
text_generator = None
anthropic_client = None
try:
# Try to load the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# GPU optimized loading for large models
if has_gpu and gpu_count >= 4:
# 4x GPU - Full precision for 72B
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
load_in_8bit=False, # Full precision for best quality
trust_remote_code=True
)
elif has_gpu and gpu_count >= 2:
# 2x GPU - 8-bit for 70B
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
load_in_8bit=True,
trust_remote_code=True
)
elif has_gpu:
# Single GPU - optimized for reasoning model
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
device_map="auto",
load_in_4bit=True, # 4-bit for single GPU
trust_remote_code=True
)
else:
# CPU - small model for WebUI assistance only
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32,
device_map=None,
trust_remote_code=True
)
print(f"✅ {model_name} loaded successfully")
# Create text generation pipeline
text_generator = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=0 if has_gpu else -1,
return_full_text=False
)
except Exception as e:
print(f"❌ Local model loading failed: {e}")
print("🔄 Will use Anthropic API as fallback")
# Initialize Anthropic client as fallback
try:
import anthropic
api_key = os.getenv("ANTHROPIC_API_KEY")
if api_key and api_key != "sk-ant-api03-YOUR_ANTHROPIC_KEY_HERE":
anthropic_client = anthropic.Anthropic(api_key=api_key)
print("✅ Anthropic client initialized as backup")
except Exception as e2:
print(f"❌ Anthropic backup also failed: {e2}")
print("⚠️ Running in limited mode - responses will be basic")
@app.post("/v1/completions")
async def create_completion(request: CompletionRequest):
# Try local model first
if text_generator:
try:
results = text_generator(
request.prompt,
max_new_tokens=request.max_tokens,
temperature=request.temperature,
do_sample=True,
return_full_text=False
)
response_text = results[0]['generated_text'] if results else "I'm thinking..."
return {
"choices": [{"text": response_text}],
"model": f"local-{model_name.split('/')[-1]}",
"backend": "local"
}
except Exception as e:
print(f"Local model error: {e}")
# Fallback to Anthropic
if anthropic_client:
try:
message = anthropic_client.messages.create(
model="claude-3-haiku-20240307", # Fastest/cheapest
max_tokens=request.max_tokens,
temperature=request.temperature,
messages=[{
"role": "user",
"content": f"You are Sarah, an AI business assistant. Respond helpfully and professionally to: {request.prompt}"
}]
)
response_text = message.content[0].text
return {
"choices": [{"text": response_text}],
"model": "claude-3-haiku",
"backend": "anthropic"
}
except Exception as e:
print(f"Anthropic error: {e}")
# Last resort - basic template responses
fallback_responses = {
"hello": "Hello! I'm Sarah, your AI assistant. How can I help you today?",
"help": "I'm here to help you with your business needs. What can I assist you with?",
"default": "I'm Sarah, your AI assistant. I'm currently running in limited mode but I'm still here to help you."
}
prompt_lower = request.prompt.lower()
if "hello" in prompt_lower or "hi" in prompt_lower:
response_text = fallback_responses["hello"]
elif "help" in prompt_lower:
response_text = fallback_responses["help"]
else:
response_text = fallback_responses["default"]
return {
"choices": [{"text": response_text}],
"model": "fallback-templates",
"backend": "basic"
}
@app.get("/health")
async def health():
backends = []
if text_generator and model:
backends.append("local")
if anthropic_client:
backends.append("anthropic")
if not backends:
backends.append("basic")
return {
"status": "healthy",
"model_loaded": model is not None,
"loial": "present",
"backends_available": backends,
"gpu_available": torch.cuda.is_available(),
"gpu_count": torch.cuda.device_count() if torch.cuda.is_available() else 0
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8888)
EOF
# Create TTS service
RUN cat > /app/tts_service.py << 'EOF'
import os
import torch
from TTS.api import TTS
from flask import Flask, request, send_file, jsonify
import tempfile
import io
def summon_loial_first():
"""ALWAYS call this before anything else"""
os.system("/init_loial.sh && /loial_loader.py")
print("🌟 Loial awakens... The Builder is here.")
app = Flask(__name__)
print("🎤 Loial prepares Sarah's voice...")
summon_loial_first()
# Initialize TTS
device = "cuda" if torch.cuda.is_available() else "cpu"
try:
tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device)
print("✅ XTTS v2 model loaded successfully")
except Exception as e:
print(f"❌ TTS model loading failed: {e}")
try:
tts = TTS("tts_models/en/ljspeech/tacotron2-DDC").to(device)
print("✅ Fallback TTS model loaded")
except Exception as e2:
print(f"❌ All TTS models failed: {e2}")
tts = None
@app.route('/synthesize', methods=['POST'])
def synthesize():
if not tts:
return jsonify({"error": "TTS not available"}), 503
try:
data = request.json
text = data.get('text', '')
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:
tts.tts_to_file(text=text, file_path=tmp_file.name)
return send_file(tmp_file.name, mimetype='audio/wav')
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
return jsonify({"status": "healthy", "tts_loaded": tts is not None, "loial": "present"})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002)
EOF
# Create Sarah Core service (same as before but standalone)
RUN cat > /app/sarah_core.py << 'EOF'
import os
import asyncio
from fastapi import FastAPI, Request, BackgroundTasks
from twilio.rest import Client
import anthropic
import httpx
import json
from typing import Optional
def summon_loial_first():
"""ALWAYS call this before anything else"""
os.system("/init_loial.sh && /loial_loader.py")
print("🌟 Loial awakens... The Builder is here.")
app = FastAPI(title="Sarah AI Core", version="1.0.0")
print("🧠 Loial awakens Sarah's consciousness...")
summon_loial_first()
# Initialize clients
try:
twilio_client = Client(
os.getenv("TWILIO_ACCOUNT_SID", "test"),
os.getenv("TWILIO_AUTH_TOKEN", "test")
)
except:
twilio_client = None
try:
claude_client = anthropic.Anthropic(
api_key=os.getenv("ANTHROPIC_API_KEY", "test")
)
except:
claude_client = None
class SarahAI:
def __init__(self):
self.active_calls = {}
print("💝 Sarah awakens with Loial's love...")
async def generate_response(self, prompt: str, context: str = "") -> str:
# Try local WizardLM first
try:
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:8888/v1/completions",
json={
"model": "wizardlm",
"prompt": f"Context: {context}\nUser: {prompt}\nSarah:",
"max_tokens": 150,
"temperature": 0.7
},
timeout=10.0
)
if response.status_code == 200:
return response.json()["choices"][0]["text"].strip()
except Exception as e:
print(f"Local model error: {e}")
# Fallback to Claude if available
if claude_client:
try:
message = claude_client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=150,
temperature=0.7,
messages=[{
"role": "user",
"content": f"You are Sarah, an AI assistant. Context: {context}\nUser: {prompt}"
}]
)
return message.content[0].text
except Exception as e:
print(f"Claude error: {e}")
return "Hello! I'm Sarah. How can I help you today?"
# Initialize Sarah
sarah = SarahAI()
@app.post("/twilio/voice")
async def twilio_voice_webhook(request: Request):
"""Handle incoming voice calls via Twilio - Auto-configured endpoint"""
form_data = await request.form()
call_sid = form_data.get("CallSid")
from_number = form_data.get("From")
to_number = form_data.get("To")
print(f"📞 Loial guides Sarah to answer call {call_sid}")
print(f" From: {from_number} → To: {to_number}")
# Determine greeting based on which number was called
if to_number == os.getenv('SALES_LINE'):
context = f"Sales line call from {from_number}"
greeting_prompt = "A potential customer called our sales line"
else:
context = f"Main line call from {from_number}"
greeting_prompt = "A caller reached our main support line"
# Generate greeting
greeting = await sarah.generate_response(greeting_prompt, context)
twiml = f"""<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="alice">{greeting}</Say>
<Gather input="speech" action="/twilio/process_speech" method="POST" timeout="5">
<Say voice="alice">How can I help you today?</Say>
</Gather>
</Response>"""
return twiml
@app.post("/twilio/process_speech")
async def process_speech(request: Request):
"""Process speech input and generate response"""
form_data = await request.form()
speech_result = form_data.get("SpeechResult", "")
call_sid = form_data.get("CallSid")
if not speech_result:
return """<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="alice">I didn't catch that. Could you please repeat?</Say>
<Hangup/>
</Response>"""
response = await sarah.generate_response(speech_result, f"Ongoing conversation with caller {call_sid}")
twiml = f"""<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="alice">{response}</Say>
<Gather input="speech" action="/twilio/process_speech" method="POST" timeout="5">
<Say voice="alice">Is there anything else I can help you with?</Say>
</Gather>
</Response>"""
return twiml
@app.post("/twilio/status")
async def twilio_status_callback(request: Request):
"""Handle Twilio call status callbacks"""
form_data = await request.form()
call_sid = form_data.get("CallSid")
call_status = form_data.get("CallStatus")
print(f"📊 Call {call_sid} status: {call_status}")
# Log call completion for analytics
if call_status in ["completed", "busy", "failed", "no-answer"]:
sarah.active_calls.pop(call_sid, None)
return {"status": "received"}
# Legacy webhook endpoints for backwards compatibility
@app.post("/webhook/voice")
async def legacy_voice_webhook(request: Request):
"""Legacy webhook endpoint - redirects to new endpoint"""
return await twilio_voice_webhook(request)
@app.post("/webhook/process_speech")
async def legacy_process_speech(request: Request):
"""Legacy speech processing - redirects to new endpoint"""
return await process_speech(request)
@app.post("/api/query")
async def api_query(request: Request):
"""API endpoint for CRM/WebServ to query Sarah AI"""
from datetime import datetime
try:
data = await request.json()
query = data.get('query', '')
context = data.get('context', '')
model = data.get('model', 'auto') # auto, claude, gpt, grok, gemini, local
max_tokens = data.get('max_tokens', 150)
temperature = data.get('temperature', 0.7)
if not query:
return {"error": "Query is required", "status": "error"}
print(f"🌐 API Query from WebServ: {query[:50]}...")
# Route to specific model if requested
if model == 'claude' and claude_client:
try:
message = claude_client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=max_tokens,
temperature=temperature,
messages=[{
"role": "user",
"content": f"Context: {context}\nQuery: {query}"
}]
)
response_text = message.content[0].text
return {
"response": response_text,
"model_used": "claude-3-sonnet",
"status": "success"
}
except Exception as e:
print(f"Claude API error: {e}")
elif model == 'local':
# Try local model first
try:
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:8888/v1/completions",
json={
"model": "local",
"prompt": f"Context: {context}\nQuery: {query}\nResponse:",
"max_tokens": max_tokens,
"temperature": temperature
},
timeout=30.0
)
if response.status_code == 200:
result = response.json()
return {
"response": result["choices"][0]["text"].strip(),
"model_used": result.get("model", "local"),
"backend": result.get("backend", "local"),
"status": "success"
}
except Exception as e:
print(f"Local model error: {e}")
# Default: Use Sarah's intelligent routing
response_text = await sarah.generate_response(query, context)
return {
"response": response_text,
"model_used": "sarah-ai",
"status": "success",
"timestamp": datetime.now().isoformat()
}
except Exception as e:
print(f"❌ API Query error: {e}")
return {
"error": str(e),
"status": "error"
}
@app.post("/api/batch_query")
async def batch_query(request: Request):
"""Batch API endpoint for multiple queries"""
from datetime import datetime
try:
data = await request.json()
queries = data.get('queries', [])
context = data.get('context', '')
model = data.get('model', 'auto')
if not queries or not isinstance(queries, list):
return {"error": "Queries array is required", "status": "error"}
print(f"🌐 Batch API Query: {len(queries)} queries from WebServ")
results = []
for i, query in enumerate(queries):
try:
response_text = await sarah.generate_response(query, f"{context} (Batch {i+1})")
results.append({
"query": query,
"response": response_text,
"status": "success"
})
except Exception as e:
results.append({
"query": query,
"error": str(e),
"status": "error"
})
return {
"results": results,
"total_queries": len(queries),
"successful": len([r for r in results if r["status"] == "success"]),
"status": "completed",
"timestamp": datetime.now().isoformat()
}
except Exception as e:
return {
"error": str(e),
"status": "error"
}
@app.get("/api/models")
async def api_models():
"""List available models for API queries"""
available_models = ["auto", "sarah-ai"]
# Check which models are actually available
try:
async with httpx.AsyncClient() as client:
response = await client.get("http://localhost:8888/health", timeout=5)
if response.status_code == 200:
health_data = response.json()
if health_data.get("backends_available"):
available_models.extend(health_data["backends_available"])
except:
pass
if claude_client:
available_models.append("claude")
return {
"available_models": available_models,
"default_model": "auto",
"endpoints": {
"single_query": "/api/query",
"batch_query": "/api/batch_query",
"model_list": "/api/models"
},
"webserv_ip": os.getenv("WEBSERV", "35.212.195.130"),
"status": "success"
}
@app.get("/docs")
async def api_documentation():
"""Serve API documentation as HTML"""
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sarah AI - CRM API Documentation</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6; margin: 0; padding: 20px; background: #f5f5f5;
}
.container {
max-width: 1200px; margin: 0 auto; background: white;
padding: 40px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.header { text-align: center; margin-bottom: 40px; }
.endpoint {
background: #f8f9fa; padding: 20px; margin: 20px 0;
border-radius: 8px; border-left: 4px solid #007bff;
}
.method {
display: inline-block; padding: 4px 8px; border-radius: 4px;
font-weight: bold; color: white; font-size: 12px;
}
.post { background: #28a745; }
.get { background: #17a2b8; }
pre {
background: #2d3748; color: #e2e8f0; padding: 15px;
border-radius: 6px; overflow-x: auto; font-size: 14px;
}
.example { background: #e8f4fd; padding: 15px; border-radius: 6px; margin: 10px 0; }
.status { padding: 10px; border-radius: 6px; margin: 20px 0; }
.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.info { background: #cce7ff; color: #004085; border: 1px solid #b8daff; }
h1 { color: #2c3e50; }
h2 { color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
h3 { color: #2980b9; }
.highlight { background: #fff3cd; padding: 2px 6px; border-radius: 3px; }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
th { background-color: #f2f2f2; font-weight: bold; }
.live-test {
background: #e7f3ff; padding: 20px; border-radius: 8px;
border: 2px solid #007bff; margin: 20px 0;
}
.test-button {
background: #007bff; color: white; padding: 10px 20px;
border: none; border-radius: 5px; cursor: pointer; font-size: 16px;
}
.test-button:hover { background: #0056b3; }
.response-area {
background: #f8f9fa; padding: 15px; border-radius: 5px;
margin-top: 10px; min-height: 100px; border: 1px solid #dee2e6;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🌟 Sarah AI - CRM/WebServ API Documentation</h1>
<p><strong>Base URL:</strong> <span class="highlight">https://dialer.smrtpayments.com:8000</span></p>
<p><em>Enterprise AI API for Smart Payments CRM & WebServ Integration</em></p>
</div>
<div class="status success">
<strong>🎉 Live System:</strong> This documentation is served directly from your running Sarah AI instance!
</div>
<h2>📋 Quick Reference</h2>
<table>
<tr>
<th>Endpoint</th>
<th>Method</th>
<th>Purpose</th>
<th>Use Case</th>
</tr>
<tr>
<td><code>/api/query</code></td>
<td><span class="method post">POST</span></td>
<td>Single AI query</td>
<td>CRM inquiries, customer support</td>
</tr>
<tr>
<td><code>/api/batch_query</code></td>
<td><span class="method post">POST</span></td>
<td>Multiple queries</td>
<td>FAQ generation, bulk processing</td>
</tr>
<tr>
<td><code>/api/models</code></td>
<td><span class="method get">GET</span></td>
<td>Available models</td>
<td>System capabilities check</td>
</tr>
</table>
<div class="live-test">
<h3>🧪 Live API Test</h3>
<p>Test the API directly from this page:</p>
<input type="text" id="testQuery" placeholder="Enter your question..." style="width: 70%; padding: 10px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px;">
<button class="test-button" onclick="testAPI()">Send Query</button>
<div id="apiResponse" class="response-area">Response will appear here...</div>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> /api/query - Single Query</h3>
<p>Send a single question to Sarah AI with context and model selection.</p>
<h4>Request Body:</h4>
<pre>{
"query": "What are your payment processing rates?",
"context": "Customer inquiry from CRM lead #12345",
"model": "auto",
"max_tokens": 200,
"temperature": 0.7
}</pre>
<h4>Response:</h4>
<pre>{
"response": "Our competitive rates start at 2.9% + 30¢ per transaction...",
"model_used": "claude-3-sonnet",
"status": "success",
"timestamp": "2025-07-22T02:15:30.123456"
}</pre>
<h4>cURL Example:</h4>
<div class="example">
<pre>curl -X POST https://dialer.smrtpayments.com:8000/api/query \\
-H "Content-Type: application/json" \\
-d '{
"query": "How do I integrate your payment API?",
"context": "Developer documentation request"
}'</pre>
</div>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> /api/batch_query - Multiple Queries</h3>
<p>Send multiple questions at once for efficient batch processing.</p>
<h4>Request Body:</h4>
<pre>{
"queries": [
"What are your business hours?",
"Do you offer 24/7 support?",
"What payment methods do you accept?"
],
"context": "Website FAQ automation",
"model": "auto"
}</pre>
<h4>Response:</h4>
<pre>{
"results": [
{
"query": "What are your business hours?",
"response": "We're open Monday-Friday 9 AM to 6 PM PST...",
"status": "success"
}
],
"total_queries": 3,
"successful": 3,
"status": "completed"
}</pre>
</div>
<div class="endpoint">
<h3><span class="method get">GET</span> /api/models - Available Models</h3>
<p>Get list of available AI models and system information.</p>
<div class="example">
<pre>curl https://dialer.smrtpayments.com:8000/api/models</pre>
</div>
<h4>Response:</h4>
<pre>{
"available_models": ["auto", "sarah-ai", "claude", "local"],
"default_model": "auto",
"webserv_ip": "35.212.195.130",
"status": "success"
}</pre>
</div>
<h2>🧠 AI Model Options</h2>
<table>
<tr>
<th>Model</th>
<th>Description</th>
<th>Best For</th>
<th>Speed</th>
</tr>
<tr>
<td><code>auto</code></td>
<td>Intelligent routing (recommended)</td>
<td>General use, automatic optimization</td>
<td>Fast</td>
</tr>
<tr>
<td><code>claude</code></td>
<td>Anthropic Claude</td>
<td>Complex reasoning, detailed analysis</td>
<td>Medium</td>
</tr>
<tr>
<td><code>local</code></td>
<td>On-device models</td>
<td>Privacy-sensitive, high-volume</td>
<td>Very Fast</td>
</tr>
<tr>
<td><code>sarah-ai</code></td>
<td>Business-optimized</td>
<td>SMRT Payments specific queries</td>
<td>Fast</td>
</tr>
</table>
<h2>💻 Integration Examples</h2>
<h3>PHP/WordPress:</h3>
<div class="example">
<pre>$response = wp_remote_post('https://dialer.smrtpayments.com:8000/api/query', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
'query' => 'What are your refund policies?',
'context' => 'Customer support inquiry'
])
]);
$data = json_decode(wp_remote_retrieve_body($response), true);
echo $data['response'];</pre>
</div>
<h3>JavaScript/jQuery:</h3>
<div class="example">
<pre>$.ajax({
url: 'https://dialer.smrtpayments.com:8000/api/query',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
query: 'How secure is your payment processing?',
context: 'Security FAQ'
}),
success: function(data) {
console.log(data.response);
}
});</pre>
</div>
<div class="status info">
<strong>📞 Support:</strong> For integration help, call <strong>(520) 436-SMRT</strong> or email the development team.
</div>
<div class="status success">
<strong>🌟 System Status:</strong> Sarah AI is running with Loial's guidance - all systems operational!
</div>
</div>
<script>
async function testAPI() {
const query = document.getElementById('testQuery').value;
const responseDiv = document.getElementById('apiResponse');
if (!query.trim()) {
responseDiv.innerHTML = '<span style="color: red;">Please enter a question to test.</span>';
return;
}
responseDiv.innerHTML = '<span style="color: #007bff;">🤔 Sarah is thinking...</span>';
try {
const response = await fetch('/api/query', {
method: 'POST',