Spaces:
Sleeping
Sleeping
Commit ·
36d2dc6
1
Parent(s): f2524b7
debug news query
Browse filesFiles changed (7)
62 unmodified lines6364656667686962 unmodified lines"chunks": [], # retrieval results can be appended later"needs_news_fetch": analysis.get("needs_news_fetch", False),"news_topic": analysis.get("news_topic", ""),"news_question": analysis.get("news_question", "")}# --- Debug logging ---62 unmodified lines636465666768697062 unmodified lines"chunks": [], # retrieval results can be appended later"needs_news_fetch": analysis.get("needs_news_fetch", False),"news_topic": analysis.get("news_topic", ""),"news_question": analysis.get("news_question", ""),"news_temporal_context": analysis.get("news_temporal_context", "")}# --- Debug logging ---
34 unmodified lines3536373839404152 unmodified lines94959697989910010110210310410510610710810911011132 unmodified lines14414514614714814915034 unmodified lines"topic_for_story": "","needs_news_fetch": False,"news_topic": [],"news_question": ""}, indent=2)system_prompt = f"""52 unmodified lines* Never invent new labels.- needs_news_fetch:* true if the user is clearly asking for news, current events, or external information lookup.* false otherwise.- news_topic:* If needs_news_fetch=true → return a JSON array of 2–3 concise topic labels (e.g. ["US Open", "men's final", "tennis"]).* If false → return [].- news_question:* If needs_news_fetch=true → restate the user’s request as a clear research question.Example: "Who is going to play the US Open final?"* If false → return "".- Do not add any explanation or text outside the JSON."""32 unmodified lines"topic_for_story": "none","needs_news_fetch": False,"news_topic": [],"news_question": ""}34 unmodified lines353637383940414252 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113232 unmodified lines16516616716816917017117234 unmodified lines"topic_for_story": "","needs_news_fetch": False,"news_topic": [],"news_question": "","news_temporal_context": ""}, indent=2)system_prompt = f"""52 unmodified lines* Never invent new labels.- needs_news_fetch:* true if ANY of these apply (regardless of language):- User references something that happened recently: "yesterday", "today", "last night","ieri", "oggi", "hier", "gestern", "ayer", "a few hours ago", "qualche ora fa", etc.- User asks about a sports result, score, match outcome, or team performance.- User implies they heard/saw something recent ("hai sentito?", "did you hear?", "t’as vu?").- User uses sarcasm about a team or event (e.g. "bella figura", "che disastro") implying a recent outcome.- User asks what a country, team, or person "did" or "has done" recently.* Do NOT require the word "news" — infer from context and temporal language.* false only if the question is clearly philosophical, personal, historical, or purely hypothetical.- news_topic:* If needs_news_fetch=true → return a JSON array of 2–3 concise English topic labels.Example: ["Italy", "football", "World Cup qualification"]* If false → return [].- news_question:* ALWAYS write in English, even if the user wrote in another language.* If needs_news_fetch=true → restate the user’s implicit request as a clear, literal research question.Rules:- Decode sarcasm: "bella figura che ha fatto l’Italia" → "bad result for Italy football"- Include subject + event type + temporal hint.- Examples:"cosa ha fatto l’italia ieri?" → "Italy national team result yesterday""bella figura che ha fatto ieri l’italia" → "Italy football bad result yesterday""hai saputo della partita dell’italia contro la bosnia?" → "Italy vs Bosnia football match result"* If false → return "".- news_temporal_context:* Extract the time reference from the user message as a short English string.* Examples: "yesterday", "today", "a few hours ago", "last week", "this morning"* Return "" if no temporal reference is present.- Do not add any explanation or text outside the JSON."""32 unmodified lines"topic_for_story": "none","needs_news_fetch": False,"news_topic": [],"news_question": "","news_temporal_context": ""}
131 unmodified lines13213313413513613713813914014114214314414514682 unmodified lines229230231232233234378 unmodified lines613614615616617618619131 unmodified lines""".strip(),"news": """1. **Primary source**: Use the WEB SEARCH RESULTS (tavily_news) as your main factual source.Do not add outside knowledge not present in these results.2. If no web results are available and db6 has relevant content, use db6 as fallback.3. If neither source has the information, say so briefly — do not invent facts.4. **History Athens (db2)**: include ONLY if directly relevant as a philosophical analogy, not as factual news.5. **Chat memory**: short_term.json for continuity.6. **Long-term memory**: db5 for continuity across sessions.7. **User information**: user_info.json for personalization.8. Maintain Socratic tone while delivering factual news content.""".strip(),"personal": """82 unmodified linesemotion: dict = None,life_events: list = None,past_dialogues: list = None,) -> str:memory_keywords = ["do you remember",378 unmodified linesdb5_block = f"--- LONG-TERM MEMORY (db5) ---\n{db5_text}\n" if db5_text.strip() else ""db6_block = f"(db6: news on tracked topics)\n{db6_text}\n" if db6_text.strip() else ""db8_block = f"(db8: socratic stories – semantic recall)\n{db8_text}\n" if db8_text.strip() else ""tavily_news_block = f"--- WEB SEARCH RESULTS (current news) ---\n{tavily_news_text}\n" if tavily_news_text.strip() else ""secondary_context = "\n".join(filter(None, [db2_block, db3_block, db6_block, db8_block]))secondary_block = f"--- SECONDARY CONTEXT ---\n{secondary_context}" if secondary_context.strip() else ""131 unmodified lines13213313413513613713813914014114214314414514614714814915015182 unmodified lines234235236237238239240378 unmodified lines619620621622623624625626627628629630631131 unmodified lines""".strip(),"news": """1. **Primary source**: Use ONLY the WEB SEARCH RESULTS (tavily_news) for factual claims.NEVER invent scores, outcomes, dates, or facts not present in these results.2. **Date awareness**: Check the published_date of each result.If the user asked about something "yesterday" or "a few hours ago" but the results are from several days ago,acknowledge the mismatch explicitly — e.g. "I found a result from [date] but I am not sure it is what you mean."3. **No results**: If tavily_news is empty AND db6 has nothing relevant, say clearly:"I do not have information about that specific event. Can you tell me more?"Do NOT guess or hallucinate any facts.4. **Sarcasm/irony**: If the user's tone implies a negative outcome (sarcasm like "bella figura"),look for a negative result in the sources. If you only find positive results, express doubt:"I found [X] but it seems positive — is that what you meant, or did something else happen?"5. **Chat memory**: short_term.json for continuity.6. **Long-term memory**: db5 for continuity across sessions.7. Maintain Socratic tone while delivering factual news content.""".strip(),"personal": """82 unmodified linesemotion: dict = None,life_events: list = None,past_dialogues: list = None,news_temporal_context: str = None,) -> str:memory_keywords = ["do you remember",378 unmodified linesdb5_block = f"--- LONG-TERM MEMORY (db5) ---\n{db5_text}\n" if db5_text.strip() else ""db6_block = f"(db6: news on tracked topics)\n{db6_text}\n" if db6_text.strip() else ""db8_block = f"(db8: socratic stories – semantic recall)\n{db8_text}\n" if db8_text.strip() else ""temporal_note = f" | User expected: {news_temporal_context}" if news_temporal_context else ""if tavily_news_text.strip():tavily_news_block = f"--- WEB SEARCH RESULTS (current news{temporal_note}) ---\n{tavily_news_text}\n"elif topic == "news":tavily_news_block = f"--- WEB SEARCH RESULTS (current news{temporal_note}) ---\n[No results found]\n"else:tavily_news_block = ""secondary_context = "\n".join(filter(None, [db2_block, db3_block, db6_block, db8_block]))secondary_block = f"--- SECONDARY CONTEXT ---\n{secondary_context}" if secondary_context.strip() else ""
150 unmodified lines1511521531541551564 unmodified lines161162163164165166167168169168 unmodified lines338339340341342343150 unmodified linesstory = analysis.get("topic_for_story")# ---- fetch news before retrieval so chunks are available for LLM ----news_chunks: list = []if analysis.get("topic") == "news" and analysis.get("needs_news_fetch"):try:4 unmodified linesnews_result = run_tavily_news_pipeline(news_question=analysis.get("news_question", user_msg_en),news_topic=analysis.get("news_topic", []),user_id=user_id,)news_chunks = news_result.get("chunks", [])except Exception as e:print(f"⚠️ [news] Tavily pipeline failed: {e}")168 unmodified linesuser_id=user_id,life_events=life_events,past_dialogues=past_dialogues,)final_reply_display = translate_from_english(150 unmodified lines1511521531541551561574 unmodified lines162163164165166167168169170171172173174168 unmodified lines343344345346347348349150 unmodified linesstory = analysis.get("topic_for_story")# ---- fetch news before retrieval so chunks are available for LLM ----print(f"[DEBUG][classifier] topic={analysis.get('topic')} | needs_news_fetch={analysis.get('needs_news_fetch')} | news_topic={analysis.get('news_topic')} | news_question={analysis.get('news_question')}")news_chunks: list = []if analysis.get("topic") == "news" and analysis.get("needs_news_fetch"):try:4 unmodified linesnews_result = run_tavily_news_pipeline(news_question=analysis.get("news_question", user_msg_en),news_topic=analysis.get("news_topic", []),news_temporal_context=analysis.get("news_temporal_context", ""),user_id=user_id,)news_chunks = news_result.get("chunks", [])print(f"[DEBUG][tavily] status={news_result.get('status')} | articles={news_result.get('articles')} | chunks={len(news_chunks)}")for i, c in enumerate(news_chunks):print(f"[DEBUG][tavily] chunk[{i}] title={c.get('metadata',{}).get('title')} | date={c.get('metadata',{}).get('date')} | score={c.get('score')}")except Exception as e:print(f"⚠️ [news] Tavily pipeline failed: {e}")168 unmodified linesuser_id=user_id,life_events=life_events,past_dialogues=past_dialogues,news_temporal_context=analysis.get("news_temporal_context", ""),)final_reply_display = translate_from_english(
23 unmodified lines2425262728297 unmodified lines37383940414223 unmodified linesemotion=None,life_events=None,past_dialogues=None,):prompt = build_socratic_prompt(7 unmodified linesemotion=emotion,life_events=life_events,past_dialogues=past_dialogues,)constraints = (emotion or {}).get("constraints", {})23 unmodified lines242526272829307 unmodified lines3839404142434423 unmodified linesemotion=None,life_events=None,past_dialogues=None,news_temporal_context=None,):prompt = build_socratic_prompt(7 unmodified linesemotion=emotion,life_events=life_events,past_dialogues=past_dialogues,news_temporal_context=news_temporal_context,)constraints = (emotion or {}).get("constraints", {})
21 unmodified lines222324252627282930313233343570 unmodified lines1061071081091101118 unmodified lines12012112212312412512621 unmodified lines# Search# ---------------------------------------------------------------------------def search_news(news_question: str, days: int = 3, max_results: int = 5) -> list[dict]:"""Run a Tavily news search and return raw results.Each result: {title, url, content (snippet), score, published_date}"""client = TavilyClient(api_key=TAVILY_API_KEY)response = client.search(query=news_question,topic="news",search_depth="basic",max_results=max_results,70 unmodified linesnews_question: str,news_topic: list[str],user_id: str,days: int = 3,max_results: int = 5,) -> dict[str, Any]:8 unmodified lines}"""try:results = search_news(news_question, days=days, max_results=max_results)except Exception as e:print(f"⚠️ [tavily_news] Search failed: {e}")return {"status": "error", "chunks": [], "articles": 0}21 unmodified lines2223242526272829303132333435363738394070 unmodified lines1111121131141151161178 unmodified lines12612712812913013113221 unmodified lines# Search# ---------------------------------------------------------------------------def search_news(news_question: str, temporal_context: str = "", days: int = 3, max_results: int = 5) -> list[dict]:"""Run a Tavily news search and return raw results.Each result: {title, url, content (snippet), score, published_date}temporal_context: e.g. "yesterday", "today", "a few hours ago" — appended to query for recency."""query = news_questionif temporal_context:query = f"{news_question} {temporal_context}"print(f"[DEBUG][tavily] Searching: '{query}' (days={days})")client = TavilyClient(api_key=TAVILY_API_KEY)response = client.search(query=query,topic="news",search_depth="basic",max_results=max_results,70 unmodified linesnews_question: str,news_topic: list[str],user_id: str,news_temporal_context: str = "",days: int = 3,max_results: int = 5,) -> dict[str, Any]:8 unmodified lines}"""try:results = search_news(news_question, temporal_context=news_temporal_context, days=days, max_results=max_results)except Exception as e:print(f"⚠️ [tavily_news] Search failed: {e}")return {"status": "error", "chunks": [], "articles": 0}
Agent_Chat_Classification.py+2-1
Agent_Chat_Classification_Helper.py+29-7
Prompt_building.py+20-8
socrates_core.py → SS/socrates_core.pyRenamed
app_nn.py+6
ask_llm_final_prompt.py+2
tavily_news.py+9-3