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
93ef338
b02e301
e47fb69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93ef338
e47fb69
 
 
 
 
 
 
 
 
 
b02e301
e47fb69
 
93ef338
 
 
e47fb69
 
93ef338
 
e47fb69
b02e301
 
 
 
 
e47fb69
 
 
 
 
b02e301
 
 
 
 
 
 
 
 
93ef338
e47fb69
 
93ef338
e47fb69
 
 
 
93ef338
e47fb69
 
93ef338
 
e47fb69
93ef338
 
e47fb69
 
 
93ef338
 
 
 
 
e47fb69
 
 
93ef338
e47fb69
93ef338
e47fb69
93ef338
b02e301
93ef338
b02e301
e47fb69
 
93ef338
e47fb69
 
 
93ef338
 
 
e47fb69
b02e301
93ef338
b02e301
 
 
93ef338
b02e301
 
 
 
e47fb69
 
93ef338
 
b02e301
93ef338
b02e301
 
 
 
e47fb69
93ef338
 
e47fb69
 
93ef338
 
 
 
 
 
 
 
 
 
e47fb69
b02e301
e47fb69
b02e301
93ef338
 
 
b02e301
 
a524489
93ef338
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# from dotenv import load_dotenv
# from openai import OpenAI
# import json
# import os
# import requests
# from pypdf import PdfReader
# import gradio as gr


# load_dotenv(override=True)

# def push(text):
#     requests.post(
#         "https://api.pushover.net/1/messages.json",
#         data={
#             "token": os.getenv("PUSHOVER_TOKEN"),
#             "user": os.getenv("PUSHOVER_USER"),
#             "message": text,
#         }
#     )


# def record_user_details(email, name="Name not provided", notes="not provided"):
#     push(f"Recording {name} with email {email} and notes {notes}")
#     return {"recorded": "ok"}

# def record_unknown_question(question):
#     push(f"Recording {question}")
#     return {"recorded": "ok"}

# record_user_details_json = {
#     "name": "record_user_details",
#     "description": "Use this tool to record that a user is interested in being in touch and provided an email address",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "email": {
#                 "type": "string",
#                 "description": "The email address of this user"
#             },
#             "name": {
#                 "type": "string",
#                 "description": "The user's name, if they provided it"
#             }
#             ,
#             "notes": {
#                 "type": "string",
#                 "description": "Any additional information about the conversation that's worth recording to give context"
#             }
#         },
#         "required": ["email"],
#         "additionalProperties": False
#     }
# }

# record_unknown_question_json = {
#     "name": "record_unknown_question",
#     "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "question": {
#                 "type": "string",
#                 "description": "The question that couldn't be answered"
#             },
#         },
#         "required": ["question"],
#         "additionalProperties": False
#     }
# }

# tools = [{"type": "function", "function": record_user_details_json},
#         {"type": "function", "function": record_unknown_question_json}]


# class Me:

#     def __init__(self):
#         self.openai = OpenAI()
#         self.name = "Ed Donner"
#         reader = PdfReader("me/linkedin.pdf")
#         self.linkedin = ""
#         for page in reader.pages:
#             text = page.extract_text()
#             if text:
#                 self.linkedin += text
#         with open("me/summary.txt", "r", encoding="utf-8") as f:
#             self.summary = f.read()


#     def handle_tool_call(self, tool_calls):
#         results = []
#         for tool_call in tool_calls:
#             tool_name = tool_call.function.name
#             arguments = json.loads(tool_call.function.arguments)
#             print(f"Tool called: {tool_name}", flush=True)
#             tool = globals().get(tool_name)
#             result = tool(**arguments) if tool else {}
#             results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id})
#         return results
    
#     def system_prompt(self):
#         system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \
# particularly questions related to {self.name}'s career, background, skills and experience. \
# Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \
# You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \
# Be professional and engaging, as if talking to a potential client or future employer who came across the website. \
# If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \
# If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. "

#         system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n"
#         system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}."
#         return system_prompt
    
#     def chat(self, message, history):
#         messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}]
#         done = False
#         while not done:
#             response = self.openai.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)
#             if response.choices[0].finish_reason=="tool_calls":
#                 message = response.choices[0].message
#                 tool_calls = message.tool_calls
#                 results = self.handle_tool_call(tool_calls)
#                 messages.append(message)
#                 messages.extend(results)
#             else:
#                 done = True
#         return response.choices[0].message.content
    

