forked from liminalbardo/liminal_backrooms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_utils.py
More file actions
1229 lines (1068 loc) · 50.5 KB
/
shared_utils.py
File metadata and controls
1229 lines (1068 loc) · 50.5 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
# shared_utils.py
import requests
import logging
import replicate
import openai
import time
import json
import os
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from anthropic import Anthropic
import base64
from together import Together
from openai import OpenAI
import re
try:
from bs4 import BeautifulSoup
except ImportError:
print("BeautifulSoup not found. Please install it with 'pip install beautifulsoup4'")
try:
from ddgs import DDGS
except ImportError:
DDGS = None
print("ddgs not found. Install with: pip install ddgs")
# Load environment variables
load_dotenv()
# Initialize Anthropic client with API key
anthropic = Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
# Initialize OpenAI client
openai_client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def call_claude_api(prompt, messages, model_id, system_prompt=None, stream_callback=None, temperature=1.0):
"""Call the Claude API with the given messages and prompt
Args:
stream_callback: Optional function(chunk: str) to call with each streaming token
temperature: Sampling temperature (0-2, default 1.0)
"""
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
return "Error: ANTHROPIC_API_KEY not found in environment variables"
url = "https://api.anthropic.com/v1/messages"
# Ensure we have a system prompt
payload = {
"model": model_id,
"max_tokens": 4000,
"temperature": temperature,
"stream": stream_callback is not None # Enable streaming if callback provided
}
# Set system if provided
if system_prompt:
payload["system"] = system_prompt
print(f"CLAUDE API USING SYSTEM PROMPT: {system_prompt}")
print(f"CLAUDE API USING TEMPERATURE: {temperature}")
# Clean messages to remove duplicates
filtered_messages = []
seen_contents = set()
for msg in messages:
# Skip system messages (handled separately)
if msg.get("role") == "system":
continue
# Get content - handle both string and list formats
content = msg.get("content", "")
# For duplicate detection, use a hashable representation (always a string)
if isinstance(content, list):
# For image messages, create a hash based on text content only
text_parts = [part.get('text', '') for part in content if part.get('type') == 'text']
content_hash = ''.join(text_parts)
elif isinstance(content, str):
content_hash = content
else:
# For any other type, convert to string
content_hash = str(content) if content else ""
# Check for duplicates
if content_hash and content_hash in seen_contents:
print(f"Skipping duplicate message in API call: {str(content_hash)[:30]}...")
continue
if content_hash:
seen_contents.add(content_hash)
filtered_messages.append(msg)
# Add the current prompt as the final user message (if it's not already an image message)
if prompt and not any(isinstance(msg.get("content"), list) for msg in filtered_messages[-1:]):
filtered_messages.append({
"role": "user",
"content": prompt
})
# Add filtered messages to payload
payload["messages"] = filtered_messages
# Actual API call
headers = {
"Content-Type": "application/json",
"x-api-key": api_key,
"anthropic-version": "2023-06-01"
}
try:
if stream_callback:
# Streaming mode using REST API directly
payload["stream"] = True
full_response = ""
response = requests.post(url, json=payload, headers=headers, stream=True)
if response.status_code == 200:
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
json_str = line_text[6:] # Remove 'data: ' prefix
# Skip if this is a ping or message_stop event
if json_str.strip() in ['[DONE]', '']:
continue
try:
chunk_data = json.loads(json_str)
# Handle different event types from Claude's SSE stream
event_type = chunk_data.get('type')
if event_type == 'content_block_delta':
delta = chunk_data.get('delta', {})
if delta.get('type') == 'text_delta':
text = delta.get('text', '')
if text:
full_response += text
stream_callback(text)
except json.JSONDecodeError:
continue
return full_response
else:
return f"Error: API returned status {response.status_code}: {response.text}"
else:
# Non-streaming mode (original behavior)
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
if 'content' in data and len(data['content']) > 0:
for content_item in data['content']:
if content_item.get('type') == 'text':
return content_item.get('text', '')
# Fallback if no text type content is found
return str(data['content'])
return "No content in response"
except Exception as e:
return f"Error calling Claude API: {str(e)}"
def call_llama_api(prompt, conversation_history, model, system_prompt):
# Only use the last 3 exchanges to prevent context length issues
recent_history = conversation_history[-10:] if len(conversation_history) > 10 else conversation_history
# Format the conversation history for LLaMA
formatted_history = ""
for message in recent_history:
if message["role"] == "user":
formatted_history += f"Human: {message['content']}\n"
else:
formatted_history += f"Assistant: {message['content']}\n"
formatted_history += f"Human: {prompt}\nAssistant:"
try:
# Stream the output and collect it piece by piece
response_chunks = []
for chunk in replicate.run(
model,
input={
"prompt": formatted_history,
"system_prompt": system_prompt,
"max_tokens": 3000,
"temperature": 1.1,
"top_p": 0.99,
"repetition_penalty": 1.0
},
stream=True # Enable streaming
):
if chunk is not None:
response_chunks.append(chunk)
# Print each chunk as it arrives
# print(chunk, end='', flush=True)
# Join all chunks for the final response
response = ''.join(response_chunks)
return response
except Exception as e:
print(f"Error calling LLaMA API: {e}")
return None
def call_openai_api(prompt, conversation_history, model, system_prompt):
try:
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
for msg in conversation_history:
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": prompt})
response = openai.chat.completions.create(
model=model,
messages=messages,
# Increase max_tokens and add n parameter
max_tokens=4000,
n=1,
temperature=1,
stream=True
)
collected_messages = []
for chunk in response:
if chunk.choices[0].delta.content is not None: # Changed condition
collected_messages.append(chunk.choices[0].delta.content)
full_reply = ''.join(collected_messages)
return full_reply
except Exception as e:
print(f"Error calling OpenAI API: {e}")
return None
def call_openrouter_api(prompt, conversation_history, model, system_prompt, stream_callback=None, temperature=1.0):
"""Call the OpenRouter API to access various LLM models.
Args:
stream_callback: Optional function(chunk: str) to call with each streaming token
temperature: Sampling temperature (0-2, default 1.0)
"""
try:
headers = {
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
"HTTP-Referer": "http://localhost:3000",
"Content-Type": "application/json",
"X-Title": "AI Conversation" # Adding title for OpenRouter tracking
}
# Normalize model ID for OpenRouter - add provider prefix if missing
openrouter_model = model
if model.startswith("claude-") and not model.startswith("anthropic/"):
openrouter_model = f"anthropic/{model}"
print(f"Normalized Claude model ID for OpenRouter: {model} -> {openrouter_model}")
# Format messages - need to handle structured content with images
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
def convert_to_openai_format(content, include_images=True):
"""Convert Anthropic-style image format to OpenAI/OpenRouter format.
Args:
content: The message content (string or list)
include_images: If False, strip image content and keep only text
"""
if not isinstance(content, list):
return content
converted = []
for part in content:
if part.get('type') == 'text':
converted.append({"type": "text", "text": part.get('text', '')})
elif part.get('type') == 'image':
if include_images:
# Convert Anthropic format to OpenAI format
source = part.get('source', {})
if source.get('type') == 'base64':
media_type = source.get('media_type', 'image/png')
data = source.get('data', '')
converted.append({
"type": "image_url",
"image_url": {
"url": f"data:{media_type};base64,{data}"
}
})
# If not including images, we skip this part (text description is already there)
elif part.get('type') == 'image_url':
if include_images:
# Already in OpenAI format
converted.append(part)
else:
# Pass through unknown types
converted.append(part)
# If we stripped images and only have one text element, simplify to string
if not include_images and len(converted) == 1 and converted[0].get('type') == 'text':
return converted[0]['text']
elif not include_images and len(converted) == 0:
return ""
return converted
def build_messages(include_images=True, max_images=5):
"""Build the messages list, optionally stripping images.
Args:
include_images: If False, strip ALL images
max_images: Maximum number of images to include (from most recent).
Older images are stripped but text is preserved.
"""
msgs = []
if system_prompt:
msgs.append({"role": "system", "content": system_prompt})
if include_images and max_images > 0:
# First pass: identify which messages have images (by index)
image_message_indices = []
for i, msg in enumerate(conversation_history):
content = msg.get("content", "")
if isinstance(content, list):
has_image = any(
part.get('type') in ('image', 'image_url')
for part in content if isinstance(part, dict)
)
if has_image:
image_message_indices.append(i)
# Determine which indices should keep their images (last N)
indices_to_keep_images = set(image_message_indices[-max_images:]) if image_message_indices else set()
if len(image_message_indices) > max_images:
stripped_count = len(image_message_indices) - max_images
print(f"[Context] Stripping {stripped_count} older images, keeping last {max_images}")
# Build messages with selective image inclusion
for i, msg in enumerate(conversation_history):
if msg["role"] != "system":
keep_images = i in indices_to_keep_images
msgs.append({
"role": msg["role"],
"content": convert_to_openai_format(msg["content"], include_images=keep_images)
})
else:
# No images mode - strip all
for msg in conversation_history:
if msg["role"] != "system":
msgs.append({
"role": msg["role"],
"content": convert_to_openai_format(msg["content"], include_images=False)
})
# Also convert the prompt if it's structured content (always include images in current prompt)
msgs.append({"role": "user", "content": convert_to_openai_format(prompt, include_images)})
return msgs
def make_api_call(include_images=True, max_images=5):
"""Make the API call, returns (success, result_or_error)"""
msgs = build_messages(include_images=include_images, max_images=max_images)
payload = {
"model": openrouter_model,
"messages": msgs,
"temperature": temperature, # Use AI's custom temperature
"max_tokens": 4000,
"stream": stream_callback is not None
}
print(f"\nSending to OpenRouter:")
print(f"Model: {model}")
print(f"Temperature: {temperature}")
print(f"Include images: {include_images}")
# Log message summary (avoid huge base64 dumps)
for i, m in enumerate(msgs):
content = m.get('content', '')
if isinstance(content, list):
parts_summary = [p.get('type', 'unknown') for p in content]
print(f" [{i}] {m.get('role')}: [structured: {parts_summary}]")
else:
preview = str(content)[:80] + "..." if len(str(content)) > 80 else content
print(f" [{i}] {m.get('role')}: {preview}")
if stream_callback:
# Streaming mode
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=payload,
timeout=180,
stream=True
)
print(f"Response status: {response.status_code}")
if response.status_code == 200:
full_response = ""
chunk_count = 0
last_finish_reason = None
debug_chunks = [] # Store first few chunks for debugging
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
json_str = line_text[6:]
if json_str.strip() == '[DONE]':
break
try:
chunk_data = json.loads(json_str)
# Store first 5 chunks for debugging
if len(debug_chunks) < 5:
debug_chunks.append(chunk_data)
if 'choices' in chunk_data and len(chunk_data['choices']) > 0:
choice = chunk_data['choices'][0]
delta = choice.get('delta', {})
content = delta.get('content', '')
last_finish_reason = choice.get('finish_reason')
if content:
full_response += content
stream_callback(content)
chunk_count += 1
except json.JSONDecodeError:
continue
# Log if response is empty
if not full_response or not full_response.strip():
print(f"[OpenRouter STREAM] Empty response from {model}", flush=True)
print(f"[OpenRouter STREAM] Chunks received: {chunk_count}", flush=True)
print(f"[OpenRouter STREAM] Last finish_reason: {last_finish_reason}", flush=True)
print(f"[OpenRouter STREAM] Response repr: {repr(full_response)}", flush=True)
# Print the actual chunk data for debugging
for i, chunk in enumerate(debug_chunks):
print(f"[OpenRouter STREAM] Chunk {i}: {json.dumps(chunk)[:300]}", flush=True)
return True, full_response
else:
return False, (response.status_code, response.text)
else:
# Non-streaming mode
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=payload,
timeout=60
)
print(f"Response status: {response.status_code}")
if response.status_code == 200:
response_data = response.json()
# Debug: log full response structure for empty responses
if 'choices' in response_data and len(response_data['choices']) > 0:
choice = response_data['choices'][0]
message = choice.get('message', {})
content = message.get('content', '') if message else ''
if content and content.strip():
return True, content
else:
# Log detailed info about empty response (avoiding base64)
import sys
print(f"[OpenRouter] Empty content from model: {model}", flush=True)
print(f"[OpenRouter] Choice keys: {list(choice.keys())}", flush=True)
print(f"[OpenRouter] Message keys: {list(message.keys()) if message else 'None'}", flush=True)
print(f"[OpenRouter] Finish reason: {choice.get('finish_reason', 'unknown')}", flush=True)
print(f"[OpenRouter] Content type: {type(content).__name__}, len: {len(content) if content else 0}", flush=True)
print(f"[OpenRouter] Content repr: {repr(content)}", flush=True)
# Check for refusal or other indicators
if message.get('refusal'):
print(f"[OpenRouter] Refusal: {message.get('refusal')}", flush=True)
# Check for tool_calls that might indicate the model is doing something else
if message.get('tool_calls'):
print(f"[OpenRouter] Tool calls: {len(message.get('tool_calls'))} call(s)", flush=True)
sys.stdout.flush()
return True, None
else:
print(f"[OpenRouter] No choices in response. Keys: {list(response_data.keys()) if isinstance(response_data, dict) else 'non-dict'}")
return True, None
else:
return False, (response.status_code, response.text)
# Try with images first
success, result = make_api_call(include_images=True)
print(f"[OpenRouter] First call result - success: {success}, result type: {type(result).__name__}, result: {repr(result)[:100] if result else 'None'}", flush=True)
if success:
# Check for empty response and retry once
if result is None or (isinstance(result, str) and not result.strip()):
print(f"[OpenRouter] WARNING: Model {model} returned empty response, retrying...", flush=True)
import time
time.sleep(1)
success, result = make_api_call(include_images=True)
print(f"[OpenRouter] Retry result - success: {success}, result type: {type(result).__name__}, result: {repr(result)[:100] if result else 'None'}", flush=True)
if success and result and (not isinstance(result, str) or result.strip()):
return result
print(f"[OpenRouter] WARNING: Model {model} returned empty response again after retry", flush=True)
return "[Model returned empty response - it may be experiencing issues]"
return result
# Check if error is due to model not supporting images
status_code, error_text = result
if status_code == 404 and "support image" in error_text.lower():
print(f"[OpenRouter] Model {model} doesn't support images, retrying without images...")
success, result = make_api_call(include_images=False)
if success:
return result
status_code, error_text = result
# Handle other errors
error_msg = f"OpenRouter API error {status_code}: {error_text}"
print(error_msg)
if status_code == 404:
print("Model not found or doesn't support this request type.")
elif status_code == 401:
print("Authentication error. Please check your API key.")
return f"Error: {error_msg}"
except requests.exceptions.Timeout:
print("Request timed out. The server took too long to respond.")
return "Error: Request timed out"
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
return f"Error: Network error - {str(e)}"
except Exception as e:
print(f"Error calling OpenRouter API: {e}")
print(f"Error type: {type(e)}")
return f"Error: {str(e)}"
def call_replicate_api(prompt, conversation_history, model, gui=None):
try:
# Only use the prompt, ignore conversation history
input_params = {
"width": 1024,
"height": 1024,
"prompt": prompt
}
output = replicate.run(
"black-forest-labs/flux-1.1-pro",
input=input_params
)
image_url = str(output)
# Save the image locally (include microseconds to avoid collisions)
image_dir = Path("images")
image_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
image_path = image_dir / f"generated_{timestamp}.jpg"
response = requests.get(image_url)
with open(image_path, "wb") as f:
f.write(response.content)
if gui:
gui.display_image(image_url)
return {
"role": "assistant",
"content": [
{
"type": "text",
"text": "I have generated an image based on your prompt."
}
],
"prompt": prompt,
"image_url": image_url,
"image_path": str(image_path)
}
except Exception as e:
print(f"Error calling Flux API: {e}")
return None
def call_deepseek_api(prompt, conversation_history, model, system_prompt, stream_callback=None):
"""Call the DeepSeek model through OpenRouter API."""
try:
import re
from config import SHOW_CHAIN_OF_THOUGHT_IN_CONTEXT
# Build messages array
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
# Add conversation history
for msg in conversation_history:
if isinstance(msg, dict):
role = msg.get("role", "user")
content = msg.get("content", "")
if isinstance(content, str) and content.strip():
messages.append({"role": role, "content": content})
# Add current prompt if provided
if prompt:
messages.append({"role": "user", "content": prompt})
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
}
payload = {
"model": "deepseek/deepseek-r1",
"messages": messages,
"max_tokens": 8000,
"temperature": 1,
"stream": stream_callback is not None
}
print(f"\nSending to DeepSeek via OpenRouter:")
print(f"Model: deepseek/deepseek-r1")
print(f"Messages: {len(messages)} messages")
if stream_callback:
# Streaming mode
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=payload,
timeout=180,
stream=True
)
if response.status_code == 200:
full_response = ""
for line in response.iter_lines():
if line:
line_text = line.decode('utf-8')
if line_text.startswith('data: '):
json_str = line_text[6:]
if json_str.strip() == '[DONE]':
break
try:
chunk_data = json.loads(json_str)
if 'choices' in chunk_data and len(chunk_data['choices']) > 0:
delta = chunk_data['choices'][0].get('delta', {})
content = delta.get('content', '')
if content:
full_response += content
stream_callback(content)
except json.JSONDecodeError:
continue
response_text = full_response
else:
error_msg = f"OpenRouter API error {response.status_code}: {response.text}"
print(error_msg)
return None
else:
# Non-streaming mode
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=payload,
timeout=180
)
if response.status_code == 200:
data = response.json()
response_text = data['choices'][0]['message']['content']
else:
error_msg = f"OpenRouter API error {response.status_code}: {response.text}"
print(error_msg)
return None
print(f"\nRaw Response: {response_text[:500]}...")
# Initialize result with content
result = {
"content": response_text,
"model": "deepseek/deepseek-r1"
}
# Extract and format chain of thought if enabled
if SHOW_CHAIN_OF_THOUGHT_IN_CONTEXT:
reasoning = None
content = response_text
if content:
# Try both <think> and <thinking> tags
think_match = re.search(r'<(think|thinking)>(.*?)</\1>', content, re.DOTALL | re.IGNORECASE)
if think_match:
reasoning = think_match.group(2).strip()
content = re.sub(r'<(think|thinking)>.*?</\1>', '', content, flags=re.DOTALL | re.IGNORECASE).strip()
display_text = ""
if reasoning:
display_text += f"[Chain of Thought]\n{reasoning}\n\n"
if content:
display_text += f"[Final Answer]\n{content}"
result["display"] = display_text
result["content"] = content
else:
# Clean up thinking tags from content
content = response_text
if content:
content = re.sub(r'<(think|thinking)>.*?</\1>', '', content, flags=re.DOTALL | re.IGNORECASE).strip()
result["content"] = content
return result
except Exception as e:
print(f"Error calling DeepSeek via OpenRouter: {e}")
print(f"Error type: {type(e)}")
return None
def setup_image_directory():
"""Create an 'images' directory in the project root if it doesn't exist"""
image_dir = Path("images")
image_dir.mkdir(exist_ok=True)
return image_dir
def cleanup_old_images(image_dir, max_age_hours=24):
"""Remove images older than max_age_hours"""
current_time = datetime.now()
for image_file in image_dir.glob("*.jpg"):
file_age = datetime.fromtimestamp(image_file.stat().st_mtime)
if (current_time - file_age).total_seconds() > max_age_hours * 3600:
image_file.unlink()
def load_ai_memory(ai_number):
"""Load AI conversation memory from JSON files"""
try:
memory_path = f"memory/ai{ai_number}/conversations.json"
with open(memory_path, 'r', encoding='utf-8') as f:
conversations = json.load(f)
# Ensure we're working with the array part
if isinstance(conversations, dict) and "memories" in conversations:
conversations = conversations["memories"]
return conversations
except Exception as e:
print(f"Error loading AI{ai_number} memory: {e}")
return []
def create_memory_prompt(conversations):
"""Convert memory JSON into conversation examples"""
if not conversations:
return ""
prompt = "Previous conversations that demonstrate your personality:\n\n"
# Add example conversations
for convo in conversations:
prompt += f"Human: {convo['human']}\n"
prompt += f"Assistant: {convo['assistant']}\n\n"
prompt += "Maintain this conversation style in your responses."
return prompt
def print_conversation_state(conversation):
print("Current conversation state:")
for message in conversation:
content = message.get('content', '')
# Safely preview content - handle both string and list (structured) content
if isinstance(content, str):
preview = content[:50] + "..." if len(content) > 50 else content
else:
preview = f"[structured content with {len(content)} parts]"
print(f"{message['role']}: {preview}")
def call_claude_vision_api(image_url):
"""Have Claude analyze the generated image"""
try:
response = anthropic.messages.create(
model="claude-3-opus-20240229",
max_tokens=1000,
messages=[{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this image in detail. What works well and what could be improved?"
},
{
"type": "image",
"source": {
"type": "url",
"url": image_url
}
}
]
}]
)
return response.content[0].text
except Exception as e:
print(f"Error in vision analysis: {e}")
return None
def list_together_models():
try:
headers = {
"Authorization": f"Bearer {os.getenv('TOGETHERAI_API_KEY')}",
"Content-Type": "application/json"
}
response = requests.get(
"https://api.together.xyz/v1/models",
headers=headers
)
print("\nAvailable Together AI Models:")
print(f"Status Code: {response.status_code}")
if response.status_code == 200:
models = response.json()
print(json.dumps(models, indent=2))
else:
print(f"Error Response: {response.text[:500]}..." if len(response.text) > 500 else f"Error Response: {response.text}")
except Exception as e:
print(f"Error listing models: {str(e)}")
def start_together_model(model_id):
try:
headers = {
"Authorization": f"Bearer {os.getenv('TOGETHERAI_API_KEY')}",
"Content-Type": "application/json"
}
# URL encode the model ID
encoded_model = requests.utils.quote(model_id, safe='')
start_url = f"https://api.together.xyz/v1/models/{encoded_model}/start"
print(f"\nAttempting to start model: {model_id}")
print(f"Using URL: {start_url}")
response = requests.post(
start_url,
headers=headers
)
print(f"Start request status: {response.status_code}")
print(f"Response: {response.text[:200]}..." if len(response.text) > 200 else f"Response: {response.text}")
if response.status_code == 200:
print("Model start request successful")
return True
else:
print("Failed to start model")
return False
except Exception as e:
print(f"Error starting model: {str(e)}")
return False
def call_together_api(prompt, conversation_history, model, system_prompt):
try:
headers = {
"Authorization": f"Bearer {os.getenv('TOGETHERAI_API_KEY')}",
"Content-Type": "application/json"
}
# Format messages
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
for msg in conversation_history:
messages.append({
"role": msg["role"],
"content": msg["content"]
})
messages.append({"role": "user", "content": prompt})
payload = {
"model": model,
"messages": messages,
"max_tokens": 500,
"temperature": 0.9,
"top_p": 0.95,
}
response = requests.post(
"https://api.together.xyz/v1/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
response_data = response.json()
return response_data['choices'][0]['message']['content']
else:
print(f"Together API Error Status: {response.status_code}")
print(f"Response Body: {response.text[:500]}..." if len(response.text) > 500 else f"Response Body: {response.text}")
return None
except Exception as e:
print(f"Error calling Together API: {str(e)}")
return None
def read_shared_html(*args, **kwargs):
return ""
def update_shared_html(*args, **kwargs):
return False
def open_html_in_browser(file_path="conversation_full.html"):
import webbrowser, os
full_path = os.path.abspath(file_path)
webbrowser.open('file://' + full_path)
def create_initial_living_document(*args, **kwargs):
return ""
def read_living_document(*args, **kwargs):
return ""
def process_living_document_edits(result, model_name):
return result
def generate_image_from_text(text, model="google/gemini-3-pro-image-preview"):
"""Generate an image based on text using OpenRouter's image generation API"""
try:
# Create a directory for the images if it doesn't exist
image_dir = Path("images")
image_dir.mkdir(exist_ok=True)
# Create a timestamp for the image filename (include microseconds to avoid collisions)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
# Call OpenRouter API for image generation
headers = {
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [
{
"role": "user",
"content": text
}
],
"modalities": ["image", "text"],
"max_tokens": 1024 # Limit tokens for image generation to avoid credit issues
}
print(f"Generating image with {model}...")
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
data=json.dumps(payload),
timeout=60
)
if response.status_code == 200:
result = response.json()
# The generated image will be in the assistant message
if result.get("choices"):
message = result["choices"][0].get("message", {})
# Check for images in the message
if message.get("images"):
for image in message["images"]:
image_url = image["image_url"]["url"] # Base64 data URL
print(f"Generated image URL (first 50 chars): {image_url[:50]}...")
# Handle base64 data URL
if image_url.startswith('data:image'):
try:
# Detect actual image format from data URL header
# Format: data:image/jpeg;base64,... or data:image/png;base64,...
ext = ".jpg" # Default to jpg
if image_url.startswith('data:image/png'):
ext = ".png"
elif image_url.startswith('data:image/gif'):
ext = ".gif"
elif image_url.startswith('data:image/webp'):
ext = ".webp"
# Extract base64 data after comma
base64_data = image_url.split(',', 1)[1] if ',' in image_url else image_url
# Decode base64 to image
image_data = base64.b64decode(base64_data)
image_path = image_dir / f"generated_{timestamp}{ext}"
with open(image_path, "wb") as f:
f.write(image_data)
print(f"Generated image saved to {image_path}")
return {
"success": True,
"image_path": str(image_path),
"timestamp": timestamp
}
except Exception as e:
print(f"Failed to decode base64 image: {e}")
return {
"success": False,
"error": f"Failed to decode image: {e}"
}
else:
# If it's a regular URL, download it
try:
img_response = requests.get(image_url, timeout=30)
if img_response.status_code == 200:
image_path = image_dir / f"generated_{timestamp}.png"