← все видео

I Built the Agentic Loop in Laravel from Scratch

Laravel · 2026-04-09 · 22м 18с · 4 832 просмотров · YouTube ↗

Топики: ai-loop-engineering

🎧 Аудио

📝 Summary

model=deepseek-v4-flash · prompt=summary-v7 · 6 276→3 558 tokens · 2026-07-20 11:50:11

🎯 Главная суть

Agentic loop — механика, при которой ИИ-модель сама решает, когда ей не хватает данных, вызывает один или несколько инструментов, получает результаты и на их основе формирует окончательный ответ. В видео реализован такой цикл в Laravel на чистом OpenAI API: от простого чата до множественных кастомных функций (получение календарной доступности, запрос к GitHub за последним релизом), завершающихся ответом, который модель не могла бы дать без внешних данных.


Подготовка окружения и первый вызов OpenAI

В новом Laravel-приложении устанавливается пакет openai-php/client. Ключ API сохраняется в .env, загружается через сервис. Создаётся консольная команда chat, в которой инициализируется клиент и совершается запрос к модели gpt-4.5 с текстом «Hello». Ответ выводится в консоль. На этом этапе это статический однократный запрос.

Интерактивный диалог и ограничения модели

Команда дорабатывается: добавляется цикл, в каждой итерации пользователь вводит сообщение, а ответ модели выводится через спиннер (используется библиотека leovol/laravel-prompts). Уже в этом простом диалоге выясняется, что модель не знает актуальных событий — на вопрос «What is the latest Laravel release?» она отвечает неверно или устаревшими данными (версия 12, хотя вышла 13.4). Причина: модель обучена на срезе данных, не включающем последние изменения.

Встроенный web search tool

Первый шаг к решению — добавление встроенного инструмента type: "web_search_preview". Теперь модель может выполнять поиск в интернете. Ответ на тот же вопрос улучшается (модель видит, что последняя мажорная версия 13, но всё ещё не может назвать точный номер патча или детали). Для точных и структурированных данных требуются собственные инструменты, работающие с конкретными API.

Кастомный инструмент: календарь доступности

Определяется новый инструмент типа function с именем get_calendar_availability, описанием «get available recording dates» и пустыми параметрами. В реализации — массив с парами «дата → true/false», который эмулирует доступность автора на ближайшие дни. Этот инструмент добавляется в массив tools при вызове API.

Цикл обработки одного tool call

После ответа модели проверяется наличие function_call в response->output. Если вызов найден, выполняется соответствующая функция (в данном случае get_calendar_availability). Результат (JSON) отправляется обратно модели в новом запросе с указанием previous_response_id и input типа function_call_output, содержащего call_id и output. Теперь модель знает, что, например, «вторник и четверг» — свободные дни, и отвечает на вопрос «когда есть время записать видео?» на основе этих данных.

Множественные инструменты: получение релиза Laravel с GitHub

Добавляется второй инструмент get_latest_laravel_release. Его реализация выполняет HTTP GET к api.github.com/repos/laravel/framework/releases/latest, извлекает tag_name, name, html_url и body. Этот инструмент также добавляется в список. Теперь ответ модели может содержать несколько function_call. Логика переделывается: все вызовы из response->output собираются в коллекцию, для каждого выполняется нужная функция, и все результаты передаются в одном новом запросе (каждый function_call_output со своим call_id). Цикл повторяется до тех пор, пока модель не решит, что данных достаточно.

Совместная демонстрация

Пользователь задаёт комплексный вопрос: «Какой последний релиз Laravel? Когда есть время записать видео о нём? Назови три самые важные функции». Модель принимает решение запустить оба инструмента. После их выполнения она получает даты доступности и структуру релиза 13.4 (с тремя ключевыми функциями, например, «Form request strict mode»). Ответ выводится единым сообщением — это и есть agentic loop: модель сама выбирает и вызывает нужные инструменты, в цикле «запрос → выполнение функции → новый запрос» до готовности.

Суть и возможности расширения

Agentic loop — это ядро любого AI-агента. В примере реализованы два простых инструмента, но по той же схеме можно подключать любые внешние сервисы (Google Calendar, Notion, Trello). Для продакшена код стоит вынести в отдельные PHP-классы, а ещё проще — использовать готовый Laravel AI SDK, который автоматизирует весь цикл. Понимание механики позволяет создавать кастомных агентов без чёрных ящиков.

📜 Transcript

en · 3 813 слов · 47 сегментов · clean

