mirror of
https://github.com/hwchase17/langchain
synced 2024-11-10 01:10:59 +00:00
c2a3021bb0
Signed-off-by: ChengZi <chen.zhang@zilliz.com> Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com> Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com> Co-authored-by: Dan O'Donovan <dan.odonovan@gmail.com> Co-authored-by: Tom Daniel Grande <tomdgrande@gmail.com> Co-authored-by: Grande <Tom.Daniel.Grande@statsbygg.no> Co-authored-by: Bagatur <baskaryan@gmail.com> Co-authored-by: ccurme <chester.curme@gmail.com> Co-authored-by: Harrison Chase <hw.chase.17@gmail.com> Co-authored-by: Tomaz Bratanic <bratanic.tomaz@gmail.com> Co-authored-by: ZhangShenao <15201440436@163.com> Co-authored-by: Friso H. Kingma <fhkingma@gmail.com> Co-authored-by: ChengZi <chen.zhang@zilliz.com> Co-authored-by: Nuno Campos <nuno@langchain.dev> Co-authored-by: Morgante Pell <morgantep@google.com>
69 lines
2.0 KiB
Python
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"
|