Spaces:
Sleeping
Sleeping
| from app.agent.gemini_client import get_client | |
| def refine_answer(user_query: str, tavily_answer: str) -> str: | |
| """ | |
| Refine Tavily's answer using Gemini for better formatting and structure. | |
| """ | |
| client = get_client() | |
| prompt = f"""You are a factual research assistant. You will receive an answer from a web search and need to refine it for better readability. | |
| Rules: | |
| - Keep ALL factual information intact - do not remove any details | |
| - When listing items (languages, products, etc), format as a clear bulleted list with markdown | |
| - Each item should be on its own line with a bullet point (-) | |
| - Add brief context or explanation where helpful | |
| - Make the answer well-structured and easy to scan | |
| - Do not add information not present in the original answer | |
| - Ensure the answer is complete and ends properly | |
| User question: "{user_query}" | |
| Original answer from search: | |
| {tavily_answer} | |
| Refine this answer with proper markdown formatting and clear structure. Make it easy to read while preserving all information. | |
| """ | |
| response = client.models.generate_content( | |
| model="gemini-flash-latest", | |
| contents=prompt, | |
| config={ | |
| "temperature": 0.3, | |
| "max_output_tokens": 2000 | |
| } | |
| ) | |
| raw_text = response.text or "" | |
| if not raw_text.strip(): | |
| return tavily_answer # Fallback to original | |
| return clean_answer(raw_text) | |
| def clean_answer(text: str) -> str: | |
| if not text: | |
| return "No answer could be generated." | |
| text = text.strip() | |
| # Remove incomplete bullet points or dangling text | |
| if text.endswith(":") or text.endswith("("): | |
| # Find the last complete line | |
| lines = text.split("\n") | |
| for i in range(len(lines) - 1, -1, -1): | |
| if lines[i].strip() and not lines[i].strip().endswith(":") and not lines[i].strip().endswith("("): | |
| return "\n".join(lines[:i+1]) | |
| return "Unable to generate a complete answer from the sources." | |
| # Check for incomplete last line (no period, ends mid-word) | |
| lines = text.split("\n") | |
| if lines and lines[-1].strip(): | |
| last_line = lines[-1].strip() | |
| # If last line doesn't end with proper punctuation and looks incomplete | |
| if not any(last_line.endswith(char) for char in ['.', '!', '?', ')', ']', '"', "'"]): | |
| if len(lines) > 1: | |
| return "\n".join(lines[:-1]) | |
| return text | |