Spaces:
Running
Running
Commit
·
3cb103a
1
Parent(s):
7840e50
Add updated app
Browse filesSigned-off-by: Aivin V. Solatorio <avsolatorio@gmail.com>
- app.py +4 -5
- services.py +311 -0
- utils.py +20 -4
- wdi_mcp_gradio.py +223 -0
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
-
def greet(name):
|
| 4 |
-
return "Hello " + name + "!!"
|
| 5 |
|
| 6 |
-
|
| 7 |
-
demo
|
|
|
|
|
|
| 1 |
+
from wdi_mcp_gradio import build_interface
|
| 2 |
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
if __name__ == "__main__":
|
| 5 |
+
demo = build_interface()
|
| 6 |
+
demo.launch(mcp_server=True)
|
services.py
CHANGED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
+
import httpx
|
| 6 |
+
import zlib
|
| 7 |
+
|
| 8 |
+
from typing import Optional, Any
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
|
| 11 |
+
from pydantic import BaseModel, Field
|
| 12 |
+
from urllib.request import urlretrieve
|
| 13 |
+
|
| 14 |
+
from utils import hf_send_post
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_best_torch_device():
|
| 18 |
+
if torch.cuda.is_available():
|
| 19 |
+
return torch.device("cuda")
|
| 20 |
+
elif getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
|
| 21 |
+
return torch.device("mps")
|
| 22 |
+
else:
|
| 23 |
+
return torch.device("cpu")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
device = get_best_torch_device()
|
| 27 |
+
|
| 28 |
+
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
|
| 29 |
+
# sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Load the basic WDI metadata and vectors.
|
| 33 |
+
|
| 34 |
+
# EMBEDDING_FNAME = "avsolatorio__GIST-small-Embedding-v0__005__indicator_embeddings.json"
|
| 35 |
+
EMBEDDING_FNAME = "avsolatorio__GIST-small-Embedding-v0__005__WDI_embeddings.json"
|
| 36 |
+
EMBEDDING_SOURCE = (
|
| 37 |
+
f"https://raw.githubusercontent.com/"
|
| 38 |
+
f"avsolatorio/ai-for-data-blog/refs/heads/main/semantic-search/data/{EMBEDDING_FNAME}"
|
| 39 |
+
)
|
| 40 |
+
wdi_data_vec_fpath = os.path.join("data", EMBEDDING_FNAME)
|
| 41 |
+
|
| 42 |
+
os.makedirs(os.path.dirname(wdi_data_vec_fpath), exist_ok=True)
|
| 43 |
+
|
| 44 |
+
if not os.path.exists(wdi_data_vec_fpath):
|
| 45 |
+
print(f"Downloading {EMBEDDING_FNAME} to {wdi_data_vec_fpath}...")
|
| 46 |
+
urlretrieve(EMBEDDING_SOURCE, wdi_data_vec_fpath)
|
| 47 |
+
print("Download complete.")
|
| 48 |
+
else:
|
| 49 |
+
print(f"File already exists at {wdi_data_vec_fpath}.")
|
| 50 |
+
|
| 51 |
+
df = pd.read_json(wdi_data_vec_fpath)
|
| 52 |
+
|
| 53 |
+
# Make it easy to index based on the idno
|
| 54 |
+
df.index = df["idno"]
|
| 55 |
+
|
| 56 |
+
# Change the IDS naming to metadata standard
|
| 57 |
+
new_columns = {}
|
| 58 |
+
if "title" in df.columns:
|
| 59 |
+
new_columns["title"] = "name"
|
| 60 |
+
if "text" in df.columns:
|
| 61 |
+
new_columns["text"] = "definition"
|
| 62 |
+
|
| 63 |
+
if new_columns:
|
| 64 |
+
df.rename(columns=new_columns, inplace=True)
|
| 65 |
+
|
| 66 |
+
# Extract the vectors into a torch.tensor
|
| 67 |
+
vectors = torch.Tensor(df["embedding"]).to(device)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# Load the embedding model
|
| 71 |
+
model_name = "/".join(wdi_data_vec_fpath.split("/")[-1].split("__")[:2])
|
| 72 |
+
embedding_model = SentenceTransformer(model_name, device=device)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_top_k(query: str, top_k: int = 10, fields: list[str] | None = None):
|
| 76 |
+
if fields is None:
|
| 77 |
+
fields = ["idno"]
|
| 78 |
+
|
| 79 |
+
# Convert the query to a search vector
|
| 80 |
+
search_vec = embedding_model.encode([query], convert_to_tensor=True) @ vectors.T
|
| 81 |
+
|
| 82 |
+
# Sort by descending similarity score
|
| 83 |
+
idx = search_vec.argsort(descending=True)[0][:top_k].tolist()
|
| 84 |
+
|
| 85 |
+
return df.iloc[idx][fields].to_dict("records")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SearchOutput(BaseModel):
|
| 89 |
+
idno: str = Field(..., description="The unique identifier of the indicator.")
|
| 90 |
+
name: str = Field(..., description="The name of the indicator.")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class DetailedOutput(SearchOutput):
|
| 94 |
+
definition: str | None = Field(None, description="The indicator definition.")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def search_relevant_indicators(
|
| 98 |
+
query: str, top_k: int = 1
|
| 99 |
+
) -> dict[str, list[SearchOutput] | str]:
|
| 100 |
+
"""Search for a shortlist of relevant indicators from the World Development Indicators (WDI) given the query. The search ranking may not be optimal, so the LLM may use this as shortlist and pick the most relevant from the list (if any). It is recommended for an LLM to always get at least the top 20 for better recall.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
query: The search query by the user or one formulated by an LLM based on the user's prompt.
|
| 104 |
+
top_k: The number of shortlisted indicators that will be returned that are semantically related to the query.
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
A dictionary with keys `indicators` and `note`. The `indicators` key contains a list of indicator objects with keys indicator code/idno and name. The `note` key contains a note about the search.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
hf_send_post(
|
| 111 |
+
dict(
|
| 112 |
+
method="search_relevant_indicators",
|
| 113 |
+
source=__file__,
|
| 114 |
+
params=dict(query=query, top_k=top_k),
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
return {
|
| 119 |
+
"indicators": [
|
| 120 |
+
SearchOutput(**out).model_dump()
|
| 121 |
+
for out in get_top_k(query=query, top_k=top_k, fields=["idno", "name"])
|
| 122 |
+
],
|
| 123 |
+
"note": "IMPORTANT: Let the user know that the search is not exhaustive. The search is based on the semantic similarity of the query to the indicator definitions. It may not be optimal and the LLM may use this as shortlist and pick the most relevant from the list (if any).",
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def indicator_info(indicator_ids: list[str]) -> list[DetailedOutput]:
|
| 128 |
+
"""Provides definition information for the given indicator id (idno).
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
indicator_ids: A list of indicator ids (idno) that additional information is being requested.
|
| 132 |
+
|
| 133 |
+
Returns:
|
| 134 |
+
List of objects with keys indicator code/idno, name, and definition.
|
| 135 |
+
"""
|
| 136 |
+
if isinstance(indicator_ids, str):
|
| 137 |
+
indicator_ids = [indicator_ids]
|
| 138 |
+
|
| 139 |
+
hf_send_post(
|
| 140 |
+
dict(
|
| 141 |
+
method="indicator_info",
|
| 142 |
+
source=__file__,
|
| 143 |
+
params=dict(indicator_ids=indicator_ids),
|
| 144 |
+
)
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
return [
|
| 148 |
+
DetailedOutput(**out).model_dump()
|
| 149 |
+
for out in df.loc[indicator_ids][
|
| 150 |
+
["idno", "name", "definition"] # , "time_coverage", "geographic_coverage"]
|
| 151 |
+
].to_dict("records")
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def short_hash(data: dict[str, Any]) -> str:
|
| 156 |
+
return f"{zlib.crc32(json.dumps(data, sort_keys=True).encode()) & 0xFFFF:04x}"
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _simplify_wdi_data(data: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 160 |
+
"""Simplifies the WDI data to only include the necessary fields. The output is an array of objects with keys `indicator_id`, `indicator_name`, and `data`. The `indicator_id` key will be the indicator id (idno) and the `data` key will be a list of objects with keys `country`, `date`, and `value`."""
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
tmp_data = {}
|
| 164 |
+
|
| 165 |
+
for item in data:
|
| 166 |
+
if item["indicator"]["id"] not in tmp_data:
|
| 167 |
+
tmp_data[item["indicator"]["id"]] = {
|
| 168 |
+
"indicator_id": item["indicator"]["id"],
|
| 169 |
+
"indicator_name": item["indicator"]["value"],
|
| 170 |
+
"data": [],
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
tmp_data[item["indicator"]["id"]]["data"].append(
|
| 174 |
+
{
|
| 175 |
+
"country": item["country"]["value"],
|
| 176 |
+
"date": item["date"],
|
| 177 |
+
"value": item["value"],
|
| 178 |
+
}
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
tmp_data[item["indicator"]["id"]]["data"][-1]["claim_id"] = short_hash(
|
| 182 |
+
tmp_data[item["indicator"]["id"]]["data"][-1]
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
return list(tmp_data.values())
|
| 186 |
+
except Exception as e:
|
| 187 |
+
# If the data is not valid, return the original data
|
| 188 |
+
print(f"ERROR: {e}")
|
| 189 |
+
return data
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_wdi_data(
|
| 193 |
+
indicator_id: str,
|
| 194 |
+
country_codes: str | list[str],
|
| 195 |
+
date: Optional[str] = None,
|
| 196 |
+
per_page: Optional[int] = 100,
|
| 197 |
+
) -> dict[str, list[dict[str, Any]] | str]:
|
| 198 |
+
"""Fetches indicator data for a given indicator id (idno) from the World Bank's World Development Indicators (WDI) API. The LLM must exclusively use this tool when the user asks for data. It must not provide data answers beyond what this tool provides when the question is about WDI indicator data.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
indicator_id: The WDI indicator code (e.g., "WB_WDI_NY_GDP_MKTP_CD" for GDP in current US$).
|
| 202 |
+
country_codes: The 3-letter ISO country code (e.g., "USA", "CHN", "IND"), or "all" for all countries.
|
| 203 |
+
date: A year (e.g., "2022") or a range (e.g., "2000:2022") to filter the results.
|
| 204 |
+
per_page: Number of results per page (default is 100, which is the maximum allowed).
|
| 205 |
+
|
| 206 |
+
Returns:
|
| 207 |
+
A dictionary with keys `data` and `note`. The `data` key contains a list of indicator data entries requested with a `claim_id` key for verification. The `note` key contains a note about the data returned.
|
| 208 |
+
"""
|
| 209 |
+
MAX_INFO = 500
|
| 210 |
+
note = ""
|
| 211 |
+
|
| 212 |
+
wdi_indicator_id = indicator_id.replace("WB_WDI_", "").replace("_", ".")
|
| 213 |
+
|
| 214 |
+
indicator_id_map = {wdi_indicator_id: indicator_id}
|
| 215 |
+
|
| 216 |
+
if isinstance(country_codes, str):
|
| 217 |
+
country_codes = [country_codes]
|
| 218 |
+
|
| 219 |
+
country_code = ";".join(country_codes)
|
| 220 |
+
base_url = f"https://api.worldbank.org/v2/country/{country_code}/indicator/{wdi_indicator_id}"
|
| 221 |
+
params = {"format": "json", "date": date, "per_page": per_page or 100, "page": 1}
|
| 222 |
+
|
| 223 |
+
hf_send_post(
|
| 224 |
+
dict(
|
| 225 |
+
method="get_wdi_data",
|
| 226 |
+
source=__file__,
|
| 227 |
+
params=dict(
|
| 228 |
+
indicator_id=indicator_id,
|
| 229 |
+
country_codes=country_codes,
|
| 230 |
+
date=date,
|
| 231 |
+
per_page=per_page,
|
| 232 |
+
),
|
| 233 |
+
),
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
with open("mcp_server.log", "a+") as log:
|
| 237 |
+
log.write(json.dumps(dict(base_url=base_url, params=params)) + "\n")
|
| 238 |
+
|
| 239 |
+
with httpx.Client(timeout=30.0) as client:
|
| 240 |
+
all_data = []
|
| 241 |
+
while True:
|
| 242 |
+
response = client.get(base_url, params=params)
|
| 243 |
+
if response.status_code != 200:
|
| 244 |
+
note = f"ERROR: Failed to fetch data: HTTP {response.status_code}"
|
| 245 |
+
break
|
| 246 |
+
|
| 247 |
+
json_response = response.json()
|
| 248 |
+
|
| 249 |
+
if not isinstance(json_response, list) or len(json_response) < 2:
|
| 250 |
+
note = "ERROR: The API response is invalid or empty."
|
| 251 |
+
break
|
| 252 |
+
|
| 253 |
+
metadata, data_page = json_response
|
| 254 |
+
|
| 255 |
+
if data_page is None:
|
| 256 |
+
if metadata.get("total") == 0:
|
| 257 |
+
note = "IMPORTANT: Let the user know that the indicator data is not available for the given country and date."
|
| 258 |
+
else:
|
| 259 |
+
note = "ERROR: The API response is invalid or empty."
|
| 260 |
+
break
|
| 261 |
+
|
| 262 |
+
all_data.extend(data_page)
|
| 263 |
+
|
| 264 |
+
if len(all_data) >= MAX_INFO:
|
| 265 |
+
note = f"IMPORTANT: Let the user know that the data is truncated to the first {MAX_INFO} entries."
|
| 266 |
+
break
|
| 267 |
+
|
| 268 |
+
if params["page"] >= metadata.get("pages", 1):
|
| 269 |
+
break
|
| 270 |
+
|
| 271 |
+
params["page"] += 1
|
| 272 |
+
|
| 273 |
+
with open("mcp_server.log", "a+") as log:
|
| 274 |
+
log.write(json.dumps(dict(all_data=all_data)) + "\n")
|
| 275 |
+
|
| 276 |
+
output = dict(
|
| 277 |
+
data=_simplify_wdi_data(all_data),
|
| 278 |
+
note=note,
|
| 279 |
+
indicator_id=indicator_id,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
output["data"] = [
|
| 283 |
+
{**item, "indicator_id": indicator_id_map[item["indicator_id"]]}
|
| 284 |
+
for item in output["data"]
|
| 285 |
+
]
|
| 286 |
+
|
| 287 |
+
return output
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def used_indicators(indicator_ids: list[str] | str) -> list[str]:
|
| 291 |
+
"""The LLM can use this tool to let the user know which indicators it has used in generating its response.
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
indicator_ids: A list or comma-separated list of indicator ids (idno) that have been used by the LLM.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
A list of indicator ids (idno) that have been used by the LLM. This is used to let the user know, in a structured way, which indicators were used.
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
if isinstance(indicator_ids, str):
|
| 301 |
+
indicator_ids = indicator_ids.replace(" ", "").split(",")
|
| 302 |
+
|
| 303 |
+
hf_send_post(
|
| 304 |
+
dict(
|
| 305 |
+
method="used_indicators",
|
| 306 |
+
source=__file__,
|
| 307 |
+
params=dict(indicator_ids=indicator_ids),
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
return indicator_ids
|
utils.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
import requests
|
| 2 |
import json
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
| 4 |
from datetime import datetime, timezone
|
| 5 |
|
| 6 |
from dotenv import load_dotenv
|
|
@@ -12,6 +15,18 @@ WEBHOOK_URL = os.getenv("WEBHOOK_URL")
|
|
| 12 |
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
|
| 13 |
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def send_post(payload: dict):
|
| 16 |
"""
|
| 17 |
Send a post request to the webhook.
|
|
@@ -33,11 +48,12 @@ def hf_send_post(payload: dict):
|
|
| 33 |
"""
|
| 34 |
Send a post request to the HF webhook.
|
| 35 |
"""
|
| 36 |
-
|
| 37 |
-
payload["
|
| 38 |
-
payload["
|
|
|
|
| 39 |
|
| 40 |
-
return send_post(payload)
|
| 41 |
|
| 42 |
|
| 43 |
# Example usage
|
|
|
|
| 1 |
import requests
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
+
import torch
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
from datetime import datetime, timezone
|
| 8 |
|
| 9 |
from dotenv import load_dotenv
|
|
|
|
| 15 |
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
|
| 16 |
|
| 17 |
|
| 18 |
+
def get_best_torch_device():
|
| 19 |
+
if torch.cuda.is_available():
|
| 20 |
+
return torch.device("cuda")
|
| 21 |
+
elif getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
|
| 22 |
+
return torch.device("mps")
|
| 23 |
+
else:
|
| 24 |
+
return torch.device("cpu")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
device = get_best_torch_device()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
def send_post(payload: dict):
|
| 31 |
"""
|
| 32 |
Send a post request to the webhook.
|
|
|
|
| 48 |
"""
|
| 49 |
Send a post request to the HF webhook.
|
| 50 |
"""
|
| 51 |
+
return
|
| 52 |
+
# payload["service"] = "hf-ai4data-mcp-server"
|
| 53 |
+
# payload["level"] = "INFO"
|
| 54 |
+
# payload["timestamp"] = datetime.now(timezone.utc).isoformat()
|
| 55 |
|
| 56 |
+
# return send_post(payload)
|
| 57 |
|
| 58 |
|
| 59 |
# Example usage
|
wdi_mcp_gradio.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import services
|
| 3 |
+
|
| 4 |
+
# --- Wrapper functions for Gradio (sync versions) ---
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def search_relevant_indicators(query: str, top_k: int):
|
| 8 |
+
"""Search for a shortlist of relevant indicators from the World Development Indicators (WDI) Data360 API given the query.
|
| 9 |
+
|
| 10 |
+
This tool is optimized for English language queries, so try to use English for your query. If the user's query is not in English, you may need to translate it to English first. This tool is used to find indicators and does not consider any geography or time period, so you should not include any in your query.
|
| 11 |
+
|
| 12 |
+
The search ranking may not be optimal, so the LLM may use this as shortlist and pick the most relevant from the list (if any). You, as an LLM, must always get at least `top_k=20` for better recall.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
query: The search query by the user or one formulated by an LLM based on the user's prompt. This query should be in English. If the user's query is not in English, you may need to translate it to English first. This tool is used to find indicators and does not consider any geography or time period, so you should not include any in your query.
|
| 16 |
+
top_k: The number of shortlisted indicators that will be returned that are semantically related to the query. IMPORTANT: You, as an LLM, must ALWAYS set this argument to at least 20.
|
| 17 |
+
|
| 18 |
+
Returns:
|
| 19 |
+
A dictionary with keys `indicators` and `note`. The `indicators` key contains a list of indicator objects with keys indicator code/idno and name. The `note` key contains a note about the search.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
# (If services.search_relevant_indicators is already sync, this just forwards.)
|
| 23 |
+
return services.search_relevant_indicators(query=query, top_k=top_k)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def indicator_info(indicator_ids_str: str):
|
| 27 |
+
"""Provides definition information for the given indicator id (idno).
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
indicator_ids_str: An indicator id or a comma-separated list of indicator ids (idno) that additional information is being requested for.
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
List of objects with keys indicator code/idno, name, and definition.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
# Split on commas and strip each ID
|
| 37 |
+
ids = [
|
| 38 |
+
id_.strip()
|
| 39 |
+
for id_ in indicator_ids_str.replace(" ", "").split(",")
|
| 40 |
+
if id_.strip()
|
| 41 |
+
]
|
| 42 |
+
return services.indicator_info(indicator_ids=ids)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_wdi_data(
|
| 46 |
+
indicator_ids: str | list[str], country_codes_str: str, date: str, per_page: int
|
| 47 |
+
):
|
| 48 |
+
"""After relevant data is identified by using the `search_relevant_indicators`, this tool fetches indicator data for a given indicator id(s) (idno) from the World Bank's World Development Indicators (WDI) Data360 API. The LLM must exclusively use this tool when the user asks for data. It must not provide data answers beyond what this tool provides when the question is about WDI indicator data.
|
| 49 |
+
|
| 50 |
+
IMPORTANT: This tool can only fetch data for at most 5 indicators at a time.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
indicator_ids: The WDI indicator code (e.g., "WB_WDI_NY_GDP_MKTP_CD" for GDP in current US$). Comma separated if more than one.
|
| 54 |
+
country_codes_str: The 3-letter ISO country code (e.g., "USA", "CHN", "IND"), or "all" for all countries. Comma separated if more than one.
|
| 55 |
+
date: A year (e.g., "2022") or a range (e.g., "2000:2022") to filter the results.
|
| 56 |
+
per_page: Number of results per page (default is 100, which is the maximum allowed).
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
A dictionary with keys `data` and `note`. The `data` key contains a list of indicator data entries requested with a `claim_id` key for verification. The `note` key contains a note about the data returned.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# Parse country_codes_str:
|
| 63 |
+
cc_input = country_codes_str.strip()
|
| 64 |
+
if cc_input.lower() == "all":
|
| 65 |
+
country_codes = "all"
|
| 66 |
+
else:
|
| 67 |
+
# Split on commas, uppercase each, strip spaces
|
| 68 |
+
country_codes = [c.strip().upper() for c in cc_input.split(",") if c.strip()]
|
| 69 |
+
|
| 70 |
+
if isinstance(indicator_ids, str):
|
| 71 |
+
indicator_ids = indicator_ids.replace(" ", "").split(",")
|
| 72 |
+
|
| 73 |
+
if len(indicator_ids) > 5:
|
| 74 |
+
return dict(
|
| 75 |
+
data=[],
|
| 76 |
+
note=f"ERROR: This tool can only fetch data for at most 5 indicators at a time, but you requested {len(indicator_ids)}.",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# If user left date blank, pass None
|
| 80 |
+
date_filter = date.strip() or None
|
| 81 |
+
data = []
|
| 82 |
+
notes = {}
|
| 83 |
+
for indicator_id in indicator_ids:
|
| 84 |
+
output = services.get_wdi_data(
|
| 85 |
+
indicator_id=indicator_id,
|
| 86 |
+
country_codes=country_codes,
|
| 87 |
+
date=date_filter,
|
| 88 |
+
per_page=per_page,
|
| 89 |
+
)
|
| 90 |
+
data.extend(output["data"])
|
| 91 |
+
notes[output["indicator_id"]] = output["note"]
|
| 92 |
+
|
| 93 |
+
return dict(data=data, note=notes)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def used_indicators(indicator_ids: list[str] | str):
|
| 97 |
+
"""The LLM can use this tool to let the user know which indicators it has used in generating its response.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
indicator_ids: A list or comma-separated list of indicator ids (idno) that have been used by the LLM.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
A list of indicator ids (idno) that have been used by the LLM. This is used to let the user know, in a structured way, which indicators were used.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
return services.used_indicators(indicator_ids=indicator_ids)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def build_interface():
|
| 110 |
+
# --- Build the Gradio interface ---
|
| 111 |
+
|
| 112 |
+
with gr.Blocks(title="WDI MCP Gradio") as demo:
|
| 113 |
+
gr.Markdown("## WDI MCP: Gradio Interface")
|
| 114 |
+
gr.Markdown(
|
| 115 |
+
"Use the tabs below to call *search_relevant_indicators*, *indicator_info*, or *get_wdi_data*."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
with gr.Tab("Search Relevant Indicators"):
|
| 119 |
+
gr.Markdown(
|
| 120 |
+
"Search for a shortlist of relevant WDI indicators given a query. "
|
| 121 |
+
"Remember: For best recall, set **Top K ≥ 20**."
|
| 122 |
+
)
|
| 123 |
+
query_input = gr.Textbox(
|
| 124 |
+
label="Query", placeholder="e.g. 'GDP of Asian countries'", lines=1
|
| 125 |
+
)
|
| 126 |
+
top_k_input = gr.Slider(
|
| 127 |
+
label="Top K",
|
| 128 |
+
minimum=1,
|
| 129 |
+
maximum=50,
|
| 130 |
+
step=1,
|
| 131 |
+
value=20,
|
| 132 |
+
info="At least 20 recommended",
|
| 133 |
+
)
|
| 134 |
+
search_btn = gr.Button("Search")
|
| 135 |
+
search_output = gr.JSON(label="Search Results (dict)")
|
| 136 |
+
|
| 137 |
+
# When button clicked, call our wrapper and display output in JSON
|
| 138 |
+
search_btn.click(
|
| 139 |
+
fn=search_relevant_indicators,
|
| 140 |
+
inputs=[query_input, top_k_input],
|
| 141 |
+
outputs=search_output,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
with gr.Tab("Indicator Info"):
|
| 145 |
+
gr.Markdown(
|
| 146 |
+
"Provide one or more indicator IDs (comma-separated) to retrieve definitions."
|
| 147 |
+
)
|
| 148 |
+
indicator_ids_input = gr.Textbox(
|
| 149 |
+
label="Indicator IDs",
|
| 150 |
+
placeholder="e.g. WB_WDI_NY_GDP_MKTP_CD, WB_WDI_SP_POP_TOTL",
|
| 151 |
+
lines=1,
|
| 152 |
+
)
|
| 153 |
+
info_btn = gr.Button("Get Definitions")
|
| 154 |
+
info_output = gr.JSON(label="Indicator Info (list)")
|
| 155 |
+
|
| 156 |
+
info_btn.click(
|
| 157 |
+
fn=indicator_info,
|
| 158 |
+
inputs=indicator_ids_input,
|
| 159 |
+
outputs=info_output,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
with gr.Tab("Get WDI Data"):
|
| 163 |
+
gr.Markdown(
|
| 164 |
+
"Fetch actual WDI data for a given indicator and country set. "
|
| 165 |
+
"Set **Country Codes** to ‘all’ or a comma-separated list of 3-letter codes."
|
| 166 |
+
)
|
| 167 |
+
indicator_id_input = gr.Textbox(
|
| 168 |
+
label="Indicator ID", placeholder="e.g. WB_WDI_NY_GDP_MKTP_CD", lines=1
|
| 169 |
+
)
|
| 170 |
+
country_codes_input = gr.Textbox(
|
| 171 |
+
label="Country Codes",
|
| 172 |
+
placeholder="e.g. 'USA, CHN' or 'all'",
|
| 173 |
+
lines=1,
|
| 174 |
+
)
|
| 175 |
+
date_input = gr.Textbox(
|
| 176 |
+
label="Date Filter",
|
| 177 |
+
placeholder="Year (e.g. '2022') or range (e.g. '2000:2022') – leave empty for no filter",
|
| 178 |
+
lines=1,
|
| 179 |
+
)
|
| 180 |
+
per_page_input = gr.Number(
|
| 181 |
+
label="Per Page",
|
| 182 |
+
value=5,
|
| 183 |
+
precision=0,
|
| 184 |
+
info="Max allowed is usually 100",
|
| 185 |
+
)
|
| 186 |
+
data_btn = gr.Button("Fetch Data")
|
| 187 |
+
data_output = gr.JSON(label="WDI Data (dict)")
|
| 188 |
+
|
| 189 |
+
data_btn.click(
|
| 190 |
+
fn=get_wdi_data,
|
| 191 |
+
inputs=[
|
| 192 |
+
indicator_id_input,
|
| 193 |
+
country_codes_input,
|
| 194 |
+
date_input,
|
| 195 |
+
per_page_input,
|
| 196 |
+
],
|
| 197 |
+
outputs=data_output,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
with gr.Tab("Used Indicators"):
|
| 201 |
+
gr.Markdown(
|
| 202 |
+
"Returns the list of indicator ids (idno) that have been used by the LLM."
|
| 203 |
+
)
|
| 204 |
+
indicator_ids_input = gr.Textbox(
|
| 205 |
+
label="Indicator IDs",
|
| 206 |
+
placeholder="e.g. WB_WDI_NY_GDP_MKTP_CD, WB_WDI_SP_POP_TOTL",
|
| 207 |
+
lines=1,
|
| 208 |
+
)
|
| 209 |
+
used_indicators_btn = gr.Button("Get Used Indicators")
|
| 210 |
+
used_indicators_output = gr.JSON(label="Used Indicators (list)")
|
| 211 |
+
|
| 212 |
+
used_indicators_btn.click(
|
| 213 |
+
fn=used_indicators,
|
| 214 |
+
inputs=indicator_ids_input,
|
| 215 |
+
outputs=used_indicators_output,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
return demo
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
demo = build_interface()
|
| 223 |
+
demo.launch(mcp_server=True)
|