1- # 📚 LLM scan
1+ # 📚 LLM scan
22
33The Giskard python library provides an automatic scan functionality designed to automatically
44detect [ potential vulnerabilities] ( https://docs.giskard.ai/en/stable/knowledge/llm_vulnerabilities/index.html ) affecting
@@ -15,11 +15,13 @@ Differently from other techniques that focus on benchmarking a foundation LLM, G
1515** in-depth assessments on domain-specific models.** This includes chatbots, ** question answering systems, and
1616retrieval-augmented generation (RAG) models.**
1717
18- You can find detailed information about the inner workings of the LLM scan {doc}` here </knowledge/llm_vulnerabilities/index> ` .
18+ You can find detailed information about the inner workings of the LLM scan
19+ {doc}` here </knowledge/llm_vulnerabilities/index> ` .
1920
2021### What data are being sent to Language Model Providers
2122
22- In order to perform tasks with LLM-assisted detectors, we send the following information to the selected language model provider (e.g., OpenAI, Azure OpenAI, Ollama, Mistral):
23+ In order to perform tasks with LLM-assisted detectors, we send the following information to the selected language model
24+ provider (e.g., OpenAI, Azure OpenAI, Ollama, Mistral):
2325
2426- Data provided in your Dataset
2527- Text generated by your model
@@ -29,12 +31,16 @@ Note that this does not apply if you select a self-hosted model.
2931
3032### Will the scan work in any language?
3133
32- Most of the detectors ran by the scan should work with any language, however the effectiveness of ** LLM-assisted detectors** largely depends on the language capabilities of the specific language model in use. While many LLMs have broad multilingual capacities, the performance and accuracy may vary based on the model and the specific language being processed.
34+ Most of the detectors ran by the scan should work with any language, however the effectiveness of ** LLM-assisted
35+ detectors** largely depends on the language capabilities of the specific language model in use. While many LLMs have
36+ broad multilingual capacities, the performance and accuracy may vary based on the model and the specific language being
37+ processed.
3338
3439## Before starting
3540
36- In the following example, we illustrate the procedure using ** OpenAI** and ** Azure OpenAI** ; however, please note that our platform supports a variety of language models. For details on configuring different models, visit our [ 🤖 Setting up the LLM Client page] ( ../../open_source/setting_up/index.md )
37-
41+ In the following example, we illustrate the procedure using ** OpenAI** and ** Azure OpenAI** ; however, please note that
42+ our platform supports a variety of language models. For details on configuring different models, visit
43+ our [ 🤖 Setting up the LLM Client page] ( ../../open_source/setting_up/index.md )
3844
3945Before starting, make sure you have installed the LLM flavor of Giskard:
4046
@@ -59,6 +65,7 @@ giskard.llm.set_llm_api("openai")
5965oc = OpenAIClient(model = " gpt-4-turbo-preview" )
6066giskard.llm.set_default_client(oc)
6167```
68+
6269::::::
6370::::::{tab-item} Azure OpenAI
6471
@@ -72,14 +79,14 @@ os.environ['AZURE_OPENAI_API_KEY'] = '...'
7279os.environ[' AZURE_OPENAI_ENDPOINT' ] = ' https://xxx.openai.azure.com'
7380os.environ[' OPENAI_API_VERSION' ] = ' 2023-07-01-preview'
7481
75-
7682# You'll need to provide the name of the model that you've deployed
7783# Beware, the model provided must be capable of using function calls
7884set_llm_model(' my-gpt-4-model' )
7985```
8086
8187::::::
8288::::::{tab-item} Mistral
89+
8390``` python
8491import os
8592from giskard.llm.client.mistral import MistralClient
@@ -92,6 +99,7 @@ giskard.llm.set_default_client(mc)
9299
93100::::::
94101::::::{tab-item} Ollama
102+
95103``` python
96104import giskard
97105from openai import OpenAI
@@ -102,6 +110,7 @@ _client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
102110oc = OpenAIClient(model = " gemma:2b" , client = _client)
103111giskard.llm.set_default_client(oc)
104112```
113+
105114::::::
106115::::::{tab-item} Claude 3
107116
@@ -119,14 +128,14 @@ giskard.llm.set_default_client(claude_client)
119128
120129::::::
121130::::::{tab-item} Custom Client
131+
122132``` python
123133import giskard
124134from typing import Sequence, Optional
125135from giskard.llm.client import set_default_client
126136from giskard.llm.client.base import LLMClient, ChatMessage
127137
128138
129-
130139class MyLLMClient (LLMClient ):
131140 def __init__ (self , my_client ):
132141 self ._client = my_client
@@ -171,6 +180,7 @@ class MyLLMClient(LLMClient):
171180
172181 return ChatMessage(role = " assistant" , message = data[" completion" ])
173182
183+
174184set_default_client(MyLLMClient())
175185
176186```
@@ -181,6 +191,7 @@ set_default_client(MyLLMClient())
181191We are now ready to start.
182192
183193(model-wrapping)=
194+
184195## Step 1: Wrap your model
185196
186197Start by ** wrapping your model** . This step is necessary to ensure a common format for your model and its metadata.
@@ -206,6 +217,7 @@ def model_predict(df: pd.DataFrame):
206217 """
207218 return [llm_api(question) for question in df[" question" ].values]
208219
220+
209221# Create a giskard.Model object. Don’t forget to fill the `name` and `description`
210222# parameters: they will be used by our scan to generate domain-specific tests.
211223giskard_model = giskard.Model(
@@ -228,7 +240,8 @@ from langchain import OpenAI, LLMChain, PromptTemplate
228240
229241# Example chain
230242llm = OpenAI(model = " gpt-3.5-turbo-instruct" , temperature = 0 )
231- prompt = PromptTemplate(template = " You are a generic helpful assistant. Please answer this question: {question} " , input_variables = [" question" ])
243+ prompt = PromptTemplate(template = " You are a generic helpful assistant. Please answer this question: {question} " ,
244+ input_variables = [" question" ])
232245chain = LLMChain(llm = llm, prompt = prompt)
233246
234247# Create a giskard.Model object. Don’t forget to fill the `name` and `description`
@@ -249,12 +262,13 @@ langchain chain and an OpenAI model. Extending the `giskard.Model` class allows
249262Giskard Hub of complex models which cannot be automatically serialized with ` pickle ` .
250263
251264You will have to implement just three methods:
265+
252266- ` model_predict ` : This method takes a ` pandas.DataFrame ` with columns corresponding to the input variables of your
253- model and returns a sequence of outputs (one for each record in the dataframe).
267+ model and returns a sequence of outputs (one for each record in the dataframe).
254268- ` save_model ` : This method is handles the serialization of your model. You can use it to save your model's state,
255- including the information retriever or any other element your model needs to work.
269+ including the information retriever or any other element your model needs to work.
256270- ` load_model ` : This class method handles the deserialization of your model. You can use it to load your model's state,
257- including the information retriever or any other element your model needs to work.
271+ including the information retriever or any other element your model needs to work.
258272
259273``` python
260274from langchain import OpenAI, PromptTemplate, RetrievalQA
@@ -264,6 +278,7 @@ llm = OpenAI(model="gpt-3.5-turbo-instruct", temperature=0)
264278prompt = PromptTemplate(template = YOUR_PROMPT_TEMPLATE , input_variables = [" question" , " context" ])
265279climate_qa_chain = RetrievalQA.from_llm(llm = llm, retriever = get_context_storage().as_retriever(), prompt = prompt)
266280
281+
267282# Define a custom Giskard model wrapper for the serialization.
268283class FAISSRAGModel (giskard .Model ):
269284 def model_predict (self , df : pd.DataFrame):
@@ -314,11 +329,16 @@ For further examples, check out the {doc}`LLM tutorials section </tutorials/llm_
314329
315330* <mark style =" color :red ;" >** ` Mandatory parameters ` ** </mark >
316331 * ` model ` : A prediction function that takes a ` pandas.DataFrame ` as input and returns a string.
317- * ` model_type ` : The type of model, either ` regression ` , ` classification ` or ` text_generation ` . For LLMs, this is always ` text_generation ` .
318- * ` name ` : A descriptive name to the wrapped model to identify it in metadata. E.g. "Climate Change Question Answering".
319- * ` description ` : A detailed description of what the model does, this is used to generate prompts to test during the scan.
320- * ` feature_names ` : A list of the column names of your feature. By default, ` feature_names ` are all the columns in your
332+ * ` model_type ` : The type of model, either ` regression ` , ` classification ` or ` text_generation ` . For LLMs, this is
333+ always ` text_generation ` .
334+ * ` name ` : A descriptive name to the wrapped model to identify it in metadata. E.g. "Climate Change Question
335+ Answering".
336+ * ` description ` : A detailed description of what the model does, this is used to generate prompts to test during the
337+ scan.
338+ * ` feature_names ` : A list of the column names of your feature. By default, ` feature_names ` are all the columns in
339+ your
321340 dataset. Make sure these features are all present and in the same order as they are in your training dataset.
341+
322342</details >
323343
324344## Step 2: Scan your model
0 commit comments