Показать текст транскрипта
What makes an AI agent different from a simple chatbot? One thing, the agentic loop. Leovol makes working with the AI SDK incredibly easy. You do find tools, have your prompts, and the agent just figures it out. But what's actually happening under the hood? Today we're going to build the agentic loop from scratch in PAP and Leovol, so you truly understand how AI agents work. We are going to start here from scratch with a new level application. I just installed this new application. Nothing in here yet. And we're going to use OpenAI here as our AI model provider. And I'm going to work with the OpenAI PHP client, which is really great for our use case today. Okay, that's installed. And now inside this application, inside PHP Storm, the only thing that I have already added here is inside services. We have our OpenAI key settings here defined. and my key i have already added to my environment file okay and we're going to trigger now a new ai call through a console command i'm just calling this chat command and what we're doing here is chat chat with ai we keep this very simple here and now we're creating here a new client from the new open ai library which we're using and we're going to load now our key which we have here services open ai key all right so this gives us a new client and we're now getting new response by calling on responses we're going to create a new one and here we're going to need to define the model which in our case is gpt 4.5 and the second argument here is our input and we're going with a static string here of just hello Now we're going to print out the response and we should have here output text. All right. So PHP artists chat. Let's trigger this command. Okay. Something is working. Hello. How can I help you today? Okay. Perfect. So we've made a very basic API call to the OpenAI model, which we're using here and we got a response back. Okay. Pretty straightforward so far. So let's update this a little bit and now. For the input, we are using a lower prompt here and we're calling this U, which is the label. Placeholder is hello. And now we are using this input here, so we don't have here a static value. And let's try this now again. I have art is my shortcut for PHP Addison. Chat, now we have this input here. Hey, what's going on? and this should still be working and it's now a little bit nicer not much just here and ready to help what's up with you okay perfect so we have now this amazing ai model which is capable of so many things um let's give me a short lower song that is funny and as you can see it just can do lots of yeah funny thing sure here's one level blues i woke up late my app was down php artisan turned it all around Routes were crying, Cash was mad, but Composer update made things worse. How bad? Blade was slicing, Eloquent was slick, then one small typo made the whole thing sick. All Laravel, you Eloquent queen, what's my bug? Always on line 17. I mean, yeah, that's funny. The point here is we have the iModel, we can lots of things, but yeah, this is now very limited. So if I would ask it, what was the latest Laravel? release what do you think we will get back so we can already tell you if you mean level oh yeah misspelled that the latest stable release series is level 12 year you can see those ai models are pretty outdated because they were trained on a lot of data from the internet from a couple of years ago so yeah we don't get here the latest information when we ask it things like what's the latest level release so the idea is now today in this video we're trying to here help our ai by creating some tools that our ai model can use trigger and then use this information from these tools to provide us better feedback here and better responses but before we're going to do this we're going to make this a little bit better to use because currently we just have one input and then it stops immediately so we're making a loop here so this ends down here all right so now we're inside a loop And then what we're going to do here is we are changing the response to be a task here. And we're going to give this a label called thinking. So this is also a label prompt feature, which you can see is very handy. And the second argument is a callback, which is a closure. And then we just need to close this off here like this. We need to import a function. Okay. So what we're doing here, we're wrapping now our API call inside this task, which will give us a nice spinner. And we're also now inside this loop. So as long as we have here some feedback, we are still staying inside this loop. So let's give this a try. Hey, now we get this nice spinner thinking, how can I help you? Nothing. All good. And you can see this is still working. Okay, so this is now a little better for us for testing. And we also have some nicer output. And as always, yeah, checkout level. prompts all those features here are just amazing they look so cool in your terminal okay but the point here is now we want to add a tool here and the most simple tools that we can add first we're going to provide tools here through through our api call and every tool is an array item with a specific type search preview which we can use with open ai so many models have some specific web search tools that you can just provide here and then they have something where they are going to trigger the web search or something that we don't have to do on our site and this should be it let's give this a try what is the latest laravel release again a typo here but it's a good thing about ai they don't matter about my typos they don't complain so let me see what we get back here now the latest major level release was level 13 which is already good If you mean the latest framework package version on GitHub, the result I found was 1244. Okay, so you can see it's already way better, but it's still missing some exact details about. So it's just getting this by searching and Googling for the right answer. And yeah, it can really tell me here about what's the latest minor release. So that's, yeah, if you want to get to know the specific information, a web search is just not enough. So what can we do about this? We can create our own tools here. So I'm going to paste here in one because it's a little bit lot to write. So the new type is now called function. So this is something that's being called here on our site and then we provide information. The name get calendar availability. So this will be about if the AI so that the AI can tell if I have time on a specific day to record a video. Description get available recording dates. And then for the parameters, we don't have one. We just need to provide here some boilerplate. So that's an object. Here we have the properties. We keep it empty. But for example, you could provide a from or to date in order to look for something through some specific parameters here. But in our case, we don't need that. We're just going to provide the I some days here where I have or have not time. And then the I can figure out the rest. So that's the way it is a little bit easier for us to handle. Okay, and in order to let the AI know if I have time or not, get calendar availability, which just gives an array of some dates here and tells if I'm available at this day or not. So very simple for now, but you could all think that this could maybe connect you to your Google Calendar and you provide some dates from there, or yeah, there's a lot you can do. In this case, we're just keeping it simple with an array. of these dates where I'm available and where I'm not for the next couple of days. Okay so let's go back here. So what do we have to do here now? So after this first response here, let's go back down here before we type something out. We are now creating a new loop here and this loop is about the tool calls. And in order to check if we need to make a tool call, what we're going to do is we're going to make a collection. of the response and the output. So in the output of the response typically there's just a message here with the response but if the AI feels like hey I would love to use one of your tools because this sounds like it can help me to provide a better response then we have some function calls here as well and we can find them. Let's do this by first where the type is called function call. Okay, and if we don't have a tool call, then we're just creating a new line and a new info, basically just this here. Okay, now it's fixed. So if we're going to make a loop here, we're going to check if we have some tool calls here by using a collection. And then if we don't have a tool call, we're just providing the response back similar to what we had before. And I think we also got to break out here of the loop. But if we have a tool call, let's make this very simple for now. Let's call this tool. Tool result equals this get calendar availability. So we're going to assume here that if there is a tool call from the AI, it must be only the one that we have here and then we're calling. We're going to call this here immediately. And then let's also make a new line here. And let's just info out that our tool was called. So very similar to coding agents. ChatGPT or other tools here where you would also see if the AI model is doing a web search or using other tools here you would also see this in the UI and now let's we're going to copy this here we're going to make another call now to the AI but now we don't need to provide the tools anymore and what we also need to do we now need to respond to a specific call from the AI from before And we're going to find this with previous response ID. And we're going to grab the response ID from the response from before. So what's different is now we don't have a text input like before. Now we're providing the information from our tool. So there's a new array item. It has a type of function called output. And the call ID is which we have inside our tool. And that our tool call and it's called call ID I believe. And then the only thing missing here is the output, which is our tool result just JSON encoding. Okay, let's go through this again. So up here, we're creating a new client in order to make call to OpenAI. Then we have this loop to keep the conversation going. If I ask something, we get a response back. I can ask something again and so on. This is the first input we are providing by typing something. Then we are providing this into the input of this OpenAI call and inside this call we are telling OpenAI in this case, hey, here's the input, here's what the user wants, but I also want you to let you know that we are providing some tools here. First one, this is of OpenAI, a web search tool, but this other one is a function tool which we are providing and here we have the information and the description here and the description helps the AI model to think if this cool tool could help us to provide a better response to the user. We don't have any properties here so this means after that we're creating another loop. We need to create the loop because you have to think about maybe there are multiple tool calls that could be triggered before we send something back to the user. Okay so we are collecting from the response output this is where the AI would respond to us that it wants to provide it, wants to run a tool call and with the type function call. Okay if we don't have a tool call we just provide the info back but if we have one we are telling out we are here getting the result of our function we are providing my availability and then we're making another call to OpenAI where we're going to respond to the previous response from OpenAI and in the input here we are providing specific input which is a function called input for a specific tool call with a specific output okay um yeah this was a lot let's see if this is working okay let's try with something where we wouldn't trigger a tool called just hey do we get something back yeah we do but now let's try something different when do i have time this week to record a new video okay now the i model should see it has already taught um has already called our tool let's forget this input here and then you have time to record a new video on those two days where i have provided in the array items that i'm available for this and i really hope you could see how useful this now is that the ami model can use specific tools running in our hand to provide specific information on our side like some specific dates where i have time to record a new video and now this conversation becomes more personal in the ai model or this ai conversation can help us a lot more than before and it's not just a response and a question here from my side it now can in between run this loop to call some tools and then the ai at some point decides okay now i got enough information now i don't need any other tools to be called now i can respond back to the user okay but back to application here where we were first using the built-in web search tool then we're creating our own tool in order to find out my calendar availability and when we think about an example from before getting the latest release which is something that i do almost weekly videos about so how can we yeah give the ai some information about this and this is also actually pretty simple so here in satinco well we can make just an http request to the github api and we just go to level frameworks releases and check out the latest and if we're going to run this we should see yeah the latest one is 13.4 which was released i believe yesterday and inside i think there's also body somewhere yeah here inside the body we see all those new features which could be something very useful to me when i ask the ai about the latest release okay so since this is just an http call here we can also make a tool in order to yeah give this information to the ai model so we're going to create here a new tool or new tool definition so i'm going to copy the code in here this again is a function get latest level release is a name description get the latest level framework release from github again we don't have any properties here because we don't need to provide something that's why this is almost empty here okay then we also need another function here in this application Of course, later we're going to clean this a little bit up. And here we have it. We're going to import the HTTP facade here. All right. And we don't have any headers. So let's get rid of that. Okay. Like this. And now we're just returning here. Release tag name, name, HTML, URL, and body, which is enough for the AI to do something with this and provide this in a format that I can work with this. Okay, so what do we need to change here? A few things. So currently we have hardcoded that we are just getting, if we need a tool, we're going to get this from the calendar. So, and we're starting by changing this here. We're going to call this tool calls. And now we're getting rid of the first because now we grab multiple ones, if there are multiple ones. And then we're just grabbing here the values. And then we're checking here if... Let's make this tool calls and now is empty. This stays the same. And now here we're going to change this. And I've already prepared this again because this would be a lot of time. Okay, so what we're doing here for all of our tool calls, which we got right here by checking what we got from the output back from the AI. So these are all the things that the AI, all the tool calls that the AI wants us to do. So we're mapping this, we're providing here again. the type, the call id, the output similar to what we have before and now we're changing this the input now is just our tool outputs i think we still need to close this yeah like this one okay so now again we have multiple outputs here and we're providing those inside the input key here for the client call here to the ai model and I think that's it. Let's give this a try now. Let's create a new chat. Hey, what is the latest Laravel release? And when do I have time to make a video about it? And please also tell me about the three most important features of this release. to cover in my video okay so now this should make two calls here to our http or it's failing because all right let's take a look here is empty why wasn't php telling me about this okay let's give this another try i'm going to paste in here the same prompt record this week okay the prompt was very similar to before So let's see if this is working now. It looks like we forgot now the info about the tool that our tool was being called. But this looks already good. Latest release. Yeah. 13.4. Okay. So I was using the tool. These are the top three features. Form request strict mode. Oh, I need to check this out. Okay. And best time to record. We have now to... two days here where i have time to record this and this is now really cool because we asked the ai something it didn't have the answer but it knew about the two features the two tools here that we are providing here and it's okay i think those tools can help us so it triggered that we are going to call both of those tools then it got back the response then it made the response from the ai model and then we saw the message so this is the authentic loop where the ai is triggering some tools here being run some functions being called and then going back and forth with the AI model until it is satisfied and it can provide us a good answer like we do here and as you know yeah this wasn't possible before but yeah this is now possible like this through what we've done here and the cool thing here you can just implement here anything you want so I could even further enhance this and provide some new tools in order to save some stuff into a Notion page which I normally use in order to have some information about level releases before i record the video or maybe using trello you can create a to do there and so on so everything that you can think of everything that maybe some of the tools ai tools that you're using have some specific integrations already you can do this as well and yeah as you've seen it's not that complicated and we did this everything here in this video and yeah basically this is also how a coding agent is working of course here i would clean this up quite a bit i would probably create a custom php class for every of our tools here where we have the definitions here and also the function calls here that we don't have those inside this here but even better would be to check out the level ai sdk where all of this is already integrated for you to use in a much nicer and cleaner and easier way but yeah i think it's good to understand how to how such tools are working and i hope that this helped you as much as it did for me And that's the agentic loop. The AI decides it needs a tool, we execute it, we feedback the result and the AI tries again, over and over until we have a final answer. And this is the core mechanical behind every AI agent out there. And the beautiful thing is the leveled AI SDK does it all for you automatically. You define your tools, call the prompt and it handles the entire loop. Now that you know what's happening behind the scenes, please go out and build something really cool, post it in the comments and let me know about it. thanks for watching if you like the video please like the subscribe click the subscribe like the video you know what to do and we'll see you in the next one bye

⚙️ Pipeline jobs

StageStatusAtt.UpdatedError
download done 1/3 2026-07-20 11:49:11
transcribe done 1/3 2026-07-20 11:49:28
summarize done 1/3 2026-07-20 11:50:11
embed done 1/3 2026-07-20 11:50:12

📄 Описание YouTube

Показать
Let’s build an agentic loop in Laravel from scratch.

We will add tool calling, create custom tools, fetch the latest Laravel release from GitHub, and make the model work with multiple tool calls in one loop. Just like a real agent.

➡️ OpenAI PHP Client: https://github.com/openai-php/client
➡️ Laravel AI SDK: https://github.com/laravel/ai
➡️ Laravel AI SDK Docs: https://laravel.com/docs/ai