🤯 OpenAI Assistants API Python (Full Tutorial)
Learn how to build with the new OpenAI Assistants API in less than 20 minutes and how to integrate GPT-4 into your applications. I'll show you how, step by step using a Python environment. Learn about Key Features like: Code Interpreter, Retrieval. and Function calling.
Chapters
0:00 Intro
0:21 Install OpenAI library
1:15 The Assistants API
2:12 Build OpenAI Assistants in python
4:11 Using OpenAI Threads
4:45 Using OpenAI Messages
9:30 Output from OpenAI Assistants API
10:00 Building Assistants with File Retrieval
15:00 Outro
▬▬▬▬▬▬▬▬▬▬▬▬ CONNECT ▬▬▬▬▬▬▬▬▬▬▬▬
🖥️ Website: www.assemblyai.com/?...
📈 Newsletter: www.assemblyai.com/subscribe
🐦 Twitter: / assemblyai
🦾 Discord: / discord
▶️ Subscribe: kzhead.info?...
🔥 We're hiring! Check our open roles: www.assemblyai.com/careers
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
#MachineLearning #DeepLearning
I really liked your video, clear and concise. Most senior programmers can't even explain the simple steps properly. Thanks!
I appreciate how clear and concise your explanations were throughout the process.
You are fantastic! this is EXACTLY what I was looking for. Thank you. Very clear, specific, and to the point. I watched a different creator's video that was over an hour and was completely lost. Yours was SO good.
This is the most clear explanation I've seen so far on the topic. The only inconsistency is redefining a 'run' variable on 7:50
Thanks, this helped me to get this working. Many other sources try to fit their explanations to so broad audience that the essense "how to do this" is lost in the mess starting what is python type fo quesitons. This was good and lacked all that noise!
Would love to see a tutorial now on using the assistant in a chat ui. Would be cool to see how to approach that :)
This video introduces in detail how to create an API call file in a local program. Based on this architecture and the API Reference provided by OpenAI, you can implement an Assistants API call file that is unique to your project. This is definitely a precious resource for those who are ready to start development. At present, most KZheadrs have not explained it in such detail.😁
I found this extremely helpful. I've been using Assistants in playground on the dev site. Im using it for coding. I'm trying to imagine how i will use this in this context, but the step by step here was super helpful.
Thanks @Smitha for explaining about Openai assistant I created multi AI agents with help of your videos
Great video, simple and to the point
Anyone struggling to get a response, you might be trying to the retrieve it before it is finished. So wait until you get the run.status as completed after retrieval. Should be able to view the response after that.
exactlly! The purpose of step5 (runs.retrieve) is not to get the messages result, but to check the run.status. If the status is not completed, we can add a loop with sleep(1 or 2 seconds) and retrieve the status again, until we reach the completed status. Then go to the next step to print the messages. Thanks and appreciate for the video and comments.
Thank you! It helped a lot to understand how assistants work.
This is very well done, thank you very much.
thank you so much for this walkthrough. I spent two days working on the Quick start but I couldn't get the function to import the secret key, I didn't realize I could just insert it right into the function (I know it's not recommended for serious projects but I just wanted my request to work, as this is my first time working with the API)
You explain very well! Thanks for the video!
Extremely clear explanation, you are an awesome teacher
Yes thank you so much I took your old tutorials I think we're using torch and it's so awesome that we're in this new age and I could count on an awesome woman to teach me!
You are very welcome!
Great video. I have a question: if I use codes shown in video as server-side backend, and use XMLHttpRequest to send requests (e.g. user entered questions) and receive/display AI's responses, how do we let openai know that chat chain belongs to one thread id? In another word, if user keep asking questions, how do we make multi Runs within one thread?
Bravo for your tutorial. 👍👍 This is really well explained!! I think this is the basic foundation for becoming a developer😇🤔
Hello, I have a long text that I would like to split into 10 segments. I plan to summarize each segment using an API or assistant and then integrate these summaries. How can I ensure that all these interactions occur within the same conversation thread like in ChatGPT interface, allowing the API to remember the context? Thank you.
Superb insights. Thanks for your efforts. Success !
I want to build something with the Assistants API for my website. Is there also a word limitation for it like in GPT-4? When Im using GPT-4 in the chatbot, i need to write „continue“ after roughly 1200 words. What I need for my website is, that it generates 3000 words in one response (needs to be an analysis of something). Is this possible with the assistants api? If the answer is no, is there any workarounds?
Hi, thanks for this great explanation! How can I attach multiple files to the same assistant so it uses them simultaneously instead of just one?
You can upload multiple files and pass a list in the `file_ids` parameter when creating an assistant.
Great, finally something clear ! @AssemblyAI How can we have this view with PHPStorm ?
Can you place a file path and do a loop for all files in a directory/folder? What would that look like?
i have custom GPT Model and created its assistant over there as well. Now how to use the API of assistant to integrate the custom GPT in my web app. Plz answer
I'm trying to follow this just in a python script, but I keep getting the error "ImportError: cannot import name 'OpenAI' from 'openai'". What am I doing wrong?
i have already had credentials from my custom GPT in GPT store. how can i connect it to my separate app with assistant API
Thanks & Appreciate for making this video so easy to implement.
Glad it was helpful!
What system are you using to create this I tried to email Assembly AI from your website, but it would not let me.
Definitely not for beginners but presentation at this level is very decent along with voice control that has clarity.
very helpfull
Error: for message in reversed(messages): TypeError: 'SyncCursorPage[ThreadMessage]' object is not reversible
They may have changed the object since this video was made. Correct code should be: for message in reversed(list(messages)):
Very very good!
Is there a link to the GitHub for the python code, or to the Jupyter notebook?
Very informative. However, I have a question: is it possible to retrieve the assistant's response as soon as a query is given by the user? To develop interactive chatbots and build context, the user has to know the model's response for their query, isn't it?
Hi there, I'm trying to replicate this code, I got credit for the API environment but I just can't get the Assistant's reply. Any suggestion? I can see the assistant_id, the thread_id but there's no way to get the answer (I tried changing the model too). Thanks for the help
bro did you find out the answer I am stuck in the same issue
You need a time delay between creating the thread run and retrieving the answers/messages. Smitha has every element in a new code block, further down someone suggested a forced time delay. Either way works
can I also integrate the assistant api via JS on my website?
If not getting response, before retrieve add: import time time.sleep(20)
nice try, didn't fix it for me tho
@@GregorSchafrothAI it's not necessary to use the "sleep". Just run the "retrieve" until the run status is "completed". Change the step 5 from the video to: while run.status != "completed": run = openai.beta.threads.runs.retrieve( thread_id=thread.id, run_id=run.id ) print(run.status) time.sleep(2)
Or just split the code out into separate sections ... the time taken to click on run for each section introduces sufficient time gap for it to get a response
thank you for this clear video! Can you make another one with instructions of how to make same mechanic but user is asking questions and get answers from Assistant via simple web interface?
you have to pay to make it work?
@@kamalam1085 just some 0.01 cents for open ai API
Thanks for the tutorial . A quick question: How do one deploy this to a business or a company
you have to pay to make it work?
THX,It's still a bit difficult for someone from another industry.
Thanks for this! Do you provide the code for this tutorial anywhere?
hey thanks for the VIdeo it is very helpful. I have tried the code but facing some issue with my Assitant . It is only printing user response not the Assitant response can you help me with that. whaat might be a reson for that ?
Are you trying on VS code or Collab. Try on vs code
same thing here mate... Im not sure why
same here !@@estebanseguel7004
I ran in the same problem with the file upload. There I can't even check on the status. If there is a better way to handle this than time.sleep(), let me know.
@@estebanseguel7004 same have u found out why?
when i am putting all the code inside a single shell , it's only printing user's message , it's not printing assistant's response .why such?
same here did you find any fix?
Run the "retrieve" until the run status is "completed". Change the step 5 from the video to: while run.status != "completed": run = openai.beta.threads.runs.retrieve( thread_id=thread.id, run_id=run.id ) print(run.status) time.sleep(2)
Thank you@@paulobitfranca , exactly what I was looking for! Also I had to add import time
@@paulobitfranca thanks man
Can you give us the link to Git or the code for this?
Great video. Could you please share the notebook? Thank you
Informative. At the same time the description there is a mentioning of "Function calling". But that as a concept is not explained in the video. Can you modify the description so it won't be misleading? Thanks
How do you know if the assistant is using the research paper rather than just making things up on its own knowledge?
How to send to and fro messages?
Can you get really into detail ... In your next tutorial...........I create a blender python add on it's like the biggest in the world code wise ....FAST Animation Studio Toolz....and I'm gonna be packing artificial intelligence features in to this and I'd like if there was some information I could use to Know how I could manipulate blender operators with open AI easy..
Thanks for sharing this video. I have tried same code in colab using model="gpt-3.5-turbo", I didn't get assistant response in step 4. When I checked run.status value it is returned as failed. Can anyone advice me how to solve this issue?
Same issue
@@GregorSchafrothAI same problem, but i charge it 5 dolars and it work. i dont know why.
I have the same issue
@@DanielTorres-cn8kh you need to top up some some money to OpenAI then it will work. Or at least that's what solved it for me
Please make a video on OpenAI assistant to make a API call to third-party using functions
Do you hapen to have the whole code? I would happily buy it
what to do with a frontend in a web application?
does anyone have a clue how to fix this error : cannot import name ‘OpenAI’ from ‘openai’
🎯 Key Takeaways for quick navigation: 00:00 *🌐 Introduction to the OpenAI Assistants API, still in beta, for building AI assistants in Python.* 00:26 *💻 Instruction on installing the OpenAI library and obtaining an OpenAI API key.* 01:04 *🔑 Steps to authenticate by creating and using a client object with the OpenAI API key.* 01:17 *🤖 Overview of OpenAI Assistants: Customize personalities, capabilities, and integrate multiple tools.* 02:12 *🚀 Creating an assistant with a specific role (e.g., math tutor) and defining its capabilities.* 03:14 *🧠 Selection of the GPT-4 model for the assistant's underlying technology.* 03:45 *🧵 Concept of threads in assistant interactions for organizing messages.* 05:13 *✉️ Creating and linking messages to threads to simulate conversation flow.* 06:32 *▶️ Initiating the assistant to process and respond to queries.* 07:14 *📬 Retrieving and displaying the assistant's responses to ensure the communication loop.* 09:50 *📁 Advanced example of creating an AI assistant that processes and responds to content from uploaded files.* 10:19 *🗃️ Uploading and specifying files for the assistant to use for knowledge retrieval.* 11:43 *🤖📚 Adjusting the assistant's purpose for specialized tasks, like analyzing a research paper.* 13:07 *🧪 Demonstrating the assistant's ability to handle complex inquiries based on specific document content.* 14:33 *🔄 Highlighting the iterative process of refining questions and receiving responses to build a dynamic interaction.* 15:01 *🛠️ Mention of the beta status of the API, indicating ongoing development and future improvements.* Made with HARPA AI
I followed along with Co Pilot. I typed the first couple of letters and it fills in what is on the KZhead vid... Madness.
Great tutorial. just a heads up you spelled assistant wrong in the file name. Not a big deal at all but I noticed it and thought I would point it out considering the rest of your tutorial was spot on. Not trying to be a smart a** thanks again for the great information :)
Hmm for some reason the "Assistant: The solution..." didn't return even though I did exactly as you did?
same here, i dont know why
Thanks for your sharing but why kepe this error appear 'Beta' object has no attribute 'assistant' in assistant = client.beta.assistant.create( name='Math tutor', instructions="You are a personal math tutor. Write and answer the code.", tools=[{"type": "code_interpreter"}], model="gpt-4.0-turbo" )
it should be assistants with an S i think
It does not work using the gpt-3.5-turbo-1106 model. There is no output of assistant. Did someone run into the same problem?
hey did you found any answer for it
No response solution: while run.status != "completed": run.status = client.beta.threads.runs.retrieve(thread_id = thread.id, run_id = run.id) sleep(1)
🎯 Key Takeaways for quick navigation: 00:00 🎓 *Introduction to OpenAI's new Assistants API* - Introduction to OpenAI Assistants API and initial setup requirements, - Installation of the OpenAI Python library, - Obtaining an OpenAI API key. 01:04 🛠️ *Setting up the OpenAI client and creating an assistant* - Importing the OpenAI library and creating a client object with the API key, - Explanation of the OpenAI assistant's capabilities and tools, - Creating an assistant object with a specific name and instructions. 02:40 🧮 *Creating a Math Tutor Assistant* - Setting up an assistant to function as a math tutor, - Specifying tools and the model for the assistant, - Initiating the first thread and message within the assistant. 05:13 ✉️ *Sending and Running Messages in the Thread* - Creating and sending a message to the thread with a math problem, - Running the assistant to process the message, - Retrieving and printing the assistant's response. 07:00 📄 *Integrating File Retrieval with AI Assistant* - Uploading a file to OpenAI for the assistant to use, - Creating a new assistant with file retrieval capabilities, - Sending a content-specific question to the new assistant. 10:19 🤖 *Creating an Assistant for Research Papers* - Uploading a research paper for the assistant to reference, - Modifying the assistant creation code for a machine learning researcher persona, - Running the assistant and displaying its response to a research-related question. 13:37 🔄 *Continuing the Conversation with the Assistant* - Continuing the conversation by asking additional questions, - How to change the query and retrieve new responses, - Mention of the beta status and the need for improved documentation and resources. Made with HARPA AI
doesn't work. it doesn't include a reply from the assistant
I don't know what was more interesting to look at, the OAI Assistants code or the beautiful host teaching it to everyone.
🎯 Key Takeaways for quick navigation: 00:00 🤖 *En este video, Smitha de Assembly AI muestra cómo usar la nueva API de OpenAI llamada Assistance API para construir tu propio asistente de inteligencia artificial en Python.* 02:12 🧠 *Al crear un asistente, puedes acceder a los modelos de OpenAI, darle instrucciones específicas sobre su personalidad y capacidades, y también acceder a herramientas como el intérprete de código.* 04:11 🧵 *Para crear un asistente, se inicia creando un objeto de asistente con un nombre, instrucciones, herramientas (como el intérprete de código) y el tipo de modelo (por ejemplo, GPT-4).* 06:16 🗣️ *Se crea un hilo y se añade un mensaje al hilo para interactuar con el asistente. En este caso, se le pide al asistente resolver una ecuación matemática.* 09:35 📝 *Se muestra un ejemplo práctico donde el asistente responde a una pregunta matemática, demostrando cómo puedes crear tu propio asistente personalizado.* 11:30 📚 *Smitha luego presenta cómo crear un asistente vinculado a archivos usando la recuperación de conocimiento, subiendo un archivo y creando un asistente que responde preguntas basadas en ese archivo.* 14:47 🚀 *Se destaca que puedes ampliar la conversación, hacer más preguntas y vincular otras herramientas a tu asistente a medida que desarrollas aplicaciones prácticas con esta API.* Made with HARPA AI
is that code available?
when i run the code it gives me the error: openai.BadRequestError:Error code: 400 - {'error': {'message': "The requested model 'gpt-4-1106-preview' does not exist.", 'type': 'invalid_request_error', 'param': 'model', 'code': 'model_not_found'}}
me also get the same error message. later I change it to gpt-3.5 model. But I could not get the message of the assistant like she got in this video. Does any one know the reason
@@student7818 Had the same. I went to open AI api keys and under Settings > Billing saw that I had no credit. There is/was a free credit of $5 given to people, which expires 3 months after creating account. You can add as little as $5 to your account. Do so, to get an API credit, and try again. This fixed the error for me, and I can see my API calls under "Usage" on the web portal for the keys. However, I still am not yet getting an actual response back from the assistant.
Cool""😁""🐤i know, i'm..
What is actually use of this assistant....?if you can't implement these
great explanation, Likely this is not going to fly. Too complicated, the majority of the people dont use threads. They have to remove all that, and just put the normal chat completion with 2 more variables assistant and file id...
Where's the source code?
Some of us noobs have no idea what program that is your are working in from the get go....
Could share you collab?
If an AI make music, does it use algorythm ?
I'm getting BadRequestError 400. Is it because it paid?
Your API key is not allowed to use gpt-4-1106-preview
@@northdecatur thank you
It's valid to clarify that before using the api_key to build you app you should pay for it. Just saying...
не понимаю, зачем снимать видео и переписывать его с официальной документации, если я тоже могу переписать все с официальной документации и записать видео на 15 минут, которое ничем и не помогло, мдам
scripte ples
°\\• I believe we are meant to be like Jesus in our hearts and not in our flesh. But be careful of AI, for it is just our flesh and that is it. It knows only things of the flesh (our fleshly desires) and cannot comprehend things of the spirit such as peace of heart (which comes from obeying God's Word). Whereas we are a spirit and we have a soul but live in the body (in the flesh). When you go to bed it is your flesh that sleeps but your spirit never sleeps (otherwise you have died physically) that is why you have dreams. More so, true love that endures and last is a thing of the heart (when I say 'heart', I mean 'spirit'). But fake love, pretentious love, love with expectations, love for classic reasons, love for material reasons and love for selfish reasons that is a thing of our flesh. In the beginning God said let us make man in our own image, according to our likeness. Take note, God is Spirit and God is Love. As Love He is the source of it. We also know that God is Omnipotent, for He creates out of nothing and He has no beginning and has no end. That means, our love is but a shadow of God's Love. True love looks around to see who is in need of your help, your smile, your possessions, your money, your strength, your quality time. Love forgives and forgets. Love wants for others what it wants for itself. Take note, true love works in conjunction with other spiritual forces such as patience and faith (in the finished work of our Lord and Savior, Jesus Christ, rather than in what man has done such as science, technology and organizations which won't last forever). To avoid sin and error which leads to the death of our body and also our spirit in hell fire, we should let the Word of God be the standard of our lives not AI. If not, God will let us face AI on our own and it will cast the truth down to the ground, it will be the cause of so much destruction like never seen before, it will deceive many and take many captive in order to enslave them into worshipping it and abiding in lawlessness. We can only destroy ourselves but with God all things are possible. God knows us better because He is our Creater and He knows our beginning and our end. Our prove text is taken from the book of John 5:31-44, 2 Thessalonians 2:1-12, Daniel 7-9, Revelation 13-15, Matthew 24-25 and Luke 21. Let us watch and pray... God bless you as you share this message to others.
thanks for great content, but one suggestion, I prefer where you don't have to type the code on the screen. just eats up unnecessary time and this is video after all.
How come your code box says Python, can you make a dumb version for non-developers?
the api key is paid ..... you should tell that before completing
You should Google that
What a tool :D
If u don't know that, then you shouldn't be watching this video
I’m glad y’all beat me to commenting that they were stating the obvious 😂
Lmao 20 dollars a month for what would be magic 7 years ago
The API documentation from openAI looks more clear than this video...try to add value in the video , dont hust read the api doc and explain it here , we can do that too in less time ofcourse
Hi I just ran this script (below) but I only got my own message/prompt output to the terminal, not the response! 😄 from openai import OpenAI # Create client objet and set OpenAI API key client = OpenAI(api_key="my_key") # Upload a file with an "assistants" purpose file = client.files.create( file=open("ss_output.txt", "rb"), purpose='assistants' ) print(file) assistant = client.beta.assistants.create( name = "Data Guru", instructions="You are great at data processing-particularly text files and CSVs!", model="gpt-4-turbo-preview", tools=[{"type": "retrieval"}], file_ids = ["file-kHE4llGj5A8b24ot2A6WqAvc"] ) thread = client.beta.threads.create() print(thread) message = client.beta.threads.messages.create( thread_id = thread.id, role = "user", content = "Fix/clean the data in this CSV file (attached) so it is properly formatted and output the cleaned version. In particular: - Remove any odd characters, e.g, \"`\" - Remove any sentences and only leave the correct data in each column - Convert any Names or Titles to title case - Remove duplicate header rows.") run = client.beta.threads.runs.create( thread_id = thread.id, assistant_id = assistant.id ) run = client.beta.threads.runs.retrieve( thread_id = thread.id, run_id = run.id ) messages = client.beta.threads.messages.list( thread_id = thread.id ) for message in reversed(messages.data): print(message.role + ": " + message.content[0].text.value) Any idea where I went wrong? I was just trying to type along... No errors just no response.
The most helpful api tutorial yet ! I was getting so fed up with lack of progress. Thank you a millie. Maquina.KANIKI