# if __name__ == "__main__":
#     me = Me()
#     gr.ChatInterface(me.chat, type="messages").launch()




# from dotenv import load_dotenv
# from openai import OpenAI
# import json
# import os
# import requests
# from pypdf import PdfReader
# import gradio as gr

# load_dotenv(override=True)

# GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
# google_api_key = os.getenv("GOOGLE_API_KEY")

# # Initialize Gemini client
# gemini = OpenAI(
#     base_url=GEMINI_BASE_URL,
#     api_key=google_api_key
# )

# def push(text):
#     requests.post(
#         "https://api.pushover.net/1/messages.json",
#         data={
#             "token": os.getenv("PUSHOVER_TOKEN"),
#             "user": os.getenv("PUSHOVER_USER"),
#             "message": text,
#         }
#     )


# def record_user_details(email, name="Name not provided", notes="not provided"):
#     push(f"Recording {name} with email {email} and notes {notes}")
#     return {"recorded": "ok"}


# def record_unknown_question(question):
#     push(f"Recording {question}")
#     return {"recorded": "ok"}


# record_user_details_json = {
#     "name": "record_user_details",
#     "description": "Use this tool to record that a user is interested in being in touch and provided an email address",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "email": {
#                 "type": "string",
#                 "description": "The email address of this user"
#             },
#             "name": {
#                 "type": "string",
#                 "description": "The user's name, if they provided it"
#             },
#             "notes": {
#                 "type": "string",
#                 "description": "Any additional information about the conversation that's worth recording to give context"
#             }
#         },
#         "required": ["email"],
#         "additionalProperties": False
#     }
# }

# record_unknown_question_json = {
#     "name": "record_unknown_question",
#     "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "question": {
#                 "type": "string",
#                 "description": "The question that couldn't be answered"
#             },
#         },
#         "required": ["question"],
#         "additionalProperties": False
#     }
# }

# tools = [
#     {"type": "function", "function": record_user_details_json},
#     {"type": "function", "function": record_unknown_question_json}
# ]


# class Me:

#     def __init__(self):
#         self.openai = gemini     # REPLACED OpenAI WITH GEMINI
#         self.name = "AKASH M J"

#         reader = PdfReader("me/Profile.pdf")
#         self.linkedin = ""
#         for page in reader.pages:
#             text = page.extract_text()
#             if text:
#                 self.linkedin += text

#         with open("me/summary.txt", "r", encoding="utf-8") as f:
#             self.summary = f.read()

#     def handle_tool_call(self, tool_calls):
#         results = []
#         for tool_call in tool_calls:
#             tool_name = tool_call.function.name
#             arguments = json.loads(tool_call.function.arguments)
#             print(f"Tool called: {tool_name}", flush=True)
#             tool = globals().get(tool_name)
#             result = tool(**arguments) if tool else {}
#             results.append({
#                 "role": "tool",
#                 "content": json.dumps(result),
#                 "tool_call_id": tool_call.id
#             })
#         return results

#     def system_prompt(self):
#         system_prompt = (
#             f"You are acting as {self.name}. You are answering questions on {self.name}'s website, "
#             f"particularly questions related to {self.name}'s career, background, skills and experience. "
#             f"Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. "
#             f"You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. "
#             f"Be professional and engaging, as if talking to a potential client or future employer who came across the website. "
#             f"If you don't know the answer to any question, use your record_unknown_question tool to record the question. "
#             f"If the user is engaging in discussion, try to steer them towards getting in touch via email."
#         )

#         system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n"
#         system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}."
#         return system_prompt

#     def chat(self, message, history):
#         messages = [
#             {"role": "system", "content": self.system_prompt()}
#         ] + history + [
#             {"role": "user", "content": message}
#         ]

#         done = False
#         while not done:
#             # ---- CHANGED TO USE GEMINI ----
#             response = self.openai.chat.completions.create(
#                 model="gemini-2.0-flash",
#                 messages=messages,
#                 tools=tools
#             )
#             # --------------------------------

