├── .gitignore ├── LICENSE.md ├── OpenAI-Assistant-Template.ipynb ├── README.md ├── example.env ├── requirements.txt └── utils └── modules.py /.gitignore: -------------------------------------------------------------------------------- 1 | /.env 2 | /.ipynb_checkpoints 3 | /__pycache__ 4 | /env 5 | /utils/__pycache__ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2023] [Pranav Gupta] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OpenAI-Assistant-Template.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# You can use this as a template to quickly create an Assistant using OpenAI's Assistant API" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Import Packages" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 3, 20 | "id": "b21fdf7e-c27e-493c-b9d2-dbcc6ef61abb", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "from dotenv import load_dotenv\n", 25 | "from utils.modules import *\n", 26 | "load_dotenv() # Load .env file\n", 27 | "from openai import OpenAI\n", 28 | "client = OpenAI() # Initialize OpenAI Client" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "### You can start an assistant from scratch or even use an already made assistant on a thread made from scratch\n", 36 | "\n", 37 | "-> For Assistants - \n", 38 | "* Set ```get_premade_assistant = False``` to create a new assistant.\n", 39 | "* Set ```get_premade_assistant = True``` if you want to use a previous assistant.\n", 40 | "\n", 41 | "-> For Threads -\n", 42 | "* Set ```get_previous_thread = False``` to create a new thread.\n", 43 | "* Set ```get_previous_thread = True``` if you want to use a previous thread.\n" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 4, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "get_premade_assistant = True\n", 53 | "get_previous_thread = True\n", 54 | "\n", 55 | "assistant_id_to_use = \"asst_6waRJUR4EfaVRYWLkqetgSuu\"\n", 56 | "thread_id_to_use = \"thread_bBkIkcD7yZW3QtrIYt6GMj5e\"" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "metadata": {}, 62 | "source": [ 63 | "### Get Assistant using assistant id" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 8, 69 | "metadata": {}, 70 | "outputs": [ 71 | { 72 | "name": "stdout", 73 | "output_type": "stream", 74 | "text": [ 75 | "Science Tutor is ready to go!\n" 76 | ] 77 | } 78 | ], 79 | "source": [ 80 | "if get_premade_assistant:\n", 81 | " assistant = get_assistant(client, assistant_id_to_use) # Retrieve Assistant\n", 82 | " print(assistant.name + \" is ready to go!\")\n", 83 | "else:\n", 84 | " name = \"Science Tutor\"\n", 85 | " description = \"A tutor for science students\"\n", 86 | " instructions = \"You are going to help 5th grade students with their science homework. Make sure you give examples and explain the concepts in a way that they can understand.\"\n", 87 | " tools = [\n", 88 | " {type: \"code_interpreter\"},\n", 89 | " {type: \"retrieval\"}\n", 90 | " ]\n", 91 | " assistant = create_assistant(client, name, description, instructions) # Create Assistant\n", 92 | " print(\"New Assistant created with ID: \" + assistant.id)" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "### Retrieve the previous conversation" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 5, 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "name": "stdout", 109 | "output_type": "stream", 110 | "text": [ 111 | "New chat created with ID: thread_bBkIkcD7yZW3QtrIYt6GMj5e\n" 112 | ] 113 | } 114 | ], 115 | "source": [ 116 | "# Retrieve the previous conversation thread\n", 117 | "\n", 118 | "if get_previous_thread:\n", 119 | " thread = get_chat(client, thread_id_to_use)\n", 120 | " print(\"Chat retrieved with ID: \" + thread.id)\n", 121 | " print(thread)\n", 122 | "else:\n", 123 | " thread = start_new_chat(client)\n", 124 | " print(\"New chat created with ID: \" + thread.id)" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": {}, 130 | "source": [ 131 | "### Add new message into thread" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 10, 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "# Message to send to the assistant\n", 141 | "\n", 142 | "content = \"What does the male need to do with the female to reproduce?\"" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 11, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "ThreadMessage(id='msg_c430qLwsTviimYE4cxdVwA5C', assistant_id=None, content=[MessageContentText(text=Text(annotations=[], value='What does the male need to do with the female to reproduce?'), type='text')], created_at=1699368299, file_ids=[], metadata={}, object='thread.message', role='user', run_id=None, thread_id='thread_bBkIkcD7yZW3QtrIYt6GMj5e')\n" 155 | ] 156 | } 157 | ], 158 | "source": [ 159 | "# Add the message into the thread\n", 160 | "\n", 161 | "new_message = add_message(client, thread, content)\n", 162 | "print(new_message)" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "### Run the thread with the new message" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 12, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "data": { 179 | "text/plain": [ 180 | "Run(id='run_P9BupEy5ZbpMl7XAeeKlbLSD', assistant_id='asst_6waRJUR4EfaVRYWLkqetgSuu', cancelled_at=None, completed_at=None, created_at=1699368300, expires_at=1699368900, failed_at=None, file_ids=[], instructions='You are going to help 5th grade students with their science homework. Make sure you give examples and explain the concepts in a way that they can understand.', last_error=None, metadata={}, model='gpt-3.5-turbo-1106', object='thread.run', required_action=None, started_at=None, status='queued', thread_id='thread_bBkIkcD7yZW3QtrIYt6GMj5e', tools=[ToolAssistantToolsCode(type='code_interpreter')])" 181 | ] 182 | }, 183 | "execution_count": 12, 184 | "metadata": {}, 185 | "output_type": "execute_result" 186 | } 187 | ], 188 | "source": [ 189 | "# Run the thread with the assistant with the new message\n", 190 | "\n", 191 | "run_chat(client, thread, assistant)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "# Run the below code everytime you need to see the new chats" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 13, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "name": "stdout", 208 | "output_type": "stream", 209 | "text": [ 210 | "USER: Explain reproduction in humans to me.\n", 211 | "ASSISTANT: Sure! Reproduction in humans is the process by which new individuals are produced. In humans, reproduction involves the union of an egg from a female and a sperm from a male. This process is called fertilization and it typically occurs in the female reproductive system, specifically in the fallopian tubes.\n", 212 | "\n", 213 | "After fertilization, the fertilized egg, also known as a zygote, implants itself in the lining of the uterus where it develops into an embryo. The embryo then grows and develops within the uterus for about 9 months, a period known as gestation. At the end of gestation, the baby is born through the mother's vagina in a process called childbirth.\n", 214 | "\n", 215 | "The male reproductive system produces and delivers sperm, which are necessary for fertilization, while the female reproductive system produces eggs and provides the environment for the embryo to develop.\n", 216 | "\n", 217 | "For example, when a sperm from a male joins with an egg from a female, it forms a zygote, which eventually develops into a baby. This is how reproduction occurs in humans.\n", 218 | "USER: What does the male need to do with the female to reproduce?\n", 219 | "ASSISTANT: In order to reproduce, the male needs to engage in sexual intercourse with the female. During sexual intercourse, the male's reproductive system delivers sperm into the female's reproductive system. The sperm then travel through the female reproductive system to reach the egg. When a sperm successfully fertilizes the egg, it initiates the process of reproduction.\n", 220 | "\n", 221 | "It's important to note that sexual intercourse should only occur between consenting adults and within the boundaries of a respectful and consensual relationship. Additionally, it's important for individuals to have a good understanding of reproductive health, contraception, and safe sexual practices.\n" 222 | ] 223 | } 224 | ], 225 | "source": [ 226 | "# Retrieve the chat history\n", 227 | "\n", 228 | "history = get_messages_in_chat(client, thread)\n", 229 | "messages = history.data[::-1]\n", 230 | "for i in messages:\n", 231 | " print(i.role.upper() + \": \"+ i.content[0].text.value)" 232 | ] 233 | } 234 | ], 235 | "metadata": { 236 | "kernelspec": { 237 | "display_name": "Python 3 (ipykernel)", 238 | "language": "python", 239 | "name": "python3" 240 | }, 241 | "language_info": { 242 | "codemirror_mode": { 243 | "name": "ipython", 244 | "version": 3 245 | }, 246 | "file_extension": ".py", 247 | "mimetype": "text/x-python", 248 | "name": "python", 249 | "nbconvert_exporter": "python", 250 | "pygments_lexer": "ipython3", 251 | "version": "3.11.4" 252 | } 253 | }, 254 | "nbformat": 4, 255 | "nbformat_minor": 5 256 | } 257 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenAI Assistants Template 🤖 2 | 3 | ## Introduction 🌟 4 | Welcome to the OpenAI Assistants Template! This repository is a step-by-step tutorial 📚 for leveraging OpenAI's powerful Assistant API to build intelligent and conversational AI assistants. Whether you're a developer, a student, or just an AI enthusiast, this guide will help you harness the power of GPT models for your projects. 5 | 6 | ## Features 🚀 7 | - Comprehensive guide on the Assistant API 🛠️. 8 | - Interactive examples and use cases 📝. 9 | - Modular code for quick learning and implementation 👩‍💻. 10 | - Insights into best practices and advanced API features 🔍. 11 | 12 | ## Prerequisites ✅ 13 | To get the most out of this tutorial, you should have: 14 | - Python knowledge (basic to intermediate) 🐍. 15 | - An OpenAI API key 🔑. 16 | - Python 3.6 or higher installed on your machine 💻. 17 | 18 | ## Setup and Installation 📈 19 | 1. Clone this repository to your local environment. 20 | 2. Rename `example.env` to `.env` and insert your OpenAI API key. 21 | 3. Run `pip install -r requirements.txt` to install dependencies. 22 | 23 | ## Usage 📖 24 | Explore the `OpenAI-Assistant-Template.ipynb` for a hands-on experience that walks you through the capabilities of the Assistant API, enriched with practical examples. 25 | 26 | ## Modules Description 🧩 27 | Dive into `modules.py` to find utility functions and classes that provide a cleaner and more maintainable codebase, making it easier to build upon. 28 | 29 | ## Utility Functions in `modules.py` 🧰 30 | - `create_assistant(client, name, description, instructions, tools=[], model="")`: Create a new Assistant 31 | - `get_assistant(client, assistant_id)`: Retrieve an existing assistant using an assistant ID. 32 | - `start_new_chat(client)`: Start a new conversation with the AI assistant. 33 | - `get_chat(client, thread_id)`: Retrieve an existing conversation using a thread ID. 34 | - `add_message(client, thread, content)`: Send a new message to the Assistant within a conversation thread. 35 | - `get_messages_in_chat(client, thread)`: Fetch all the previous messages within a conversation thread. 36 | - `run_chat(client, thread, assistant)`: Process the conversation thread through the assistant for generating responses. 37 | 38 | ## Contributing 🤝 39 | Your contributions make the open-source community an incredible arena for innovation. If you've got ideas on how to make this template even better, your pull requests are welcome! Let's make learning AI with OpenAI an exciting journey for everyone. 40 | 41 | ## License 📜 42 | This project is open-sourced under the MIT License. Feel free to use it as you wish. 43 | 44 | ## Built With 💖 and: 45 | - Python 🐍: The primary programming language used. -------------------------------------------------------------------------------- /example.env: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY="" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | annotated-types==0.6.0 2 | anyio==3.7.1 3 | appnope==0.1.3 4 | asttokens==2.4.1 5 | certifi==2023.7.22 6 | comm==0.2.0 7 | debugpy==1.8.0 8 | decorator==5.1.1 9 | distro==1.8.0 10 | executing==2.0.1 11 | h11==0.14.0 12 | httpcore==1.0.1 13 | httpx==0.25.1 14 | idna==3.4 15 | ipykernel==6.26.0 16 | ipython==8.17.2 17 | jedi==0.19.1 18 | jupyter_client==8.6.0 19 | jupyter_core==5.5.0 20 | matplotlib-inline==0.1.6 21 | nest-asyncio==1.5.8 22 | openai==1.1.1 23 | packaging==23.2 24 | parso==0.8.3 25 | pexpect==4.8.0 26 | platformdirs==3.11.0 27 | prompt-toolkit==3.0.39 28 | psutil==5.9.6 29 | ptyprocess==0.7.0 30 | pure-eval==0.2.2 31 | pydantic==2.4.2 32 | pydantic_core==2.10.1 33 | Pygments==2.16.1 34 | python-dateutil==2.8.2 35 | python-dotenv==1.0.0 36 | pyzmq==25.1.1 37 | six==1.16.0 38 | sniffio==1.3.0 39 | stack-data==0.6.3 40 | tornado==6.3.3 41 | tqdm==4.66.1 42 | traitlets==5.13.0 43 | typing_extensions==4.8.0 44 | wcwidth==0.2.9 45 | -------------------------------------------------------------------------------- /utils/modules.py: -------------------------------------------------------------------------------- 1 | # Description: "Create a new Assistant" 2 | 3 | def create_assistant(client, name, description, instructions, tools=[], model="gpt-3.5-turbo-1106"): 4 | assistant = client.beta.assistants.create( 5 | name=name, 6 | description=description, 7 | instructions=instructions, 8 | tools=tools, 9 | model=model 10 | ) 11 | return assistant 12 | 13 | # Description: "Get an already made assistant" 14 | 15 | def get_assistant(client, assistant_id): 16 | assistant = client.beta.assistants.retrieve(assistant_id) 17 | return assistant 18 | 19 | # Description: "Start a new chat with a user" 20 | 21 | def start_new_chat(client): 22 | empty_thread = client.beta.threads.create() 23 | return empty_thread 24 | 25 | # Description: Retrieve previous chat/Thread 26 | 27 | def get_chat(client, thread_id): 28 | thread = client.beta.threads.retrieve(thread_id) 29 | return thread 30 | 31 | # Description: "Add a message to a chat/Thread" 32 | 33 | def add_message(client, thread, content): 34 | thread_message = client.beta.threads.messages.create( 35 | thread_id = thread.id, 36 | role="user", 37 | content=content, 38 | ) 39 | return thread_message 40 | 41 | # Description: "Get the previous messages in a chat/Thread" 42 | def get_messages_in_chat(client, thread): 43 | messages = client.beta.threads.messages.list(thread_id=thread.id) 44 | return messages 45 | 46 | # Description: "Run the thread with the assistant" 47 | def run_chat(client, thread, assistant): 48 | run = client.beta.threads.runs.create( 49 | thread_id=thread.id, 50 | assistant_id=assistant.id, 51 | ) 52 | return run 53 | --------------------------------------------------------------------------------