importosfromtypingimportAny,Dict,Generator,Iterator,List,Literal,Optionalimportrequestsfromlangchain_core.callbacks.managerimportCallbackManagerForLLMRunfromlangchain_core.language_models.llmsimportLLMfromlangchain_core.outputsimportGenerationChunkfrompydanticimportFieldSMART_ENDPOINT="https://chat-api.you.com/smart"RESEARCH_ENDPOINT="https://chat-api.you.com/research"def_request(base_url:str,api_key:str,**kwargs:Any)->Dict[str,Any]:""" NOTE: This function can be replaced by a OpenAPI-generated Python SDK in the future, for better input/output typing support. """headers={"x-api-key":api_key}response=requests.post(base_url,headers=headers,json=kwargs)response.raise_for_status()returnresponse.json()def_request_stream(base_url:str,api_key:str,**kwargs:Any)->Generator[str,None,None]:headers={"x-api-key":api_key}params=dict(**kwargs,stream=True)response=requests.post(base_url,headers=headers,stream=True,json=params)response.raise_for_status()# Explicitly coercing the response to a generator to satisfy mypyevent_source=(bytestringforbytestringinresponse)try:importsseclientclient=sseclient.SSEClient(event_source)exceptImportError:raiseImportError(("Could not import `sseclient`. ""Please install it with `pip install sseclient-py`."))foreventinclient.events():ifevent.eventin("search_results","done"):passelifevent.event=="token":yieldevent.dataelifevent.event=="error":raiseValueError(f"Error in response: {event.data}")else:raiseNotImplementedError(f"Unknown event type {event.event}")
[docs]classYou(LLM):"""Wrapper around You.com's conversational Smart and Research APIs. Each API endpoint is designed to generate conversational responses to a variety of query types, including inline citations and web results when relevant. Smart Endpoint: - Quick, reliable answers for a variety of questions - Cites the entire web page URL Research Endpoint: - In-depth answers with extensive citations for a variety of questions - Cites the specific web page snippet relevant to the claim To connect to the You.com api requires an API key which you can get at https://api.you.com. For more information, check out the documentations at https://documentation.you.com/api-reference/. Args: endpoint: You.com conversational endpoints. Choose from "smart" or "research" ydc_api_key: You.com API key, if `YDC_API_KEY` is not set in the environment """endpoint:Literal["smart","research"]=Field("smart",description=('You.com conversational endpoints. Choose from "smart" or "research"'),)ydc_api_key:Optional[str]=Field(None,description="You.com API key, if `YDC_API_KEY` is not set in the envrioment",)def_call(self,prompt:str,stop:Optional[List[str]]=None,run_manager:Optional[CallbackManagerForLLMRun]=None,**kwargs:Any,)->str:ifstop:raiseNotImplementedError("Stop words are not implemented for You.com endpoints.")params={"query":prompt}response=_request(self._request_endpoint,api_key=self._api_key,**params)returnresponse["answer"]def_stream(self,prompt:str,stop:Optional[List[str]]=None,run_manager:Optional[CallbackManagerForLLMRun]=None,**kwargs:Any,)->Iterator[GenerationChunk]:ifstop:raiseNotImplementedError("Stop words are not implemented for You.com endpoints.")params={"query":prompt}fortokenin_request_stream(self._request_endpoint,api_key=self._api_key,**params):yieldGenerationChunk(text=token)@propertydef_request_endpoint(self)->str:ifself.endpoint=="smart":returnSMART_ENDPOINTreturnRESEARCH_ENDPOINT@propertydef_api_key(self)->str:returnself.ydc_api_keyoros.environ["YDC_API_KEY"]@propertydef_llm_type(self)->str:return"you.com"