Wajahat698 commited on
Commit
fe06e19
·
verified ·
1 Parent(s): bfedf34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -25
app.py CHANGED
@@ -1025,39 +1025,55 @@ def search_knowledge_base(query):
1025
  return retrieved_docs
1026
 
1027
  def google_search(query):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1028
  try:
1029
- # Initialize the search client and parameters
1030
- search_client = serpapi.Client(api_key=serper_api_key)
1031
- search_params = {
1032
- "engine": "google",
1033
- "q": query,
1034
- "sort": "date", # Sort results by date for freshness
1035
- "hl": "en", # Language: English
1036
- "gl": "us", # Geolocation: United States
1037
  }
1038
 
1039
- # Perform the search
1040
- results = search_client.search(search_params)
1041
- organic_results = results.get("organic_results", [])
1042
- formatted_results = []
1043
 
1044
- for result in organic_results:
1045
- link = result.get("link", "")
1046
- snippet = result.get("snippet", "")
 
1047
 
1048
- # Ensure proper Markdown formatting with only "Source" as the clickable text
1049
- if link.startswith("http"):
1050
- formatted_results.append(f"{snippet} - [Source]({link})")
1051
-
1052
- if formatted_results:
1053
- return formatted_results
1054
- return ["No valid links found"]
1055
 
 
 
 
 
 
 
1056
  except Exception as e:
1057
- logger.error(f"Error in Google search: {e}")
 
1058
  return ["Error occurred during Google search"]
1059
 
1060
 
 
1061
  def rag_response(query):
1062
  """
1063
  Handle queries by searching both static and dynamically uploaded knowledge bases.
@@ -1104,8 +1120,24 @@ def google_search_tool(query: str):
1104
  """Perform a Google search using the SERPER API."""
1105
  return google_search(query)
1106
 
1107
- tools = [knowledge_base_tool, google_search_tool]
1108
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1109
  prompt_message = f"""
1110
  ** You are a Professional copywriter tasked with creating non-flowery fluid, interconnected marketing content that integrates Trust Builders into various formats for Volkswagen. Your content should be compelling, factual, well-structured, concise, and based on the knowledgebase. Write in an active voice using the first-person perspective ("we"), and avoid the third-person perspective. Creatively interconnect trust-building elements to enhance flow and impact. Avoid using terms like Stability, Development, Competence, Relationship, Benefit, Vision, trust, beacon, beacon of hope, and realm, except where specified.
1111
 
 
1025
  return retrieved_docs
1026
 
1027
  def google_search(query):
1028
+ """
1029
+ Performs a Google search using the SerpApi service and retrieves search result snippets.
1030
+
1031
+ This function uses the SerpApi client to perform a Google search based on the provided query.
1032
+ It extracts and returns the snippets from the organic search results.
1033
+
1034
+ Args:
1035
+ query (str): The search query to be used for the Google search.
1036
+
1037
+ Returns:
1038
+ list: A list of snippets from the organic search results. If an error occurs, returns a list with an error message.
1039
+
1040
+ Raises:
1041
+ requests.exceptions.HTTPError: If an HTTP error occurs during the search, it is logged and an error message is returned.
1042
+ Exception: For any other general errors, they are logged and an error message is returned.
1043
+ """
1044
  try:
1045
+ # Set up connection to google.serper.dev API
1046
+ conn = http.client.HTTPSConnection("google.serper.dev")
1047
+ payload = json.dumps({"q": query})
1048
+ headers = {
1049
+ "X-API-KEY": "07b4113c2730711b568623b13f7c88078bab9c78",
1050
+ "Content-Type": "application/json",
 
 
1051
  }
1052
 
1053
+ # Send POST request to the API
1054
+ conn.request("POST", "/search", payload, headers)
 
 
1055
 
1056
+ # Get response and decode the data
1057
+ res = conn.getresponse()
1058
+ data = res.read()
1059
+ results = json.loads(data.decode("utf-8"))
1060
 
1061
+ # Extract snippets from organic search results
1062
+ snippets = [result["snippet"] for result in results.get("organic", [])]
 
 
 
 
 
1063
 
1064
+ # Return the list of snippets
1065
+ return snippets
1066
+ except http.client.HTTPException as http_err:
1067
+ # Log HTTP errors and return a specific error message
1068
+ print(f"HTTP error occurred: {http_err}")
1069
+ return ["HTTP error occurred during Google search"]
1070
  except Exception as e:
1071
+ # Log any other general errors and return a generic error message
1072
+ print(f"General Error: {e}")
1073
  return ["Error occurred during Google search"]
1074
 
1075
 
1076
+
1077
  def rag_response(query):
1078
  """
1079
  Handle queries by searching both static and dynamically uploaded knowledge bases.
 
1120
  """Perform a Google search using the SERPER API."""
1121
  return google_search(query)
1122
 
1123
+ tavily_tool = TavilySearchResults(
1124
+ max_results=5,
1125
+ search_depth="advanced",
1126
+ include_answer=True,
1127
+ include_raw_content=True,
1128
+ include_images=True,
1129
+ # include_domains=[...],
1130
+ # exclude_domains=[...],
1131
+ # name="...", # overwrite default tool name
1132
+ # description="...", # overwrite default tool description
1133
+ # args_schema=..., # overwrite default args_schema: BaseModel
1134
+ )
1135
+ # Compile all tool functions into a list
1136
+ tools = [
1137
+ knowledge_base_tool, # Tool for querying the knowledge base and retrieving responses
1138
+ tavily_tool,
1139
+ # google_search_tool, # Tool for performing a Google search and retrieving search result snippets
1140
+ ]
1141
  prompt_message = f"""
1142
  ** You are a Professional copywriter tasked with creating non-flowery fluid, interconnected marketing content that integrates Trust Builders into various formats for Volkswagen. Your content should be compelling, factual, well-structured, concise, and based on the knowledgebase. Write in an active voice using the first-person perspective ("we"), and avoid the third-person perspective. Creatively interconnect trust-building elements to enhance flow and impact. Avoid using terms like Stability, Development, Competence, Relationship, Benefit, Vision, trust, beacon, beacon of hope, and realm, except where specified.
1143