| 7 | |
| 8 | |
| 9 | def build_tool(config) -> Tool: |
| 10 | tool = Tool( |
| 11 | "Wolfram", |
| 12 | "Wolfram", |
| 13 | name_for_model="Wolfram", |
| 14 | name_for_human="Wolfram", |
| 15 | description_for_model=""""Dynamic computation and curated data from WolframAlpha and Wolfram Cloud.\nOnly use the getWolframAlphaResults endpoints; all other Wolfram endpoints are deprecated.\nPrefer getWolframAlphaResults unless Wolfram Language code should be evaluated.\nTry to include images returned by getWolframAlphaResults. Queries to getWolframAlphaResults must ALWAYS have this structure: {\"input\": query}.\n", |
| 16 | """, |
| 17 | description_for_human="Access computation, math, curated knowledge & real-time data through Wolfram|Alpha and Wolfram Language.", |
| 18 | logo_url="https://www.wolframcdn.com/images/icons/Wolfram.png", |
| 19 | contact_email="hello@contact.com", |
| 20 | legal_info_url="hello@legal.com" |
| 21 | ) |
| 22 | |
| 23 | @tool.get("/getWolframAlphaResults") |
| 24 | def getWolframAlphaResults(input:str): |
| 25 | """Get Wolfram|Alpha results using natural query. Queries to getWolframAlphaResults must ALWAYS have this structure: {\"input\": query}. And please directly read the output json. |
| 26 | """ |
| 27 | URL = "https://api.wolframalpha.com/v2/query" |
| 28 | |
| 29 | APPID = config["subscription_key"] |
| 30 | |
| 31 | params = {'appid': APPID, "input": input} |
| 32 | |
| 33 | response = requests.get(URL, params=params) |
| 34 | |
| 35 | json_data = xmltodict.parse(response.text) |
| 36 | |
| 37 | if 'pod' not in json_data["queryresult"]: |
| 38 | return "WolframAlpha API cannot parse the input query." |
| 39 | rets = json_data["queryresult"]['pod'] |
| 40 | |
| 41 | cleaned_rets = [] |
| 42 | blacklist = ["@scanner", "@id", "@position", "@error", "@numsubpods", "@width", "@height", "@type", "@themes","@colorinvertable", "expressiontypes"] |
| 43 | |
| 44 | def filter_dict(d, blacklist): |
| 45 | if isinstance(d, dict): |
| 46 | return {k: filter_dict(v, blacklist) for k, v in d.items() if k not in blacklist} |
| 47 | elif isinstance(d, list): |
| 48 | return [filter_dict(i, blacklist) for i in d] |
| 49 | else: |
| 50 | return d |
| 51 | |
| 52 | for ret in rets: |
| 53 | ret = filter_dict(ret, blacklist=blacklist) |
| 54 | # Do further cleaning to retain only the input and result pods |
| 55 | if "@title" in ret: |
| 56 | if ret["@title"] == "Input" or ret["@title"] == "Result": |
| 57 | cleaned_rets.append(ret) |
| 58 | |
| 59 | return cleaned_rets |
| 60 | |
| 61 | return tool |