Spaces:
Sleeping

sariskiat commited on
Commit
448d9f4
·
verified ·
1 Parent(s): e65b02e

Update rag_agent/tools/rag_query.py

Browse files
Files changed (1) hide show
  1. rag_agent/tools/rag_query.py +61 -78
rag_agent/tools/rag_query.py CHANGED
@@ -3,7 +3,33 @@ Tool for querying Vertex AI RAG corpora and retrieving relevant information.
3
  """
4
 
5
  from vertexai import rag
 
 
 
 
 
 
6
  from vertexai.generative_models import GenerativeModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  from ..config import (
9
  DEFAULT_DISTANCE_THRESHOLD,
@@ -16,25 +42,7 @@ def rag_query(
16
  query: str,
17
  type: str,
18
  ) -> dict:
19
- """
20
- Executes a RAG retrieval query against a predefined Vertex AI corpus.
21
-
22
- The query is routed to one of three document groups—business, product, or
23
- service—based on the specified type. The function retrieves the top matching
24
- contexts and returns them in a simplified dictionary format.
25
-
26
- Args:
27
- query: The user's question to retrieve information for.
28
- type: Query category. One of {"business", "product", "service"}.
29
-
30
- Returns:
31
- A dictionary containing processed retrieval results, including text,
32
- source metadata, and relevance scores.
33
-
34
- Raises:
35
- ValueError: If `type` is not a valid category.
36
- """
37
- # In-tool guardrail: Screen input queries not related to the rag_agent app
38
  model = GenerativeModel("gemini-1.5-flash")
39
  prompt = f"""
40
  Determine if the following query is related to business, products, or services of a company.