#             if response.choices[0].finish_reason == "tool_calls":
#                 message = response.choices[0].message
#                 tool_calls = message.tool_calls
#                 results = self.handle_tool_call(tool_calls)
#                 messages.append(message)
#                 messages.extend(results)
#             else:
#                 done = True

#         return response.choices[0].message.content


# if __name__ == "__main__":
#     me = Me()
#     gr.ChatInterface(me.chat, type="messages").launch()
#     # gr.ChatInterface(me.chat).launch()




#  working perfectly one
# # app.py
# from dotenv import load_dotenv
# from openai import OpenAI
# import json
# import os
# import requests
# from pypdf import PdfReader
# import gradio as gr
# import sqlite3
# import time

# load_dotenv(override=True)

# # --- CONFIG ---
# GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
# google_api_key = os.getenv("GOOGLE_API_KEY")

# # Initialize Gemini client (using OpenAI wrapper you used earlier)
# gemini = OpenAI(base_url=GEMINI_BASE_URL, api_key=google_api_key)

# # --- Pushover helper ---
# def push(text):
#     token = os.getenv("PUSHOVER_TOKEN")
#     user = os.getenv("PUSHOVER_USER")
#     if not token or not user:
#         print("Pushover credentials not set. Skipping push.")
#         return
#     try:
#         requests.post(
#             "https://api.pushover.net/1/messages.json",
#             data={"token": token, "user": user, "message": text},
#             timeout=5
#         )
#     except Exception as e:
#         print("Pushover error:", e)

# # --- Tools (actual implementations) ---
# def record_user_details(email, name="Name not provided", notes="not provided"):
#     push(f"Recording contact: {name} <{email}> notes: {notes}")
#     return {"recorded": "ok", "email": email, "name": name}

# def record_unknown_question(question):
#     push(f"Unknown question recorded: {question}")
#     # Optionally write to a local file for audits
#     os.makedirs("me/logs", exist_ok=True)
#     with open("me/logs/unknown_questions.txt", "a", encoding="utf-8") as f:
#         f.write(question.strip() + "\n")
#     return {"recorded": "ok", "question": question}

# def search_faq(query):
#     db_path = os.path.join("me", "qa.db")
#     if not os.path.exists(db_path):
#         return {"answer": "FAQ database not found."}
#     conn = sqlite3.connect(db_path)
#     cur = conn.cursor()
#     cur.execute("SELECT answer FROM faq WHERE question LIKE ? LIMIT 1", (f"%{query}%",))
#     row = cur.fetchone()
#     conn.close()
#     return {"answer": row[0]} if row else {"answer": "not found"}

# # --- Tool JSON metadata (for function-calling style) ---
# record_user_details_json = {
#     "name": "record_user_details",
#     "description": "Record an interested user's email and optional name/notes.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "email": {"type": "string"},
#             "name": {"type": "string"},
#             "notes": {"type": "string"}
#         },
#         "required": ["email"],
#         "additionalProperties": False
#     }
# }

# record_unknown_question_json = {
#     "name": "record_unknown_question",
#     "description": "Record any question the assistant could not answer.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "question": {"type": "string"}
#         },
#         "required": ["question"],
#         "additionalProperties": False
#     }
# }

# search_faq_json = {
#     "name": "search_faq",
#     "description": "Search the FAQ database for a question.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "query": {"type": "string"}
#         },
#         "required": ["query"],
#         "additionalProperties": False
#     }
# }

# tools = [
#     {"type": "function", "function": record_user_details_json},
#     {"type": "function", "function": record_unknown_question_json},
#     {"type": "function", "function": search_faq_json}
# ]

# # --- The assistant class ---
# class Me:
#     def __init__(self):
#         self.openai = gemini
#         self.name = "AKASH M J"

#         # Load profile PDF into self.linkedin
#         self.linkedin = ""
#         try:
#             reader = PdfReader(os.path.join("me", "Profile.pdf"))
#             for page in reader.pages:
#                 text = page.extract_text()
#                 if text:
#                     self.linkedin += text + "\n"
#         except Exception as e:
#             print("Could not read Profile.pdf:", e)

#         # Load summary
#         try:
#             with open(os.path.join("me", "summary.txt"), "r", encoding="utf-8") as f:
#                 self.summary = f.read()
#         except Exception as e:
#             print("Could not read summary.txt:", e)
#             self.summary = ""

