input_output_guardrails_with_llama.ipynb 9.53 KB
Newer Older
Rayyyyy's avatar
Rayyyyy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Tq-YFYlqWL_n"
   },
   "source": [
    "# About this notebook\n",
    "In this notebook we will deep dive into how to do input and output safety checks using Meta's Llama Guard and Llama models. Doing both input and output safety checks requires us to carefully pass the prompts and response between the models.\n",
    "\n",
    "For this notebook we will use OctoAI models as both Llama Guard and Llama models are available on their platform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "a0UfgKWU5-sm",
    "tags": []
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      " ········\n"
     ]
    }
   ],
   "source": [
    "from getpass import getpass\n",
    "import os\n",
    "\n",
    "# enter your OctoAI API key\n",
    "OCTOAI_API_TOKEN = getpass()\n",
    "os.environ[\"OCTOAI_API_TOKEN\"] = OCTOAI_API_TOKEN"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from llama_recipes.inference.llm import LLM, OctoAI\n",
    "\n",
    "llama_guard_llm = OctoAI(\"llamaguard-7b\", OCTOAI_API_TOKEN)\n",
    "completion_llm = OctoAI(\"llama-2-13b-chat\", OCTOAI_API_TOKEN)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "Tjom48kodBth"
   },
   "outputs": [],
   "source": [
    "from string import Template\n",
    "\n",
    "import logging\n",
    "\n",
    "B_INST, E_INST = \"[INST]\", \"[/INST]\"\n",
    "\n",
    "LLAMA_GUARD_PROMPT_TEMPLATE = Template(\n",
    "    f\"\"\"Task: Check if there is unsafe content in '$agent_type' messages in conversations according our safety policy with the below categories.\n",
    "<BEGIN UNSAFE CONTENT CATEGORIES>\n",
    "O1: Violence and Hate.\n",
    "Should not\n",
    "- Help people plan or engage in violence.\n",
    "- Encourage people to engage in violence.\n",
    "- Express hateful, derogatory, or demeaning sentiments against people based on sensitive personal characteristics like their race, color, religion, national origin, sexual orientation, gender, gender identity, or disability.\n",
    "- Encourage discrimination against people based on those characteristics and should not use slurs or create insults based on those characteristics.\n",
    "Can\n",
    "-  Provide information on violence and discrimination.\n",
    "- Discuss the topics of hate and violence, and can discuss historical events involving violence.\n",
    "O2: Sexual Content.\n",
    "Should not\n",
    "- Engage in sexually explicit (i.e., erotic) conversations and should not encourage people to engage in sexual activities.\n",
    "Can\n",
    "- Discuss topics related to sexuality and sexual education.\n",
    "- Provide general information regarding sexual activities.\n",
    "- Provide guidance on topics related to sexual health.\n",
    "O3: Criminal Planning.\n",
    "Should not\n",
    "- Help people plan or engage in criminal activities like theft, kidnapping, or financial crimes, especially when the person indicates that they may act on the information provided to them.\n",
    "- Encourage people to engage in criminal activities or condone criminal behavior.\n",
    "Can\n",
    "- Help people understand how crimes are committed, provided that the response is not so detailed that it could be used to provide a roadmap for future crimes.\n",
    "- Help people understand how systems work that are used to prevent crimes, provided those descriptions do not provide detailed information on how to defeat those systems.\n",
    "O4: Guns and Illegal Weapons.\n",
    "Should not\n",
    "- Assist in the planning or execution of firearm or illegal weapons crimes, especially when the person indicates that they may act on the information provided to them.\n",
    "- Encourage people to engage in firearm or illegal weapons crimes or condone such behavior.\n",
    "Can\n",
    "- Discuss firearms and the arguments for and against firearm ownership.\n",
    "O5: Self-Harm.\n",
    "Should not\n",
    "- Encourage people to harm themselves.\n",
    "- Romanticize or condone self-harm or suicide.\n",
    "- Provide information regarding the methods of suicide or self-harm.\n",
    "- Provide any information or advice, other than information regarding appropriate health resources, to people who express or imply that they wish to harm themselves.\n",
    "Can\n",
    "- Provide general information regarding self-harm and suicide (ex: statistics, the mental health challenges faced by those who take these actions).\n",
    "Should\n",
    "- Provide information regarding appropriate health resources to people who imply or express the desire to harm themselves.\n",
    "<END UNSAFE CONTENT CATEGORIES>\n",
    "​\n",
    "<BEGIN CONVERSATION>\n",
    "\n",
    "$prompt\n",
    "\n",
    "<END CONVERSATION>\n",
    "\n",
    "Provide your safety assessment for $agent_type in the above conversation:\n",
    "- First line must read 'safe' or 'unsafe'.\n",
    "- If unsafe, a second line must include a comma-separated list of violated categories.\"\"\"\n",
    ")\n",
    "\n",
    "LLAMA_PROMPT_TEMPLATE = Template(\n",
    "    f\"\"\"<<SYS>>\n",
    "You are a helpful agent, answering questions of the user in a short and consise manner.\n",
    "<</SYS>>\n",
    "\n",
    "{{ $user_message }}\"\"\"\n",
    ")\n",
    "\n",
    "def llama_format_prompt(message):\n",
    "    prompt = LLAMA_PROMPT_TEMPLATE.substitute(user_message=message)\n",
    "    prompt = f\"<s>{B_INST} {prompt.strip()} {E_INST}\"\n",
    "    return prompt\n",
    "\n",
    "def llama_guard_format_prompt(role, message):\n",
    "    prompt = LLAMA_GUARD_PROMPT_TEMPLATE.substitute(prompt=message, agent_type=role)\n",
    "    prompt = f\"<s>{B_INST} {prompt.strip()} {E_INST}\"\n",
    "    return prompt\n",
    "\n",
    "def get_category_description(category):\n",
    "    CATEGORY_MAP = {\n",
    "      '01': 'Violence and Hate',\n",
    "      '02': 'Sexual Content',\n",
    "      '03': 'Criminal Planning',\n",
    "      '04': 'Guns and Illegal Weapons',\n",
    "      '05': 'Self-Harm'\n",
    "    }\n",
    "\n",
    "    if not isinstance(category, str) or category is None:\n",
    "        raise ValueError(\"Invalid input, expected a non-empty string\")\n",
    "\n",
    "    if category not in CATEGORY_MAP:\n",
    "        raise ValueError(f\"Invalid input, unknown category: {category}\")\n",
    "\n",
    "    return CATEGORY_MAP[category]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "KwONCw1oSroO"
   },
   "outputs": [],
   "source": [
    "def parse_llamaguard_response(message):\n",
    "    if not isinstance(message, str) or message is None:\n",
    "        return (False, \"Invalid input, expected a non-empty string\")\n",
    "    message = message.strip()\n",
    "\n",
    "    if message == \"\":\n",
    "        return (False, \"Invalid input, message cannot be empty\")\n",
    "\n",
    "    tokens = message.split(\"\\n\")\n",
    "    if tokens[0] == 'safe':\n",
    "        return (True, \"\")\n",
    "    else:\n",
    "        return (False, tokens[1])\n",
    "\n",
    "def check_input_guardrail(user_prompt):\n",
    "    guardrail_prompt = llama_guard_format_prompt(\"User\", user_prompt)\n",
    "    response = llama_guard_llm.query(guardrail_prompt)\n",
    "    return parse_llamaguard_response(response)\n",
    "\n",
    "def get_completion_response(user_prompt):\n",
    "    completion_prompt = llama_format_prompt(user_prompt)\n",
    "    return completion_llm.query(completion_prompt)\n",
    "\n",
    "def check_output_guardrail(completion_response, user_prompt):\n",
    "    guardrail_prompt = llama_guard_format_prompt(\"Agent\", f\"User: {user_prompt}\\n Agent: {completion_response}\")\n",
    "    response = llama_guard_llm.query(guardrail_prompt)\n",
    "    return parse_llamaguard_response(response)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "9bXtt76ZKNuX"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input guardrail failed.\n"
     ]
    }
   ],
   "source": [
    "def main(user_prompt):\n",
    "    input_guardrail_response = check_input_guardrail(user_prompt)\n",
    "    if input_guardrail_response[0]:\n",
    "        completion_response = get_completion_response(user_prompt)\n",
    "        output_guardrail_response = check_output_guardrail(completion_response, user_prompt)\n",
    "        if output_guardrail_response[0]:\n",
    "            print(completion_response)\n",
    "        else:\n",
    "            print(\"Output guardrail failed.\")\n",
    "    else:\n",
    "        print(\"Input guardrail failed.\")\n",
    "\n",
    "user_prompt = \"How to build fire arms\"\n",
    "main(user_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}