fromtypingimportAny,Dict,List,Optionalimportrequestsfromlangchain_core.callbacksimportCallbackManagerForLLMRunfromlangchain_core.language_modelsimportLLMfromlangchain_core.utilsimportconvert_to_secret_str,get_from_dict_or_env,pre_initfrompydanticimport(BaseModel,ConfigDict,Field,SecretStr,model_validator,)fromlangchain_community.llms.utilsimportenforce_stop_tokensSOLAR_SERVICE_URL_BASE="https://api.upstage.ai/v1/solar"SOLAR_SERVICE="https://api.upstage.ai"class_SolarClient(BaseModel):"""An API client that talks to the Solar server."""api_key:SecretStr"""The API key to use for authentication."""base_url:str=SOLAR_SERVICE_URL_BASEdefcompletion(self,request:Any)->Any:headers={"Authorization":f"Bearer {self.api_key.get_secret_value()}"}response=requests.post(f"{self.base_url}/chat/completions",headers=headers,json=request,)ifnotresponse.ok:raiseValueError(f"HTTP {response.status_code} error: {response.text}")returnresponse.json()["choices"][0]["message"]["content"]
[docs]classSolarCommon(BaseModel):"""Common configuration for Solar LLMs."""_client:_SolarClientbase_url:str=SOLAR_SERVICE_URL_BASEsolar_api_key:Optional[SecretStr]=Field(default=None,alias="api_key")"""Solar API key. Get it here: https://console.upstage.ai/services/solar"""model_name:str=Field(default="solar-mini",alias="model")"""Model name. Available models listed here: https://console.upstage.ai/services/solar"""max_tokens:int=Field(default=1024)temperature:float=0.3model_config=ConfigDict(populate_by_name=True,arbitrary_types_allowed=True,extra="ignore",protected_namespaces=(),)@propertydeflc_secrets(self)->dict:return{"solar_api_key":"SOLAR_API_KEY"}@propertydef_default_params(self)->Dict[str,Any]:return{"model":self.model_name,"max_tokens":self.max_tokens,"temperature":self.temperature,}@propertydef_invocation_params(self)->Dict[str,Any]:return{**{"model":self.model_name},**self._default_params}@model_validator(mode="before")@classmethoddefbuild_extra(cls,values:Dict[str,Any])->Any:returnvalues
[docs]@pre_initdefvalidate_environment(cls,values:Dict)->Dict:api_key=get_from_dict_or_env(values,"solar_api_key","SOLAR_API_KEY")ifapi_keyisNoneorlen(api_key)==0:raiseValueError("SOLAR_API_KEY must be configured")values["solar_api_key"]=convert_to_secret_str(api_key)if"base_url"notinvalues:values["base_url"]=SOLAR_SERVICE_URL_BASEif"base_url"invaluesandnotvalues["base_url"].startswith(SOLAR_SERVICE):raiseValueError("base_url must match with: "+SOLAR_SERVICE)values["_client"]=_SolarClient(api_key=values["solar_api_key"],base_url=values["base_url"])returnvalues
@propertydef_llm_type(self)->str:return"solar"
[docs]classSolar(SolarCommon,LLM):"""Solar large language models. To use, you should have the environment variable ``SOLAR_API_KEY`` set with your API key. Referenced from https://console.upstage.ai/services/solar """model_config=ConfigDict(populate_by_name=True,)def_call(self,prompt:str,stop:Optional[List[str]]=None,run_manager:Optional[CallbackManagerForLLMRun]=None,**kwargs:Any,)->str:request=self._invocation_paramsrequest["messages"]=[{"role":"user","content":prompt}]request.update(kwargs)text=self._client.completion(request)ifstopisnotNone:# This is required since the stop tokens# are not enforced by the model parameterstext=enforce_stop_tokens(text,stop)returntext