#         # Load knowledge files (RAG-style simple concatenation)
#         self.knowledge = ""
#         kb_dir = os.path.join("me", "knowledge")
#         if os.path.exists(kb_dir):
#             for fn in sorted(os.listdir(kb_dir)):
#                 path = os.path.join(kb_dir, fn)
#                 try:
#                     with open(path, "r", encoding="utf-8") as f:
#                         self.knowledge += f"# {fn}\n" + f.read() + "\n\n"
#                 except Exception as e:
#                     print("Error reading", path, e)

#     def system_prompt(self):
#         system_prompt = (
#             f"You are acting as {self.name}. Answer questions about {self.name}'s background "
#             "and experience using the context provided. Be professional and concise. "
#             "If you don't know an answer, use the record_unknown_question tool."
#         )
#         system_prompt += f"\n\n## Summary:\n{self.summary}\n\n"
#         system_prompt += f"## LinkedIn profile (extracted):\n{self.linkedin}\n\n"
#         system_prompt += f"## Knowledge base:\n{self.knowledge}\n\n"
#         return system_prompt

#     def handle_tool_call(self, tool_calls):
#         results = []
#         for tool_call in tool_calls:
#             tool_name = tool_call.function.name
#             try:
#                 arguments = json.loads(tool_call.function.arguments)
#             except Exception:
#                 arguments = {}
#             print("Tool called:", tool_name, arguments, flush=True)
#             tool = globals().get(tool_name)
#             result = tool(**arguments) if tool else {}
#             results.append({
#                 "role": "tool",
#                 "content": json.dumps(result),
#                 "tool_call_id": tool_call.id
#             })
#         return results

#     # Simple router/orchestrator: route common queries to the FAQ or to the LLM
#     def route_question(self, question):
#         q = question.lower()
#         # keywords that map to FAQ
#         faq_keywords = ["project", "tech stack", "stack", "skill", "skills", "study", "education", "experience"]
#         if any(k in q for k in faq_keywords):
#             return "search_faq"
#         return None

#     def evaluate_answer(self, user_question, ai_answer):
#         # Simple evaluator: ask the LLM to judge the quality
#         eval_prompt = f"""
# You are an evaluator. Judge whether the assistant reply is clear, correct, and complete for the user question.
# Return exactly PASS or FAIL and a one-line reason.

# User question:
# {user_question}

# Assistant reply:
# {ai_answer}
# """
#         try:
#             ev = self.openai.chat.completions.create(
#                 model="gemini-2.0-flash",
#                 messages=[{"role":"system","content":"You are an evaluator."},
#                           {"role":"user","content":eval_prompt}]
#             )
#             text = ev.choices[0].message.content.strip()
#             # very simple parse
#             if text.upper().startswith("PASS"):
#                 return {"result":"PASS", "note": text}
#             else:
#                 return {"result":"FAIL", "note": text}
#         except Exception as e:
#             print("Evaluator failed:", e)
#             return {"result":"UNKNOWN", "note": str(e)}

#     def chat(self, message, history):
#         # build messages with system prompt + history + user
#         messages = [{"role":"system","content":self.system_prompt()}] + history + [{"role":"user","content":message}]

#         # 1) Router: check if the question should use the FAQ tool
#         tool_to_use = self.route_question(message)
#         if tool_to_use == "search_faq":
#             # call tool directly and return evaluated answer
#             tool_result = search_faq(message)
#             raw_answer = tool_result.get("answer", "I don't have that in my FAQ.")
#             eval_res = self.evaluate_answer(message, raw_answer)
#             if eval_res["result"] == "PASS":
#                 return raw_answer
#             else:
#                 # fall back to LLM if FAIL
#                 pass

#         # 2) Normal LLM flow with tools support (function-calling style)
#         done = False
#         while not done:
#             response = self.openai.chat.completions.create(
#                 model="gemini-2.0-flash",
#                 messages=messages,
#                 tools=tools
#             )

#             finish = response.choices[0].finish_reason
#             if finish == "tool_calls":
#                 # the LLM asked to call a tool
#                 message_obj = response.choices[0].message
#                 tool_calls = getattr(message_obj, "tool_calls", [])
#                 results = self.handle_tool_call(tool_calls)
#                 messages.append(message_obj)
#                 messages.extend(results)
#                 # loop again so the LLM can consume tool outputs
#             else:
#                 done = True

