fromtypingimportList,Optional,Generator,Union,TypeimporthttpxfrompydanticimportBaseModelfrom..importSwitchAIfrom..base_clientimportBaseClientfrom..typesimportChatResponsefrom..utilsimportTaskdeffetch_website(url:str)->str:headers={"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"}try:withhttpx.Client()asclient:response=client.get(url,headers=headers)response.raise_for_status()returnstr(response.content)excepthttpx.RequestErrorase:returnf"An error occurred while requesting {e.request.url!r}: {e}"excepthttpx.HTTPStatusErrorase:returnf"Error response {e.response.status_code} while requesting {e.request.url!r}"exceptExceptionase:returnf"An unexpected error occurred: {e}"
[docs]classBrowser(BaseClient):""" A superclient that extends a chat SwitchAI client to support websites fetching and analysis. Args: client: A SwitchAI client initialized with a chat model. """def__init__(self,client:SwitchAI):if(Task.TEXT_GENERATIONnotinclient.supported_tasksandTask.IMAGE_TEXT_TO_TEXTnotinclient.supported_tasks):raiseValueError("Browser only accepts chat models.")self.client=client
[docs]defchat(self,messages:List[str|dict|ChatResponse],temperature:Optional[float]=1.0,max_tokens:Optional[int]=None,tools:Optional[List]=None,response_format:Optional[Type[BaseModel]]=None,stream:Optional[bool]=False,)->Union[ChatResponse,Generator[ChatResponse,None,None]]:iftoolsisNone:tools=[]iflen(tools)>0:raiseValueError("Browser does not accept tools.")tools.append({"type":"function","function":{"name":"get_website","description":"Get the content of a website.","parameters":{"type":"object","properties":{"url":{"type":"string","description":"The URL of the website to get."},},},},})first_response=self.client.chat(messages,temperature,max_tokens,tools)tool_calls=first_response.tool_callsiftool_calls:messages.append(first_response)fortool_callintool_calls:iftool_call.function.name=="get_website":function_args=tool_call.function.argumentsweb_page=fetch_website(**function_args)messages.append({"role":"tool","content":web_page,"tool_call_id":tool_call.id,"tool_name":tool_call.function.name,})returnself.client.chat(messages,temperature,max_tokens)returnfirst_response