Files
langchain/libs/community/langchain_community/utilities/dataherald.py
Eugene Yurtsev 844955d6e1 community[patch]: assign missed default (#26326)
Assigning missed defaults in various classes. Most clients were being
assigned during the `model_validator(mode="before")` step, so this
change should amount to a no-op in those cases.

---

This PR was autogenerated using gritql

```shell

grit apply 'class_definition(name=$C, $body, superclasses=$S) where {    
    $C <: ! "Config", // Does not work in this scope, but works after class_definition
    $body <: block($statements),
    $statements <: some bubble assignment(left=$x, right=$y, type=$t) as $A where {
        or {
            $y <: `Field($z)`,
            $x <: "model_config"
        }
    },
    // And has either Any or Optional fields without a default
    $statements <: some bubble assignment(left=$x, right=$y, type=$t) as $A where {
        $t <: or {
            r"Optional.*",
            r"Any",
            r"Union[None, .*]",
            r"Union[.*, None, .*]",
            r"Union[.*, None]",
        },
        $y <: ., // Match empty node        
        $t => `$t = None`,
    },    
}
' --language python .

```
2024-09-11 11:13:11 -04:00

69 lines
2.0 KiB
Python

"""Util that calls Dataherald."""
from typing import Any, Dict, Optional
from langchain_core.utils import get_from_dict_or_env
from pydantic import BaseModel, ConfigDict, model_validator
class DataheraldAPIWrapper(BaseModel):
"""Wrapper for Dataherald.
Docs for using:
1. Go to dataherald and sign up
2. Create an API key
3. Save your API key into DATAHERALD_API_KEY env variable
4. pip install dataherald
"""
dataherald_client: Any = None #: :meta private:
db_connection_id: str
dataherald_api_key: Optional[str] = None
model_config = ConfigDict(
extra="forbid",
)
@model_validator(mode="before")
@classmethod
def validate_environment(cls, values: Dict) -> Any:
"""Validate that api key and python package exists in environment."""
dataherald_api_key = get_from_dict_or_env(
values, "dataherald_api_key", "DATAHERALD_API_KEY"
)
values["dataherald_api_key"] = dataherald_api_key
try:
import dataherald
except ImportError:
raise ImportError(
"dataherald is not installed. "
"Please install it with `pip install dataherald`"
)
client = dataherald.Dataherald(api_key=dataherald_api_key)
values["dataherald_client"] = client
return values
def run(self, prompt: str) -> str:
"""Generate a sql query through Dataherald and parse result."""
from dataherald.types.sql_generation_create_params import Prompt
prompt_obj = Prompt(text=prompt, db_connection_id=self.db_connection_id)
res = self.dataherald_client.sql_generations.create(prompt=prompt_obj)
try:
answer = res.sql
if not answer:
# We don't want to return the assumption alone if answer is empty
return "No answer"
else:
return f"Answer: {answer}"
except StopIteration:
return "Dataherald wasn't able to answer it"