#         ai_answer = response.choices[0].message.content
#         # 3) Evaluate the answer; if FAIL, ask LLM to improve
#         eval_res = self.evaluate_answer(message, ai_answer)
#         if eval_res["result"] == "FAIL":
#             # ask the model to improve using the critique
#             improve_prompt = f"User question:\n{message}\n\nAssistant previous reply:\n{ai_answer}\n\nEvaluator note:\n{eval_res['note']}\n\nPlease produce an improved concise answer."
#             messages.append({"role":"user","content":improve_prompt})
#             improved_resp = self.openai.chat.completions.create(model="gemini-2.0-flash", messages=messages)
#             ai_answer = improved_resp.choices[0].message.content

#         return ai_answer

# # --- Launch ---
# if __name__ == "__main__":
#     me = Me()
#     gr.ChatInterface(me.chat, type="messages").launch()
#     # gr.ChatInterface(me.chat).launch()






# # openAI router using Gemini
# # app.py
# from dotenv import load_dotenv
# from openai import OpenAI
# import json
# import os
# import requests
# from pypdf import PdfReader
# import gradio as gr
# import sqlite3
# import time

# load_dotenv(override=True)

# # --- CONFIG (OpenRouter instead of Google Gemini) ---
# OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
# openrouter_api_key = os.getenv("OPENROUTER_API_KEY")

# # Initialize OpenRouter client
# gemini = OpenAI(
#     base_url=OPENROUTER_BASE_URL,
#     api_key=openrouter_api_key,
#     default_headers={
#         "HTTP-Referer": "http://localhost",  # required by OpenRouter
#         "X-Title": "My-Gemini-App"
#     }
# )

# # --- Pushover helper ---
# def push(text):
#     token = os.getenv("PUSHOVER_TOKEN")
#     user = os.getenv("PUSHOVER_USER")
#     if not token or not user:
#         print("Pushover credentials not set. Skipping push.")
#         return
#     try:
#         requests.post(
#             "https://api.pushover.net/1/messages.json",
#             data={"token": token, "user": user, "message": text},
#             timeout=5
#         )
#     except Exception as e:
#         print("Pushover error:", e)

# # --- Tools ---
# def record_user_details(email, name="Name not provided", notes="not provided"):
#     push(f"Recording contact: {name} <{email}> notes: {notes}")
#     return {"recorded": "ok", "email": email, "name": name}

# def record_unknown_question(question):
#     push(f"Unknown question recorded: {question}")
#     os.makedirs("me/logs", exist_ok=True)
#     with open("me/logs/unknown_questions.txt", "a", encoding="utf-8") as f:
#         f.write(question.strip() + "\n")
#     return {"recorded": "ok", "question": question}

# def search_faq(query):
#     db_path = os.path.join("me", "qa.db")
#     if not os.path.exists(db_path):
#         return {"answer": "FAQ database not found."}
#     conn = sqlite3.connect(db_path)
#     cur = conn.cursor()
#     cur.execute("SELECT answer FROM faq WHERE question LIKE ? LIMIT 1", (f"%{query}%",))
#     row = cur.fetchone()
#     conn.close()
#     return {"answer": row[0]} if row else {"answer": "not found"}

# # --- Tool JSON metadata ---
# record_user_details_json = {
#     "name": "record_user_details",
#     "description": "Record an interested user's email and optional name/notes.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "email": {"type": "string"},
#             "name": {"type": "string"},
#             "notes": {"type": "string"}
#         },
#         "required": ["email"],
#         "additionalProperties": False
#     }
# }

# record_unknown_question_json = {
#     "name": "record_unknown_question",
#     "description": "Record any question the assistant could not answer.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "question": {"type": "string"}
#         },
#         "required": ["question"],
#         "additionalProperties": False
#     }
# }

# search_faq_json = {
#     "name": "search_faq",
#     "description": "Search the FAQ database for a question.",
#     "parameters": {
#         "type": "object",
#         "properties": {
#             "query": {"type": "string"}
#         },
#         "required": ["query"],
#         "additionalProperties": False
#     }
# }

