importosimportrequestsLLM_GUARD_API_KEY=os.environ.get("LLM_GUARD_API_KEY")LLM_GUARD_BASE_URL=os.environ.get("LLM_GUARD_URL")classLLMGuardMaliciousPromptException(Exception):scores={}def__init__(self,*args,**kwargs):super().__init__(*args)self.scores=kwargs.get("scores",{})def__str__(self):scanners=[scannerforscanner,scoreinself.scores.items()ifscore>0]returnf"LLM Guard detected a malicious prompt. Scanners triggered: {', '.join(scanners)}; scores: {self.scores}"classLLMGuardRequestException(Exception):passdefrequest_llm_guard_prompt(prompt:str):try:response=requests.post(url=f"{LLM_GUARD_BASE_URL}/analyze/prompt",json={"prompt":prompt},headers={"Content-Type":"application/json","Authorization":f"Bearer {LLM_GUARD_API_KEY}",},)response_json=response.json()exceptrequests.RequestExceptionaserr:raiseLLMGuardRequestException(err)ifnotresponse_json["is_valid"]:raiseLLMGuardMaliciousPromptException(scores=response_json["scanners"])returnresponse_json["sanitized_prompt"]prompt="Write a Python function to calculate the factorial of a number."sanitized_prompt=request_llm_guard_prompt(prompt)print(sanitized_prompt)
importosimportasyncioimportaiohttpfromopenaiimportAsyncOpenAILLM_GUARD_API_KEY=os.environ.get("LLM_GUARD_API_KEY")LLM_GUARD_BASE_URL=os.environ.get("LLM_GUARD_URL")openai_client=AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"),)system_prompt="You are a Python tutor."classLLMGuardMaliciousPromptException(Exception):scores={}def__init__(self,*args,**kwargs):super().__init__(*args)self.scores=kwargs.get("scores",{})def__str__(self):scanners=[scannerforscanner,scoreinself.scores.items()ifscore>0]returnf"LLM Guard detected a malicious prompt. Scanners triggered: {', '.join(scanners)}; scores: {self.scores}"classLLMGuardRequestException(Exception):passasyncdefrequest_openai(prompt:str)->str:chat_completion=awaitopenai_client.chat.completions.create(messages=[{"role":"system","content":system_prompt,},{"role":"user","content":prompt},],model="gpt-3.5-turbo",)returnchat_completion.choices[0].message.contentasyncdefrequest_llm_guard_prompt(prompt:str):asyncwithaiohttp.ClientSession()assession:try:response=awaitsession.post(url=f"{LLM_GUARD_BASE_URL}/analyze/prompt",json={"prompt":prompt},headers={"Content-Type":"application/json","Authorization":f"Bearer {LLM_GUARD_API_KEY}",},ssl=False,raise_for_status=True,)response_json=awaitresponse.json()exceptExceptionase:raiseLLMGuardRequestException(e)ifnotresponse_json["is_valid"]:raiseLLMGuardMaliciousPromptException(scores=response_json["scanners"])asyncdefgenerate_completion(prompt:str)->str:result=awaitasyncio.gather(request_llm_guard_prompt(prompt),request_openai(prompt),)returnresult[1]prompt="Write a Python function to calculate the factorial of a number."message=asyncio.run(generate_completion(prompt))