@@ -49,76 +57,52 @@ def rag_query(
49
  # If Gemini call fails, allow to proceed
50
  pass
51
 
52
- corpus = rag.get_corpus("projects/38827506989/locations/asia-southeast1/ragCorpora/3458764513820540928")
53
  if type == "business":
54
- response = rag.retrieval_query(
55
- rag_resources=[
56
- rag.RagResource(
57
- rag_corpus=corpus.name,
58
- rag_file_ids=["5572399974328298423"]
59
- )
60
- ],
61
- rag_retrieval_config=rag.RagRetrievalConfig(
62
- top_k = DEFAULT_BUSINESS_TOP_K,
63
- filter=rag.Filter(
64
- vector_distance_threshold = DEFAULT_DISTANCE_THRESHOLD,
65
- ),
66
- ),
67
- text=query,
68
  )
69
  print(response)
70
  elif type == "product":
71
- response = rag.retrieval_query(
72
- rag_resources=[
73
- rag.RagResource(
74
- rag_corpus=corpus.name,
75
- rag_file_ids=["5572400164943779227"]
76
- )
77
- ],
78
- rag_retrieval_config=rag.RagRetrievalConfig(
79
- top_k = DEFAULT_PRODUCT_TOP_K,
80
- filter=rag.Filter(
81
- vector_distance_threshold = DEFAULT_DISTANCE_THRESHOLD,
82
- ),
83
- ),
84
- text=query,
85
  )
86
  print(response)
87
  elif type == "service":
88
- response = rag.retrieval_query(
89
- rag_resources=[
90
- rag.RagResource(
91
- rag_corpus=corpus.name,
92
- rag_file_ids=["5572400273133586357"]
93
- )
94
- ],
95
- rag_retrieval_config=rag.RagRetrievalConfig(
96
- top_k = DEFAULT_SERVICE_TOP_K,
97
- filter=rag.Filter(
98
- vector_distance_threshold = DEFAULT_DISTANCE_THRESHOLD,
99
- ),
100
- ),
101
- text=query,
102
  )
103
  print(response)
104
 
105
  results = []
106
- if hasattr(response, "contexts") and response.contexts:
107
- for ctx_group in response.contexts.contexts:
108
- result = {
109
- "source_uri": (
110
- ctx_group.source_uri if hasattr(ctx_group, "source_uri") else ""
111
- ),
112
- "source_name": (
113
- ctx_group.source_display_name
114
- if hasattr(ctx_group, "source_display_name")
115
- else ""
116
- ),
117
- "text": ctx_group.text if hasattr(ctx_group, "text") else "",
118
- "score": ctx_group.score if hasattr(ctx_group, "score") else 0.0,
119
  }
120
- results.append(result)
121
- # In-tool guardrail: Screen output results not relevant to the query
 
122
  if results:
123
  texts = [r["text"] for r in results if r["text"]]
124
  combined_text = " ".join(texts[:3]) # check first 3 texts
@@ -134,5 +118,4 @@ def rag_query(
134
  return {"error": "ข้อมูลที่ดึงมาไม่เกี่ยวข้องกับคำถามของคุณ ขอโทษครับ ฉันสามารถช่วยเหลือได้เฉพาะคำถามที่เกี่ยวข้องกับธุรกิจ สินค้า หรือบริการของบริษัทเท่านั้น"}
135
  except Exception:
136
  pass
137
- print(results)
138
  return results
 
3
  """
4
 
5
  from vertexai import rag
6
+
7
+ import configparser
8
+ from openai import OpenAI
9
+
10
+ from pymilvus import MilvusClient
11
+ from pymilvus import DataType
12
  from vertexai.generative_models import GenerativeModel
13
+ import json
14
+
15
+ cfp = configparser.RawConfigParser()
16
+
17
+ milvus_uri = "https://in03-6df450fd51eb74c.serverless.gcp-us-west1.cloud.zilliz.com"
18
+ token = "48c398b27df543cf49608f5399d157f40346d4b7b6d93aa592210cd4356d55183f1dd11516b41666c57775a267839b8c6dd6b1b6"
19
+ api_key = "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"
20
+
21
+
22
+ milvus_client = MilvusClient(
23
+ uri=milvus_uri,
24
+ user="db_6df450fd51eb74c",
25
+ password="Hv0../Lue;2T(-*/",
26
+ )
27
+ print(f"Connected to DB: {milvus_uri} successfully")
28
+
29
+ client = OpenAI(api_key=api_key)
30
+
31
+ def get_embedding(text, model="text-embedding-3-large"):
32
+ return client.embeddings.create(input = [text], model=model).data[0].embedding
33
 
34
  from ..config import (
35
  DEFAULT_DISTANCE_THRESHOLD,
 
42
  query: str,
43
  type: str,
44
  ) -> dict:
45
+ search_params = {"metric_type": "L2", "params": {"level": 2}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  model = GenerativeModel("gemini-1.5-flash")
47
  prompt = f"""
48
  Determine if the following query is related to business, products, or services of a company.
 
57
  # If Gemini call fails, allow to proceed
58
  pass
59
 
 
60
  if type == "business":
61
+ search_vectors = [get_embedding(query)]
62
+ response = milvus_client.search(
63
+ "business_info",
64
+ data=search_vectors,
65
+ limit=DEFAULT_BUSINESS_TOP_K,
66
+ search_params=search_params,
67
+ anns_field="business_info",
68
+ output_fields=["text"]
 
 
 
 
 
 
69
  )
70
  print(response)
71
  elif type == "product":
72
+ search_vectors = [get_embedding(query)]
73
+ response = milvus_client.search(
74
+ "product_info",
75
+ data=search_vectors,
76
+ limit=DEFAULT_PRODUCT_TOP_K,
77
+ search_params=search_params,
78
+ anns_field="product_info",
79
+ output_fields=["text"]
 
 
 
 
 
 
80
  )
81
  print(response)
82
  elif type == "service":
83
+ search_vectors = [get_embedding(query)]
84
+ response = milvus_client.search(
85
+ "service_info",
86
+ data=search_vectors,
87
+ limit=DEFAULT_SERVICE_TOP_K,
88
+ search_params=search_params,
89
+ anns_field="service_info",
90
+ output_fields=["text"]
 
 
 
 
 
 
91
  )
92
  print(response)
93
 
94
  results = []
95
+
96
+ for hits in response:
97
+ for hit in hits:
98
+ item = {
99
+ "id": hit.get("id"),
100
+ "text": hit.get("entity", {}).get("text", ""),
101
+ "score": hit.get("distance"),
 
 
 
 
 
 
102
  }
103
+ results.append(item)
104
+
105
+ print(results)
106
  if results:
107
  texts = [r["text"] for r in results if r["text"]]
108
  combined_text = " ".join(texts[:3]) # check first 3 texts
 
118
  return {"error": "ข้อมูลที่ดึงมาไม่เกี่ยวข้องกับคำถามของคุณ ขอโทษครับ ฉันสามารถช่วยเหลือได้เฉพาะคำถามที่เกี่ยวข้องกับธุรกิจ สินค้า หรือบริการของบริษัทเท่านั้น"}
119
  except Exception:
120
  pass
 
121
  return results