# tools = [
#     {"type": "function", "function": record_user_details_json},
#     {"type": "function", "function": record_unknown_question_json},
#     {"type": "function", "function": search_faq_json}
# ]

# # --- The assistant class ---
# class Me:
#     def __init__(self):
#         self.openai = gemini
#         self.name = "AKASH M J"

#         self.linkedin = ""
#         try:
#             reader = PdfReader(os.path.join("me", "Profile.pdf"))
#             for page in reader.pages:
#                 text = page.extract_text()
#                 if text:
#                     self.linkedin += text + "\n"
#         except Exception as e:
#             print("Could not read Profile.pdf:", e)

#         try:
#             with open(os.path.join("me", "summary.txt"), "r", encoding="utf-8") as f:
#                 self.summary = f.read()
#         except:
#             self.summary = ""

#         self.knowledge = ""
#         kb_dir = os.path.join("me", "knowledge")
#         if os.path.exists(kb_dir):
#             for fn in sorted(os.listdir(kb_dir)):
#                 try:
#                     with open(os.path.join(kb_dir, fn), "r", encoding="utf-8") as f:
#                         self.knowledge += f"# {fn}\n" + f.read() + "\n\n"
#                 except:
#                     pass

#     def system_prompt(self):
#         system_prompt = (
#             f"You are acting as {self.name}. Answer questions about {self.name}'s background."
#         )
#         system_prompt += f"\n\n## Summary:\n{self.summary}\n\n"
#         system_prompt += f"## LinkedIn profile:\n{self.linkedin}\n\n"
#         system_prompt += f"## Knowledge base:\n{self.knowledge}\n\n"
#         return system_prompt

#     def handle_tool_call(self, tool_calls):
#         results = []
#         for tool_call in tool_calls:
#             tool_name = tool_call.function.name
#             arguments = json.loads(tool_call.function.arguments)
#             tool = globals().get(tool_name)
#             result = tool(**arguments) if tool else {}
#             results.append({
#                 "role": "tool",
#                 "content": json.dumps(result),
#                 "tool_call_id": tool_call.id
#             })
#         return results

#     def route_question(self, q):
#         q = q.lower()
#         faq_keywords = ["project", "skills", "experience", "study", "education"]
#         if any(k in q for k in faq_keywords):
#             return "search_faq"
#         return None

#     def evaluate_answer(self, user_question, ai_answer):
#         eval_prompt = f"""
# Evaluate if the answer is good. Respond with PASS or FAIL.

# User question:
# {user_question}

# Assistant reply:
# {ai_answer}
# """
#         try:
#             ev = self.openai.chat.completions.create(
#                 model="google/gemini-2.0-flash-exp:free",
#                 messages=[
#                     {"role": "system", "content": "You are an evaluator."},
#                     {"role": "user", "content": eval_prompt}
#                 ]
#             )
#             text = ev.choices[0].message.content.strip()
#             if text.upper().startswith("PASS"):
#                 return {"result": "PASS", "note": text}
#             return {"result": "FAIL", "note": text}
#         except Exception as e:
#             return {"result": "UNKNOWN", "note": str(e)}

#     def chat(self, message, history):
#         messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}]

#         tool_to_use = self.route_question(message)
#         if tool_to_use == "search_faq":
#             tool_result = search_faq(message)
#             ans = tool_result.get("answer", "not found")
#             if self.evaluate_answer(message, ans)["result"] == "PASS":
#                 return ans

#         done = False
#         while not done:
#             response = self.openai.chat.completions.create(
#                 model="google/gemini-2.0-flash-exp:free",
#                 messages=messages,
#                 tools=tools
#             )
#             finish = response.choices[0].finish_reason

#             if finish == "tool_calls":
#                 tool_calls = response.choices[0].message.tool_calls
#                 results = self.handle_tool_call(tool_calls)
#                 messages.append(response.choices[0].message)
#                 messages.extend(results)
#             else:
#                 done = True

#         ai_answer = response.choices[0].message.content
#         eval_res = self.evaluate_answer(message, ai_answer)
#         if eval_res["result"] == "FAIL":
#             improve_prompt = f"Improve this answer:\n{ai_answer}\n\nCritique:\n{eval_res['note']}"
#             messages.append({"role": "user", "content": improve_prompt})
#             improved = self.openai.chat.completions.create(
#                 model="google/gemini-2.0-flash-exp:free",
#                 messages=messages
#             )
#             ai_answer = improved.choices[0].message.content

