"""
title: WolframAlpha LLM API Integration
author: Morgan Blangeois
version: 1.0
license: MIT
description: A tool that integrates WolframAlpha LLM API.
requirements: requests
"""
import os
import requests
import urllib.parse
from typing import Optional, Dict, Any
from pydantic import BaseModel, Field
class Tools:
class Valves(BaseModel):
WOLFRAM_APP_ID: str = Field(
default="", description="The App ID for WolframAlpha API"
)
API_BASE_URL: str = Field(
default="https://www.wolframalpha.com/api/v1/llm-api",
description="The base URL for WolframAlpha API",
)
MAX_CHARS: int = Field(
default=6800,
description="The default maximum number of characters in the response",
)
def __init__(self):
self.valves = self.Valves()
self.app_id = os.getenv("WOLFRAM_APP_ID", self.valves.WOLFRAM_APP_ID)
self.api_base_url = self.valves.API_BASE_URL
self.max_chars = self.valves.MAX_CHARS
def perform_query(
self, query: str, max_chars: Optional[int] = None, **kwargs
) -> Dict[str, Any]:
"""
Perform a query to WolframAlpha LLM API.
:param query: The query to send to WolframAlpha.
:param max_chars: Maximum number of characters in the response (optional).
:param kwargs: Additional parameters to include in the API request.
:return: A dictionary containing the response data.
"""
try:
params = {
"input": query,
"appid": self.app_id,
"maxchars": max_chars or self.max_chars,
**kwargs,
}
encoded_params = urllib.parse.urlencode(params)
url = f"{self.api_base_url}?{encoded_params}"
headers = {
"User-Agent": "WolframAlphaAPI/1.1",
"Authorization": f"Bearer {self.app_id}",
}
response = requests.get(url, headers=headers, timeout=120)
response.raise_for_status()
return {"status": "success", "data": response.text, "url": response.url}
except requests.exceptions.RequestException as e:
return {
"status": "error",
"message": str(e),
"url": url if "url" in locals() else None,
}