Formats the raw JSON response from Serper.dev into a structured string.
(data: dict)
| 40 | |
| 41 | |
| 42 | def __format_serper_results(data: dict) -> str: |
| 43 | """ |
| 44 | Formats the raw JSON response from Serper.dev into a structured string. |
| 45 | """ |
| 46 | formatted_output = [] |
| 47 | |
| 48 | # 1. Knowledge Graph |
| 49 | if "knowledgeGraph" in data: |
| 50 | kg = data["knowledgeGraph"] |
| 51 | formatted_output.append("## Knowledge Graph") |
| 52 | if "title" in kg: |
| 53 | formatted_output.append(f"**Title**: {kg['title']}") |
| 54 | if "type" in kg: |
| 55 | formatted_output.append(f"**Type**: {kg['type']}") |
| 56 | if "description" in kg: |
| 57 | if "descriptionSource" in kg and "descriptionLink" in kg: |
| 58 | formatted_output.append(f"**Description**: {kg['description']} (Source: [{kg['descriptionSource']}]({kg['descriptionLink']}))") |
| 59 | else: |
| 60 | formatted_output.append(f"**Description**: {kg['description']}") |
| 61 | |
| 62 | if "attributes" in kg: |
| 63 | formatted_output.append("**Attributes**:") |
| 64 | for key, value in kg["attributes"].items(): |
| 65 | formatted_output.append(f"- {key}: {value}") |
| 66 | formatted_output.append("") # Add spacing |
| 67 | |
| 68 | # 2. Organic Results |
| 69 | if "organic" in data and data["organic"]: |
| 70 | formatted_output.append("## Organic Results") |
| 71 | for i, result in enumerate(data["organic"], 1): |
| 72 | title = result.get("title", "No Title") |
| 73 | link = result.get("link", "#") |
| 74 | snippet = result.get("snippet", "") |
| 75 | formatted_output.append(f"{i}. **[{title}]({link})**") |
| 76 | if snippet: |
| 77 | formatted_output.append(f" {snippet}") |
| 78 | |
| 79 | # Optional: Include attributes if useful, but keep it concise |
| 80 | if "attributes" in result: |
| 81 | for key, value in result["attributes"].items(): |
| 82 | formatted_output.append(f" - {key}: {value}") |
| 83 | formatted_output.append("") |
| 84 | |
| 85 | # 3. People Also Ask |
| 86 | if "peopleAlsoAsk" in data and data["peopleAlsoAsk"]: |
| 87 | formatted_output.append("## People Also Ask") |
| 88 | for item in data["peopleAlsoAsk"]: |
| 89 | question = item.get("question") |
| 90 | snippet = item.get("snippet") |
| 91 | link = item.get("link") |
| 92 | title = item.get("title") |
| 93 | |
| 94 | if question: |
| 95 | formatted_output.append(f"- **{question}**") |
| 96 | if snippet: |
| 97 | formatted_output.append(f" {snippet}") |
| 98 | if link and title: |
| 99 | formatted_output.append(f" Source: [{title}]({link})") |
no test coverage detected