#         return ai_answer


# # --- Launch ---
# if __name__ == "__main__":
#     me = Me()
#     gr.ChatInterface(me.chat, type="messages").launch()




# openAI router using openai/gpt-oss-120b:free


from dotenv import load_dotenv
from openai import OpenAI
import json
import os
import requests
from pypdf import PdfReader
import gradio as gr
import sqlite3
import time

load_dotenv(override=True)

# -------------------------------------------------------------------
# OPENROUTER CONFIG
# -------------------------------------------------------------------
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")

openrouter = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=OPENROUTER_API_KEY
)

# Your chosen free model on OpenRouter
MODEL_NAME = "openai/gpt-oss-120b:free"

# -------------------------------------------------------------------
# Pushover helper
# -------------------------------------------------------------------
def push(text):
    token = os.getenv("PUSHOVER_TOKEN")
    user = os.getenv("PUSHOVER_USER")
    if not token or not user:
        print("Pushover credentials not set. Skipping push.")
        return
    try:
        requests.post(
            "https://api.pushover.net/1/messages.json",
            data={"token": token, "user": user, "message": text},
            timeout=5
        )
    except Exception as e:
        print("Pushover error:", e)

# -------------------------------------------------------------------
# TOOLS
# -------------------------------------------------------------------
def record_user_details(email, name="Name not provided", notes="not provided"):
    push(f"Recording contact: {name} <{email}> notes: {notes}")
    return {"recorded": "ok", "email": email, "name": name}

def record_unknown_question(question):
    push(f"Unknown question recorded: {question}")
    os.makedirs("me/logs", exist_ok=True)
    with open("me/logs/unknown_questions.txt", "a", encoding="utf-8") as f:
        f.write(question.strip() + "\n")
    return {"recorded": "ok", "question": question}

def search_faq(query):
    db_path = os.path.join("me", "qa.db")
    if not os.path.exists(db_path):
        return {"answer": "FAQ database not found."}
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    cur.execute("SELECT answer FROM faq WHERE question LIKE ? LIMIT 1", (f"%{query}%",))
    row = cur.fetchone()
    conn.close()
    return {"answer": row[0]} if row else {"answer": "not found"}

# Tool JSON
record_user_details_json = {
    "name": "record_user_details",
    "description": "Record an interested user's email and optional name/notes.",
    "parameters": {
        "type": "object",
        "properties": {
            "email": {"type": "string"},
            "name": {"type": "string"},
            "notes": {"type": "string"}
        },
        "required": ["email"],
        "additionalProperties": False
    }
}

record_unknown_question_json = {
    "name": "record_unknown_question",
    "description": "Record any question the assistant could not answer.",
    "parameters": {
        "type": "object",
        "properties": {
            "question": {"type": "string"}
        },
        "required": ["question"],
        "additionalProperties": False
    }
}

search_faq_json = {
    "name": "search_faq",
    "description": "Search the FAQ database for a question.",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {"type": "string"}
        },
        "required": ["query"],
        "additionalProperties": False
    }
}

tools = [
    {"type": "function", "function": record_user_details_json},
    {"type": "function", "function": record_unknown_question_json},
    {"type": "function", "function": search_faq_json}
]

# -------------------------------------------------------------------
# MAIN ASSISTANT CLASS
# -------------------------------------------------------------------
class Me:
    def __init__(self):
        self.openai = openrouter  # <--- using OpenRouter
        self.name = "AKASH M J"

        # Load PDF profile
        self.linkedin = ""
        try:
            reader = PdfReader(os.path.join("me", "Profile.pdf"))
            for page in reader.pages:
                text = page.extract_text()
                if text:
                    self.linkedin += text + "\n"
        except Exception as e:
            print("Could not read Profile.pdf:", e)

        # Load summary
        try:
            with open(os.path.join("me", "summary.txt"), "r", encoding="utf-8") as f:
                self.summary = f.read()
        except Exception as e:
            print("Could not read summary.txt:", e)
            self.summary = ""

        # Load knowledge files
        self.knowledge = ""
        kb_dir = os.path.join("me", "knowledge")
        if os.path.exists(kb_dir):
            for fn in sorted(os.listdir(kb_dir)):
                path = os.path.join(kb_dir, fn)
                try:
                    with open(path, "r", encoding="utf-8") as f:
                        self.knowledge += f"# {fn}\n" + f.read() + "\n\n"
                except Exception as e:
                    print("Error reading", path, e)

    def system_prompt(self):
        system_prompt = (
            f"You are acting as {self.name}. Answer questions about {self.name}'s "
            "background and experience using the context provided. Be professional. "
            "If unsure, use record_unknown_question."
        )
        system_prompt += f"\n\n## Summary:\n{self.summary}\n\n"
        system_prompt += f"## LinkedIn:\n{self.linkedin}\n\n"
        system_prompt += f"## Knowledge:\n{self.knowledge}\n\n"
        return system_prompt

    def handle_tool_call(self, tool_calls):
        results = []
        for tool_call in tool_calls:
            tool_name = tool_call.function.name
            try:
                arguments = json.loads(tool_call.function.arguments)
            except Exception:
                arguments = {}
            print("Tool called:", tool_name, arguments, flush=True)
            tool = globals().get(tool_name)
            result = tool(**arguments) if tool else {}
            results.append({
                "role": "tool",
                "content": json.dumps(result),
                "tool_call_id": tool_call.id
            })
        return results

    # Router for FAQ
    def route_question(self, question):
        q = question.lower()
        faq_keywords = ["project", "tech stack", "skill", "education", "experience"]
        if any(k in q for k in faq_keywords):
            return "search_faq"
        return None

    # Evaluator
    def evaluate_answer(self, user_question, ai_answer):
        eval_prompt = f"""

Evaluate the answer clarity and correctness.

Return PASS or FAIL and one-line reason.



Question: {user_question}

Answer: {ai_answer}

"""
        try:
            ev = self.openai.chat.completions.create(
                model=MODEL_NAME,
                messages=[
                    {"role": "system", "content": "You are an evaluator."},
                    {"role": "user", "content": eval_prompt}
                ]
            )
            text = ev.choices[0].message.content.strip()
            if text.upper().startswith("PASS"):
                return {"result": "PASS", "note": text}
            else:
                return {"result": "FAIL", "note": text}
        except Exception as e:
            return {"result": "UNKNOWN", "note": str(e)}

    # Chat
    def chat(self, message, history):
        messages = [{"role":"system","content":self.system_prompt()}] + history + [{"role":"user","content":message}]

        # Router: FAQ
        tool_to_use = self.route_question(message)
        if tool_to_use == "search_faq":
            tool_result = search_faq(message)
            raw_answer = tool_result.get("answer", "Not found.")
            ev = self.evaluate_answer(message, raw_answer)
            if ev["result"] == "PASS":
                return raw_answer

        # LLM with tools
        done = False
        while not done:
            response = self.openai.chat.completions.create(
                model=MODEL_NAME,
                messages=messages,
                tools=tools
            )

            finish = response.choices[0].finish_reason
            if finish == "tool_calls":
                msg = response.choices[0].message
                tool_calls = getattr(msg, "tool_calls", [])
                results = self.handle_tool_call(tool_calls)
                messages.append(msg)
                messages.extend(results)
            else:
                done = True

        ai_answer = response.choices[0].message.content

        # Evaluate
        eval_res = self.evaluate_answer(message, ai_answer)
        if eval_res["result"] == "FAIL":
            improve_prompt = (
                f"User question:\n{message}\n\n"
                f"Previous answer:\n{ai_answer}\n\n"
                f"Evaluator note:\n{eval_res['note']}\n\n"
                "Please provide an improved answer."
            )
            messages.append({"role": "user", "content": improve_prompt})
            improved_resp = self.openai.chat.completions.create(
                model=MODEL_NAME, messages=messages
            )
            ai_answer = improved_resp.choices[0].message.content

        return ai_answer

# -------------------------------------------------------------------
# GRADIO LAUNCH
# -------------------------------------------------------------------
if __name__ == "__main__":
    me = Me()
    # gr.ChatInterface(me.chat, type="messages").launch()
    gr.ChatInterface(me.chat).launch()