Como criar seu próprio agente de IA (como PewDiePie)
Autoria: Hugging Face · Assistir no YouTube
Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.
Idioma original: inglês
Vídeo original: How to Build Your Own AI Agent (Like PewDiePie) · Canal: Hugging Face · 23:46 · Assistir no YouTube
Tópicos: Agentes de IA, Modelos de IA, Modelos locais e open source
O vídeo apresenta Odysseus, um agent harness criado por PewDiePie, e explica como um agente coordena um LLM, ferramentas e contexto. Em seguida, mostra a diferença entre executar a aplicação localmente e executar o modelo localmente, além de comentar como escolher modelos compatíveis com o hardware. Por fim, explica como fine-tuning com traces de uso de ferramentas pode adaptar um modelo menor a um harness específico. O apresentador também recomenda materiais da Hugging Face para aprender a treinar agentes.
Pontos-chave
Seção intitulada “Pontos-chave”- Odysseus é apresentado como uma aplicação semelhante ao ChatGPT, compatível com diferentes LLMs e com suporte a ferramentas via MCP.
- Um agente recebe contexto, como system prompt, definições de ferramentas, memórias e histórico, e pode alternar entre respostas e tool calling.
- Executar a aplicação dentro de um Docker container no próprio computador não significa que o modelo também esteja sendo executado localmente.
- Modelos locais podem oferecer mais privacidade, funcionamento offline e controle, mas exigem hardware e consumo de eletricidade.
- A escolha do modelo local e do nível de quantização depende do hardware disponível.
- Modelos menores podem falhar ao selecionar ou chamar ferramentas; refinar as definições das ferramentas ou fazer fine-tuning são alternativas discutidas.
- O fine-tuning para uso de ferramentas pode utilizar traces de conversas em que um agente maior realizou as chamadas corretamente.
- O vídeo sugere usar traces públicos disponíveis na Hugging Face ou coletar traces próprios, removendo credenciais e dados sensíveis antes de compartilhá-los.
Capítulos
Seção intitulada “Capítulos”| Início | Capítulo | Resumo |
|---|---|---|
| 00:00 | Apresentação de Odysseus | O vídeo introduz o projeto de PewDiePie e apresenta Odysseus como um agent harness que pode usar diferentes LLMs. |
| 04:18 | Como funciona um agent harness | O apresentador explica o loop de um agente, o uso de ferramentas e os elementos de contexto enviados ao modelo. |
| 10:06 | Modelos locais e privacidade | O vídeo diferencia uma aplicação local de um modelo local e apresenta vantagens e custos de executar modelos no próprio hardware. |
| 13:54 | Escolha e execução de modelos locais | O apresentador demonstra como avaliar modelos e quantizações de acordo com o hardware e conectá-los a um agente. |
| 17:04 | Fine-tuning de um modelo para o harness | O vídeo explica por que um modelo menor pode falhar no tool calling e como traces podem servir para adaptá-lo. |
| 19:16 | Traces para treinamento de agentes | O apresentador aborda o uso de traces de modelos maiores e datasets públicos, além da remoção de credenciais antes do compartilhamento. |
| 21:37 | Recursos de treinamento e conclusão | O vídeo recomenda uma masterclass da Hugging Face e resume caminhos para treinar e comparar modelos menores. |
Citações
Seção intitulada “Citações”Um agente é essencialmente só um loop, ou duas chamadas a um modelo de linguagem. — 04:49
No modo local, o próprio modelo está sendo executado na sua máquina. Assim, os dados nunca saem do seu hardware. — 11:43
Executar um modelo local não significa que seja grátis, porque você ainda está executando por conta própria. — 12:15
Você pode treiná-los para suas tarefas específicas e torná-los ainda melhores, mesmo que sejam pequenos. — 19:16
Conceitos e entidades
Seção intitulada “Conceitos e entidades”- Odysseus (ferramenta): Aplicação apresentada como um agent harness que pode usar diferentes LLMs e ferramentas.
- PewDiePie (pessoa): Criador de conteúdo cujo projeto de agente e modelo local é o tema do vídeo.
- Hugging Face (empresa): Plataforma apresentada como repositório de modelos, datasets e traces de agentes.
- Qwen3.5 9B (modelo): Modelo que, segundo o vídeo, foi fine-tuned para funcionar com o harness de PewDiePie.
- Mistral Large 4 (modelo): Modelo usado pelo apresentador para demonstrar Odysseus.
- llama.cpp (ferramenta): Ferramenta recomendada no vídeo para executar modelos localmente.
- OpenRouter (ferramenta): Serviço usado na demonstração para encaminhar solicitações a um provedor de inference.
- Docker (ferramenta): Tecnologia usada para executar Odysseus em um container no computador do usuário.
- MCP (conceito): Protocolo mencionado como forma de conectar agentes a ferramentas e aplicações externas.
- Unsloth (empresa): Origem da versão do modelo Qwen que o apresentador identifica como provavelmente usada no projeto.
- DeepSeek (modelo): Exemplo de modelo com pesos abertos cujos traces poderiam ser usados no treinamento de modelos menores.
- GLM (modelo): Outro exemplo de modelo com pesos abertos citado como possível fonte de traces.
Tradução completa (pt-BR)
Seção intitulada “Tradução completa (pt-BR)”00:00 Bom dia, pessoal, como vão? Então, o PewDiePie agora está mexendo com IA, e acho que este é um ótimo momento e uma ótima oportunidade para explicar exatamente o que ele está construindo, como está fazendo isso e como vocês podem fazer a mesma coisa. Porque imagino que muitos de vocês talvez se inspirem nas coisas que ele está construindo, e algumas delas parecem complicadas e complexas demais para vocês realmente tentarem fazer. Mas, na verdade, são bem acessíveis se vocês começarem do início. Então, hoje vou dar uma visão geral bem rápida de tudo o que o PewDiePie está construindo e de como vocês podem criar algo parecido na sua própria casa.
00:35 Então, o que vamos fazer hoje é dar uma olhada no que é o Odysseus, o agent harness que o PewDiePie está construindo. Depois, vamos ver o que é um agent harness e como essas coisas funcionam do zero, além de como vocês podem criar o seu. Depois disso, vamos dar uma olhada na IA local, porque ele está tentando executar um modelo local no Odysseus e, aparentemente, isso não é muito simples. O que ele está fazendo é tentar fazer fine-tuning ou treinar um modelo Qwen 3.5 com 9 bilhões de parâmetros para rodar localmente e funcionar corretamente com o Odysseus.
01:06 E vou explicar um pouco mais sobre como vocês podem fazer isso por conta própria, como podem treinar um modelo pequeno para rodar especificamente no seu próprio harness. Então, sem mais delongas, vamos direto ao assunto. Primeiro, vamos dar uma olhada bem rápida no que é o Odysseus. Basicamente, é uma espécie de ChatGPT, mas é independente de LLM, o que significa que pode funcionar com qualquer LLM. Ele oferece suporte a outras ferramentas por meio de servidores MCP e tem várias outras ferramentas que vou mostrar daqui a pouco. E a instalação é um pouco técnica.
01:38 Então, vocês precisam clonar o repositório do GitHub e montar o contêiner Docker. Depois que isso estiver funcionando, tudo vai rodar dentro do contêiner Docker na sua máquina. Quando estiver tudo configurado e funcionando corretamente, vocês verão uma página parecida com esta. Vou só ampliar um pouco. Este é o Odysseus. Esta é a página inicial. E aqui vocês podem selecionar o modelo. Também podem adicionar modelos novos aqui. Eu já adicionei minha autenticação com o OpenRouter.
02:09 E também baixei alguns modelos locais para testar. Então, basicamente, é só selecionar qual assinante, qual assinatura ou qual provedor vocês querem e depois fazer login. Acho que a assinatura do ChatGPT não está funcionando direito agora. Simplesmente não funciona. Mas acho que as outras funcionam. Pelo menos o OpenRouter funciona. E o llama.cpp também. Aqui está o carregador. Aqui estão os modelos que já adicionei. Como podem ver, tenho um modelo Qwen. E tenho minha integração com o OpenRouter. E mais algumas coisas que aparecem aqui.
02:40 Aqui está a lista de conversas. Vocês podem pesquisar as conversas. Na verdade, há várias ferramentas. Pelo visto, há um cliente de e-mail aqui. Há uma memória, que extrai automaticamente lembranças das suas interações com ele. Também extrai skills automaticamente das suas interações. É mais ou menos como no Hermes ou no OpenClaw. E vocês também podem adicionar memórias ou skills manualmente. Dá para comparar as respostas de modelos diferentes. Há também um livrinho de receitas bem legal aqui, que deveria analisar o hardware de vocês e dizer quais modelos locais são melhores para rodar na sua máquina.
03:13 Temos uma espécie de problema de filtragem aqui. Porque, como podem ver, o EmbeddingGemma aparece como a principal recomendação para o meu hardware. O que, claro, não é um modelo que serviria para alimentar um aplicativo de chat. Consistence é um modelo de embedding. Mas é uma ideia muito legal. Gostei bastante. Enfim, há várias coisas diferentes aqui. Tem pesquisa aprofundada. Tem galeria. Tem uma espécie de biblioteca de documentos, conversas e pesquisas. Notas. Tarefas. E também dá para mudar o tema. Então, é bem legal. Não sou fã do sistema de janelas, desse layout.
03:46 Mas é isso. Agora vou mostrar como funciona com o modelo. Vou selecionar o Mistral Large, só para a demonstração. O Large 4. E vou perguntar: “Olá, por favor, apresente-se.” Vamos dar uma olhada. “Olá, sou seu assistente de IA, estou aqui para ajudar com uma ampla variedade de tarefas”, blá, blá, blá. E uma coisa engraçada é que, de alguma forma, ele pesquisa na web a cada interação, até quando eu só digo “olá”. Então, pesquisou “Hello”, da Adele, e as últimas notícias da revista Hello. Por que não? Pronto. Sim, tudo merece fontes muito bem documentadas.
04:18 Então, isso é o Odysseus. Mas como ele construiu isso? Vamos ver como vocês podem criar seu próprio harness e o que é um agent harness. Certo, vamos direto ao assunto. Beleza, vamos explicar bem rapidamente o que é um agent harness ou um agent em geral. A primeira coisa a saber é que um agent é, essencialmente, apenas um loop ou duas chamadas a um modelo de linguagem. E funciona assim, como vocês estão vendo aqui à esquerda. Aliás, este é um diagrama do tldraw, desenvolvido e gerado com IA.
04:49 Vocês podem muito bem criar seus próprios diagramas usando o ChatGPT ou o Claude para gerá-los. Certo, o que acontece é que vocês enviam uma entrada para o agent, certo? Um agent é o software que envolve seu modelo de linguagem de grande porte. Essa entrada é enviada ao modelo de linguagem, que lê todo o contexto, todo o system prompt e as definições das ferramentas, etc., que são enviadas a ele. Então, ele decide como vai responder à pergunta. Se for algo que pode ser respondido diretamente com texto, ele pode simplesmente apresentar a resposta.
05:21 Por outro lado, se precisar de ferramentas adicionais, por exemplo, para pesquisar na internet, executar um programa ou chamar um serviço externo, ele vai chamar o que chamamos de ferramenta. Ferramentas são programas ou funções disponíveis que podem fazer várias coisas diferentes. Basicamente, qualquer coisa que vocês consigam fazer com código pode ser colocada dentro de uma chamada de ferramenta. Depois que o agent retorna uma chamada de ferramenta, o aplicativo, que neste caso seria o Odysseus,
05:53 mas que poderia ser o ChatGPT, o Claude ou, neste caso, o seu próprio harness, executa essa chamada de ferramenta e retorna os resultados ao modelo. Então, depois de ver os resultados da ferramenta que chamou, o modelo consegue raciocinar novamente e descobrir se precisa chamar outra ferramenta ou se finalmente pode dar uma resposta. Então, esse é basicamente o diagrama que vocês estão vendo aqui. E quando eu disse que o modelo recebe muito contexto na primeira chamada que vocês fazem — quer dizer, em cada chamada que enviam para ele —, estou falando disto aqui.
06:23 Normalmente, o contexto, ou todo o material enviado a um modelo de linguagem, é definido pelo harness construído em torno dele. Neste caso, seria o Odysseus, mas aplicativos diferentes têm maneiras diferentes de gerenciar o contexto. Em geral, o contexto habitual de um agent de programação ou de um agent de uso geral inclui um system prompt, que diz ao agent ou descreve quais são seus objetivos ou sua finalidade iniciais. O ChatGPT tem um system prompt.
06:54 O Claude tem um system prompt. Aliás, caso vocês não conheçam, os prompts do Claude são open source e estão no site do Claude. Fiquem à vontade para dar uma olhada. Também vou deixar os links na descrição, caso tenham interesse. Depois disso, vêm as definições das ferramentas. Em outras palavras, a lista de todas as ferramentas disponíveis, para que o agent saiba quais chamar. E é basicamente isso que determina o que acontece aqui. Então, o modelo lê as definições das ferramentas e, a partir daí, decide se precisa ou não fazer uma chamada de ferramenta.
07:24 Às vezes, também temos a memória e os arquivos disponíveis dentro da context window daquela sessão. As memórias geralmente são extraídas de conversas anteriores ou vêm de outros recursos que o usuário pode ter compartilhado com o assistente. E, aliás, elas são extraídas de maneiras diferentes. Cada serviço faz isso de um jeito. Há outros vídeos aqui no canal em que falamos sobre memória e como ela funciona. Mas saiba que muitos agents diferentes fazem isso de maneiras diferentes. E, claro, elas não são acrescentadas ao system prompt todas as vezes
07:57 porque cada interação exige tipos diferentes de memória, certo? Então, o agent se lembra de algo relevante para a conversa que está tendo. Depois disso, geralmente vem a transcrição, que basicamente significa a lista completa de todas as mensagens trocadas com o modelo de linguagem. Como você pode ver aqui, a primeira mensagem talvez seja algo como “corrija o teste que está falhando”, enviada pelo usuário. Então, o assistant envia primeiro uma mensagem de raciocínio. Depois, faz um tool call, como mencionamos antes. Por exemplo, lê um arquivo. Em seguida, recebe o resultado da ferramenta.
08:29 Depois, talvez façamos outro tool call. Então, recebemos o resultado da ferramenta. Por fim, enviamos a resposta final. E tudo isso, cada quadrado que você vê aqui, é na verdade uma mensagem. Todas elas são mantidas e enviadas ao modelo de linguagem em cada interação, para que ele tenha todo o contexto da conversa, certo? Então, basicamente, é assim que um agent de IA funciona. E o wrapper que envolve essa explicação minimalista é a aplicação que coordena todas essas chamadas.
09:00 Ela coordena como o usuário envia a primeira solicitação. Neste caso, por exemplo, no Odysseus, seria este pequeno campo de entrada aqui. Mas outros agents também podem ter, por exemplo, entrada de voz. E a aplicação também pode definir como as ferramentas interagem com o modelo de linguagem. O modelo de linguagem pode, é claro, interagir com as ferramentas e atualizá-las. Mas, no caso do Odysseus, e acho que essa é uma maneira muito interessante de criar isso, você também pode interagir manualmente com as ferramentas. Então, por exemplo, neste caso, se for o calendário, você mesmo pode criar eventos.
09:33 Então, acho muito interessante ver como as ferramentas podem ser suas próprias aplicações. E isso é algo que estamos começando a ver cada vez mais com servidores MCP que permitem conectar-se a aplicações existentes, como Notion, Airtable etc. Assim, o agent pode modificar suas aplicações e executar ações nelas. Mas as aplicações ainda têm uma interface de usuário que você mesmo pode usar. É muito interessante. E é basicamente assim que um agent de IA funciona. Mas agora vamos falar sobre como o modelo é escolhido.
10:06 Porque, neste caso, claro, na demonstração que mostrei, eu estava usando o Mistral Large. É um modelo de linguagem muito grande e poderoso. Mas, se você quisesse executá-lo na sua própria máquina, esse modelo seria grande demais. E foi basicamente isso que PewDiePie estava tentando fazer. Ele estava tentando criar um assistente e também um modelo local para executá-lo. Então, vamos ver como você pode executar esse tipo de aplicação com seus próprios modelos locais. Certo. Vamos ver como executar esses modelos de IA localmente e o que realmente significa executar um modelo localmente.
10:38 Porque, quer dizer, mais uma vez, este vídeo é realmente para iniciantes. Mas, quando PewDiePie diz que o Odysseus está sendo executado localmente, isso significa que ele está sendo executado localmente dentro de um container Docker no seu computador. Então, se você compartilhar este URL com alguém que não esteja conectado ao seu computador, essa pessoa não conseguirá ver esta aplicação Odysseus, porque ela está sendo executada localmente. Isso não significa que o próprio modelo esteja sendo executado localmente. Essa é a diferença. A aplicação geralmente fica na sua máquina. E, sempre que você chama o modelo de linguagem, no exemplo que mostrei, chamei o Mistral Large 4, um dos modelos de IA mais recentes lançados.
11:13 E seus dados saem da aplicação e vão para o provedor de inference que eu estava usando naquele caso. Eu estava usando o OpenRouter, que encaminhava a solicitação para a API oficial da Mistral, se me lembro bem. Então, os dados saíram da sua aplicação, foram para a internet, chegaram ao serviço que executou o modelo de linguagem e, em seguida, a resposta voltou para você. E é basicamente isso que acontece em cada iteração do loop do agent, certo?
11:43 No caso local, porém, o LLM, o modelo de linguagem, o próprio modelo, é executado na sua máquina. Então, os dados nunca saem do seu hardware. É por isso que muitas pessoas preferem a execução local. Porque, embora as empresas, especialmente as europeias, protejam seus dados e cuidem deles, às vezes elas até os criptografam para que nem elas consigam ver seus dados, ou seja, as mensagens que você envia à aplicação. Ainda assim, os dados saem do seu computador. E, para algumas pessoas, isso é um problema. E há, claro, muitos motivos diferentes para optar pela execução local.
12:15 Por exemplo, como mencionei, isso torna tudo mais privado. Também funciona offline, porque tudo é executado na sua máquina. Não há cobrança por token. No entanto, lembre-se de que executar um modelo local não significa que seja grátis, porque você ainda está executando-o por conta própria. E paga pela eletricidade usada para executar o modelo, o que aumenta os custos. Mas isso lhe dá mais controle sobre o modelo que você quer usar. Você pode até personalizá-lo e fazer fine-tuning, como veremos daqui a pouco. E, para tarefas pequenas e bem delimitadas, ele pode até ser bem rápido.
12:47 Certo. E é assim que se faz, e é por isso que PewDiePie menciona tanto o Hugging Face: lá fica o maior repositório de modelos open source para você explorar e baixar. Neste caso, por exemplo, estamos vendo modelos que poderiam alimentar um assistente de IA. Você pode ir até “Models”, selecionar o filtro “Text Generation” e até filtrá-los por tamanho. Vou falar um pouco mais sobre o tamanho deles. Mas, em geral, dependendo da sua máquina, você deve conseguir executar modelos com provavelmente menos de 24 bilhões de parâmetros, provavelmente menos de 32.
13:19 Isso depende muito do seu hardware. Vou falar um pouco mais sobre isso neste vídeo ou em outro. Mas aqui está a lista de todos os modelos recentes que estão disponíveis. Há, por exemplo, o Kolibri 1, um modelo recente desenvolvido na Alemanha, e também modelos como o Qwen 3.8 27B. Ele deve funcionar na maioria dos computadores de uso pessoal, pelo menos se você o executar com alguma quantização. E é basicamente isso que está acontecendo aqui. Ele acessa o Hugging Face, seleciona um modelo útil para ele, baixa o modelo e o executa localmente. Na verdade, há uma maneira muito simples de executar seus modelos localmente: basta acessar llama.app.
13:54 Llama é o mecanismo que permite executar um modelo na sua máquina. Claro, há muitos outros disponíveis, mas o llama.cpp é o meu favorito. E ele é, na verdade, um aplicativo bem prático que também ajuda você a encontrar modelos adequados ao seu computador. Aqui, você pode simplesmente instalá-lo e baixá-lo, e ele vai instalar um menu prático como este. E haverá uma seção chamada “Recommended for your computer”. Assim, você pode selecionar os modelos mais adequados à sua máquina específica.
14:26 E você também pode ver os modelos que já instalou. Depois de baixar isso e confirmar que está funcionando corretamente, você pode executá-los no Odysseus ou em qualquer outro agent que estiver usando. No meu caso, estou usando o Llama aqui. Vamos supor que eu queira descobrir quais outros modelos estão disponíveis na minha máquina e quais ela consegue executar. Então vou até meu perfil. No Hugging Face, vou até as configurações. Depois, vou até a seção de hardware. Se você nunca fez isso antes, o que vai aparecer é uma tela vazia.
14:57 Mas aqui você vai selecionar qual computador tem. No meu caso, é um Apple M4 Max com 36 gigabytes. Vamos dar uma olhada. Aqui está minha pontuação. Isso é especialmente importante porque agora você pode conferir os modelos que mais lhe interessam. Por exemplo, vamos supor que você vá até llama.app. Veja os modelos mais populares que as pessoas executam localmente. Vamos supor que você queira experimentar o Qwen 3.8. O que eu recomendo é clicar nele. Você vai para a página do Hugging Face. E aqui vai encontrar o gráfico de compatibilidade com o seu hardware.
15:28 Aqui você vai ver o nível de quantização mais adequado para a sua máquina específica. Neste caso, a recomendação é usar Q4. Se o modelo for um pouco grande demais para a minha máquina, sempre posso escolher um nível um pouco abaixo. Por exemplo, vamos supor que eu queira algo menor. Posso usar o Qwen 3.5 small. Você pode ir até aqui. Como pode ver, minha máquina consegue até executar a versão BF16, que não é quantizada, ou seja, a versão completa do modelo. Certo. Depois, você pode selecioná-lo e executá-lo nos seus próprios aplicativos. Se estiver usando o Odysseus, vá até aqui.
15:59 Vá até cookbook e depois procure Qwen 3.5. Neste caso, lembre-se de que o modelo recomendado para mim foi o 3.5 0.8 B. É esse que você baixaria e executaria. Certo. E, se estiver usando outros agents, não deixe de usá-los também. Certo. Pronto. É basicamente isso que está acontecendo. E aqui está o diagrama final de novo. Você tem a solicitação do usuário. Desta vez, ela envia a mensagem para o seu modelo local. Então, o modelo local pode chamar uma ferramenta ou não.
16:32 Se ele chamar uma ferramenta, como antes, o computador executa a ferramenta e depois envia o resultado de volta ao modelo local, e então volta para este ponto. Se não houver outra chamada de ferramenta, ele apresenta a resposta final. Certo. E este é o modelo que substituímos. Você também pode usar um modelo na nuvem. Mas o que o PewDiePie está criando aqui é algo completamente local. Certo, certo. Agora que entendemos um pouco melhor como os modelos locais funcionam e como são executados na sua máquina, deixe-me contar um pouco mais sobre o que PewDiePie fez e como ele está treinando o próprio modelo, porque é isso que ele diz estar fazendo aqui com o Ajax.
17:04 E temos uma pequena pista aqui. Ele diz que o Ajax é um Qwen 3.5 9B com fine-tuning. Mas o que está acontecendo aqui? O que isso significa? E como você pode fazer isso por conta própria? Basicamente, como mostrei antes, você pode ir até o Hugging Face e encontrar o modelo que lhe interessa. Neste caso, é o Qwen 0… Não, não este. É o B. E esta é a versão que ele provavelmente está executando aqui, da Unsloth. Como podem ver, já que adicionei meu hardware, todas as quantizações são executadas na minha máquina.
17:37 Até a versão BF16 aqui, que é o modelo completo, sem nenhuma quantização. Ou seja, com todos os recursos a 100%. E provavelmente foi por isso que ele escolheu esse modelo: ele consegue ser executado em praticamente qualquer máquina em BF16 completo. O que suponho que aconteceu é que ele estava executando o Odysseus assim, com o Astra na API da OpenAI. Ele percebeu que estava funcionando muito bem, que cumpria sua função perfeitamente e que tudo estava dando certo. Então, quis trocar para um modelo local.
18:08 Quando mudou para o Qwen 3.5 9B, percebeu que o agent parou de funcionar de maneira confiável e não fazia as chamadas de ferramenta. Lembre-se de que, como mencionei antes, quando você envia uma pergunta ao seu agent, ele deve decidir se seleciona ou não uma ferramenta. O Astra fazia isso de maneira confiável, mas o novo modelo provavelmente não selecionava as ferramentas certas, ou talvez nem conseguisse chamá-las. O que eu teria feito a partir daí — e o que provavelmente aconteceu, embora eu não saiba se ele realmente tentou — seria refinar as definições das ferramentas que tinha no agent aqui.
18:45 Porque provavelmente ele poderia ter facilitado para modelos menores reconhecerem essas ferramentas. Mas o que aconteceu foi que ele percebeu que esse modelo pequeno ainda não era bom o suficiente. Então, concluiu que poderia fazer fine-tuning nele ou treiná-lo para o seu harness específico. É isso que ele diz aqui. E isso é importante, porque modelos open source podem ser treinados a partir dos pesos existentes que foram enviados ao Hugging Face. Essa é a parte legal dos modelos open source: você pode baixá-los do Hugging Face.
19:16 Você pode treiná-los para tarefas específicas e torná-los ainda melhores, mesmo que sejam pequenos, como um modelo de 9 bilhões de parâmetros. Mas como fazer isso e como ele está fazendo? Para treinar um modelo assim, você vai precisar de dados. Neste caso, como estamos tentando treinar um modelo para usar ferramentas corretamente, vamos precisar de históricos de conversas com o mesmo agent, nas quais ele execute corretamente as ferramentas. Imagino que o que aconteceu aqui foi que ele viu que o Astra fazia isso perfeitamente. Então, tentou usar essas transcrições — como você vê aqui, os rastros existentes do agent — para treinar o modelo menor.
19:52 E provavelmente se deparou com um problema quando percebeu que a OpenAI não envia a geração completa do modelo de linguagem pela API nem pela assinatura. Na verdade, ela criptografa os tokens de raciocínio. Lembre-se de que um agent ou modelo de linguagem primeiro raciocina e pensa na resposta que vai dar e só então apresenta a resposta. E esses tokens de raciocínio são muito importantes quando se faz fine-tuning de um modelo. Então, ele tentou encontrar uma maneira de extrair o conteúdo desses rastros de raciocínio.
20:26 Ele foi banido da OpenAI duas vezes, e foi isso que descobrimos neste vídeo. Mas provavelmente havia maneiras mais fáceis de fazer isso. Ele poderia ter usado um modelo que não fosse da OpenAI, como um modelo com pesos abertos, por exemplo, o DeepSeek ou o GLM, e usado esses rastros para treinar o modelo menor. Isso é algo que você também poderia fazer. Se, no entanto, o que você quer é treinar um modelo para tool calling em geral, mesmo que ele seja menor que 9B — por exemplo, fazer fine-tuning de um modelo de 0.8B de parâmetros —, você pode ir até Datasets e filtrar para mostrar apenas rastros.
21:01 Aqui você vai encontrar vários rastros públicos de agents de IA que as pessoas enviaram ao Hugging Face, para que possa fazer fine-tuning dos seus modelos pequenos usando esses rastros. E, aliás, se você estiver executando seus próprios agents e tiver os rastros na sua máquina, pode enviá-los ao Hugging Face. Você pode deixá-los públicos ou privados, caso queira apenas fazer um backup. Se optar por deixá-los públicos, claro, sem vazar suas credenciais — filtre-as antes de tornar os dados públicos. Assim, você vai ajudar outras pessoas a treinar seus modelos pequenos para que possam executar assistentes com tool calling nas próprias máquinas.
21:37 Certo. Na verdade, o que quero mostrar a vocês é que há um curso completo sobre fine-tuning de agents bem aqui no canal do YouTube. Vou mostrar isso daqui a pouco. E ele está bem aqui no canal da Hugging Face. Se você der uma olhada — quero dizer, o link vai estar na descrição de qualquer jeito —, ele faz parte da playlist de agents de pós-treinamento que você está vendo bem aqui. E aqui dá para ver que há cinco vídeos. Se quiser fazer o que mencionei aqui, você pode começar pelo vídeo número três, que é sobre treinar agents. Ele mostra exatamente o que eu disse que você poderia fazer agora mesmo, bem aqui,
22:09 que é treinar modelos pequenos com os rastros de um modelo maior. E é basicamente isso que está acontecendo. Então, recapitulando, há duas coisas que ele poderia ter feito. PewDiePie poderia ter feito fine-tuning do modelo menor dele com os rastros que já estão disponíveis no Hub bem aqui, seguindo os tutoriais que acabei de indicar aqui. Ou poderia ter executado o mesmo agent Odysseus e coletado todos os rastros do agent para usá-los no treinamento do modelo menor. E, para que os rastros tivessem os tokens de raciocínio completos,
22:40 ele teria precisado usar outro modelo, não necessariamente da OpenAI, porque eles criptografam os tokens de raciocínio, certo? E, se você for usar os rastros do Hugging Face Hub, provavelmente vai ter que limpá-los e formatá-los antes. Isso, é claro, é mencionado e abordado no curso que citei. Depois, é só fazer fine-tuning usando a técnica que você escolher. Isso também é abordado no curso que citei. E então você terá seu agent harness completo, criado por você mesmo, ou o Odysseus, funcionando com um modelo que você mesmo ajustou. Dessa forma, poderá comparar seu modelo pequeno antes e depois
23:15 do fine-tuning. É por isso que é sempre uma ótima ideia guardar esses rastros e ajudar a comunidade, anonimizando-os, removendo as credenciais e colocando-os no seu repo público, para que outras pessoas também possam usá-los para treinar modelos pequenos. Então é isso. Basicamente, foi isso que aprendemos hoje. É bem simples. E, mais uma vez, esta é uma visão geral de alto nível do que PewDiePie estava tentando criar e do que fez. Espero ter pelo menos dado a vocês um ponto de partida ou indicado os caminhos a seguir, caso queiram fazer isso por conta própria.
23:46 Se quiserem tutoriais mais aprofundados sobre como fazer essas coisas, me avisem. Posso fazer mais vídeos sobre isso, se tiverem interesse. Não deixem de conferir os cursos e os vídeos que indiquei na descrição e mencionei aqui. Eles foram feitos por algumas das pessoas mais incríveis e por especialistas muito respeitados nessa área. Então, é isso. Muito obrigado por assistir. Foi um prazer, como sempre, e vejo vocês no próximo vídeo.
Transcrição original
[00:00] Good morning everyone, how’s it going? So PewDiePie is doing AI now and I figure that this is a great moment and a great opportunity to explain to you exactly what he is building, how he’s doing it and how you can do the same thing. Because I figure that a lot of you might be inspired by the things that he’s building and some of them sound a little bit too complicated and too complex for you to actually take on. But they’re actually very approachable if you start from the beginning. So today I’m going to give you a very quick overview of everything that PewDiePie is building and how you can build yourself something similar in your own home.
[00:35] So what we’re going to be doing today is we’re going to be taking a look at what is Odysseus, the agent harness that PewDiePie is building. And then we’re going to take a look at what even is an agent harness and how these things work from scratch and how you can make your own. After that, we’re going to be taking a look at local AI because he’s trying to run a local model in Odysseus and it’s not very straightforward apparently. So what he’s doing is he’s trying to fine tune or to train a Qwen 3.5 9 billion parameter model to run locally and to work correctly with Odysseus.
[01:06] And I’m going to be telling you a little bit more about how you can do that yourself, how you can train a small model to run specifically for your own harness. So yeah, without any further ado, let’s actually get right into it. So first, let’s take a very quick look at what is Odysseus. So it’s basically some sort of a ChatGPT, but it is LLM agnostic, which means that it can run with any LLM. It has supports for other tools through MCP servers and it has a bunch of other tools that I’m going to show you in just a bit. And in order to install it, it’s a bit technical.
[01:38] So you have to clone the repository from GitHub and you have to mount the Docker container. And then once that is running, it will be running. Everything will be running inside the Docker container in your machine. So once that is done and everything is running correctly, you will see a page that looks a little bit like this. I’m just going to zoom in a little bit. So this is Odysseus. This is its landing page. And right here, you can select your model. You can add new models right here. I have myself already added my authentication with OpenRouter.
[02:09] And I have downloaded a couple of local models also to test this. And yeah, so basically just select which subscriber, which subscription or which provider you want and then log in. The ChatGPT subscription I think is not running correctly right now. It just doesn’t work. But I think the other ones do. At least OpenRouter does. And llama.cpp does as well. Here I have the loader. Here I have the added models that I have already. So I have, as you can see, a Qwen model. And I have my OpenRouter integration. Some other stuff that you have right here.
[02:40] Here’s your list of chats. You can search the chats. You have a bunch of tools, actually. You have an email client in here, apparently. You have a brain, which automatically extracts memories from your interactions with it. It also automatically extracts skills from your interactions. Kind of like a Hermes or OpenClaw kind of way. And you can also add memories or skills manually. You can compare different models outputs. You have a nice little cookbook right here, which is supposed to scan your hardware and tell you which local models are best for running in your machine.
[03:13] We have some sort of a filtering problem right here. Because, as you can see, EmbeddingGemma is listed as the top recommendation for my hardware. Which is, of course, not a model that would power a chat application. Consistence is an embedding model. But a really nice idea. I really much like it. You have, yeah, a bunch of different things right here. You have deep research. You have gallery. You have some sort of a library of documents and chats and research. Notes. Tasks. And you can also change the theme. So it’s pretty cool. I’m not a fan of the window, this window, like, layout system.
[03:46] But there you go. Let me just show you now how it works with the model. So I’m selecting Mistral Large, just for the demo. Large 4. And let me just ask it, hello, please introduce yourself. And let’s take a look at it. So hello, I’m your AI assistant here to help with a wide range of tasks, blah, blah, blah. And something funny that it somehow searches the web on every single interaction, even when I just say hello. So it’s searched for hello by Adele and latest news from Hello magazine. Why not? So there you go. Yeah, everything deserves very good documented sources.
[04:18] So that is what Odysseus is. But how did he even build this? Let’s take a look at how you can build your own harness and what even is an agent harness. Okay, so let’s get right into that. All right, so let’s go very quickly over what an agent harness or an agent in general is. The first thing to know is that an agent is essentially just a loop or two calls to a language model. And it works like this, like you see right here on the left. And by the way, this is a tldraw diagram developed, generated using AI.
[04:49] So you can totally just build your own diagrams using ChatGPT or Claude to generate these diagrams. All right, so what happens is that you send an input to your agent, right? And an agent is the software that wraps around your large language model. So that input is sent to your language model and the language model reads all your context, all the system prompt and the definitions of the tools, etc. that are sent to it. And it decides how it’s going to answer your question. If the question is something that can be answered directly with text, then it might just spit out the answer.
[05:21] If, on the other hand, it requires some additional tools, so for example, search the internet, it requires to run a program or call an external service, then it will call what we call a tool. Tools are these programs or functions that are available and they can do a bunch of different things, like basically anything that you can do with code, you can put it inside a tool call. And then, once the agent returns a tool call, your application, in this case it would be Odysseus,
[05:53] but it could be ChatGPT, Claude, or your own harness in this case, will execute that tool call and will return the results to your model. And then your model, after seeing the results of the tool that it called, it will be able to reason again and figure out if it needs to call another tool or if it can finally give you an answer. So that’s essentially the diagram that you have right here. And when I told you that the model receives a lot of context on the first call that you, I mean, on every call that you send to it, what I mean is this right here.
[06:23] Usually, the context or all of the material that is sent to a language model is defined by the harness that is built around it. In this case, it would be Odysseus, but different applications have different ways to manage the context. Usually, what you have in the usual context of a coding agent or a general purpose agent would be a system prompt that would tell the agent or describe what its initial goals or purpose are. ChatGPT has a system prompt.
[06:54] Claude has a system prompt. By the way, in case you’re not familiar with it, actually, the prompts for Claude are open sourced in the Claude website. Feel free to take a look at them. They’ll be linked in the description as well if you’re interested. And after that, you have the tool definitions. In other words, the list of all the tools available so that the agent knows what tools to call. And that’s essentially what dictates what happens right here. So the model will read its tool definitions and from there decide whether or not it requires to make a tool call or not.
[07:24] Sometimes also, inside the context window, we have the memory and the files available also in that session. Memories are usually memories extracted from previous conversations or which come from other resources that the user may have shared with the assistant. And those, by the way, are extracted in different ways. Different services do it differently. There are other videos right here on the channel where we go over memory and how it works. But just know that many different agents do this in a different way. And, of course, they are not appended to the system prompt every single time
[07:57] because every interaction requires different kinds of memories, right? So the agent remembers something relevant to the conversation that it is having. And after that, usually there is the transcript, which essentially means all of the entire list of all the messages that have been sent back and forth to the language model. As you can see right here, the first one might be something like fix the failing test from the user. Then the assistant just sends out a reasoning message first. Then it makes a tool call, as we mentioned before. Read a file, for example. And then from there, it gets the tool result.
[08:29] Then maybe we’ll do another tool call. Then it gets a tool result. And then finally, it sends over the final answer. And all of this, every single square that you see right here is actually a message. And all of them are persisted and sent over to the language model on every interaction so that it has the entire context of the conversation that it is having, okay? So essentially, that is how an AI agent works. And the wrapper around this minimalist explanation is the application that coordinates all these calls.
[09:00] So it coordinates how the user sends the first request. In this case, for example, in Odysseus, it would be this nice little input right here. But you may also have a voice input, for example, for other agents. And you have also the application that is capable of defining how the tools interact with the language model. So the language model can, of course, interact with the tools and update them. But in the case of Odysseus, and I think that that is actually a very interesting way to build this, you can also interact with the tools manually. So for example, in this thing, if it’s the calendar, you can create events yourself.
[09:33] So I think that this is a very interesting way to see how tools can actually be their own applications. And this is something that we’re starting to see more and more with MCP servers that allow you to connect to existing applications such as Notion, Airtable, etc. So the agent can modify and run actions on your applications. But the applications still have a user interface that you can use yourself. So really interesting stuff right here. And that is essentially how an AI agent works. But now let’s talk about how the model is chosen.
[10:06] Because in this case, of course, the demo I showed you, I was using Mistral Large. It’s a very large language model and very powerful. But if you wanted to run that in your own machine, then that model would be too large. And that’s essentially what PewDiePie was trying to do. He was trying to build an assistant and also the local model to run the assistant with it. So let’s take a look at how you can run these kinds of applications with your own local models. All right. So let’s take a look at how to run these AI models locally and what it actually means to run a model locally.
[10:38] Because, I mean, again, this is really for beginners. But when PewDiePie says that Odysseus is running locally, it actually is running locally in the sense that it is running in a Docker container inside of your computer. So if you share this URL with someone else that is not connected to your computer, they will not be able to see this Odysseus application because it’s running locally. That does not mean that the model is running locally itself. And that is the difference right here. So the application usually lives in your machine. And whenever you call the language model, in the example I showed you, I called Mistral Large 4, which is one of the latest AI models recently released.
[11:13] And your data leaves your application and goes to whichever inference provider I was using in that case. I was going through OpenRouter and that was routing to the official Mistral API, if I remember correctly. So that data left your application, went into the internet, went into the service that ran the language language model, and then returned to you the response. And that’s essentially what happens on every single iteration of the agent loop, right?
[11:43] On local, however, that LLM, the language model, the model itself is running in your machine. So the data never leaves your hardware. And that’s why a lot of people prefer local. Because even though companies, and especially European companies, protect your data and take care of your data, sometimes they even encrypt it so that not even them, they can look at your data, at your messages that you send your application. The data still leaves your computer. And for some people, that is a problem. And there are, of course, many different reasons to go for local.
[12:15] For example, it becomes, as I mentioned, it makes everything more private. It also works offline because everything is running in your machine. There is no bill per token. However, do keep in mind that running a local model does not mean that it is free because you’re still running it yourself. And you’re paying for the electricity that comes with running a model, which is increased cost. But it does give you more control over the model that you want. You can even customize it and fine-tune it, as we’re going to see in just a moment. And it is actually even pretty fast for small and very self-contained jobs.
[12:47] Okay. And the way to do that, and that’s why PewDiePie mentions Hugging Face so much, is because here is the largest repository of open models for you to take a look at and download. And in this case, for example, we’re taking a look at models that would power an AI assistant. And in that case, you can go right here to models, you go to filter by text generation, and you can even filter them by their size. I’m going to tell you a little bit more about their size. But in general, depending on your machine, you should be able to run models that are about probably smaller than 24 billion parameters, probably smaller than 32.
[13:19] It really depends on your hardware. I’m going to tell you a little bit more about this either in this video or another one. But here you have the list of all of the recent models that have been available. There is, for example, Kolibri 1, which is a recent model developed in Germany, which are, for example, Qwen 3.8 27B. That should run in most consumer hardware, at least if you run it with some quantization. And that is essentially what is going on right here. So what happens is that he goes to Hugging Face, he selects a model that is useful for him, and he downloads it and runs it locally. There is actually a very straightforward way to run your models locally if you go to llama.app.
[13:54] Llama is the engine that allows you to run a model in your machine. There are many, of course, available, but llama.app. Llama.cpp is my favorite one right here. And it is actually a nice little application that also helps you find the models that are adapted to your computer. So right here, you can just install it, you can download it, and it will install a nice little menu right here like this. And it will have a recommended for your computer section right here. So you can select the models that are the best for your particular machine.
[14:26] And you can also see the models that you have already installed. And once you have downloaded this and it runs correctly, then you can run them either in Odysseus or any other AI agent that you’re running. In my case, I’m running here with Llama. And let’s suppose that I want to figure out which other models are available for me in my machine and which ones my machine can run. So I’m going to go right here to my profile. And in Hugging Face, I’m going to go right here to settings. I’m going to go right here to hardware. And what’s going to happen if you have not done this before is you’re going to have this empty.
[14:57] But here you’re going to select which computer you have. In my case, it’s an Apple M4 Max with 36 gigabytes. Let’s take a look at it. And here I have my score. And this is especially important because now you can take a look at the models that you’re the most interested in. So for example, let’s suppose that you go right here to llama.app. Take a look at the most popular models that people run locally. And let’s suppose that you want to try Qwen 3.8. So what I would recommend is you click on it. You go to the Hugging Face page. And right here, you will see your hardware compatibility chart right here.
[15:28] And here you will see the level of quantization that is the best for your particular machine. In this case, it recommends that I use Q4. And if this model is a bit too large for my machine, I can always go a little bit below. So for example, let’s suppose that I want something smaller. I can use Qwen 3.5 small. You can go right here. And as you can see, my machine can even run the BF16 version, which is the version that is not quantized, like the full version of the model. Right. And then you can select it and then you can run it on your own applications. If you are using Odysseus, then you’re going to go right here.
[15:59] You’re going to go to cookbook and then you’re going to take a look at Qwen 3.5. And in this case, remember that the one that was suggested for me was 3.5 0.8 B. And this is the one that you would download and run. Okay. And if you’re running other agents, don’t hesitate to use those too. Okay. And there you go. That’s essentially what’s going on. And here’s the final diagram again. So you have the user request. Sends the message to your local model this time. Then your local model is able to either call a tool or not.
[16:32] If it holds a tool, just like before, your computer runs the tool in your computer, then sends it back to your local model and then go back right here. If there is no other tool call, then it gives you the final answer. Okay. And this is the model that we swapped. And if you wanted a cloud model, you can also do that. But what PewDiePie is building right here is something local completely. All right. All right. So now that we understand a little bit better how local models work and how they run in your machine, let me tell you a little bit more about what PewDiePie did and how he is training his own model, because that’s what he says he’s doing right here with Ajax.
[17:04] And we have a nice little hint right here. He says that Ajax is a fine-tuned Qwen 3.5 9B. Now, what is going on here? What does that even mean? And how can you do that yourself? So basically, as I showed you before, you can go right here to Hugging Face. You can find the model that you’re interested in. In this case, it’s Qwen 0. Nope, not this one. It is B. And this one is the version that he’s likely running right here from Unsloth. And as you can see right here, since I already added my hardware, every single quantization runs in my machine.
[17:37] Even the BF16 version right here, which is the full model without any quantization. So all its capabilities at 100%. And this is probably why he chose this model, because it is capable of running in pretty much any machine on full BF16. Now, what I assume that happened is that he was running Odysseus, just like that, with Astra on the OpenAI API. And he figured that it was working great, that it was doing its job perfectly, and everything was working great. And he wanted to switch to a local model.
[18:08] And when he switched to Qwen 3.5 9B, he realized that the agent actually stopped working reliably, and it was missing the tool calls. Remember, as I mentioned before, that when you send a question to your agent, it is supposed to select or not a tool. And Astra was doing that reliably, but the new one was probably not selecting the right tools, or maybe not even being able to call the tools. Now, what I would have done from there, and what was probably, and I don’t know if he actually tried it, was to actually refine the tool definitions that he had in his agent right here.
[18:45] Because he could have probably made it easier for smaller models to catch on those tools. But what happened is that, essentially, he figured out that this small model was not good enough yet. So he figured that he can fine-tune it or train it for his specific harness. And that’s what he says right here. And this is important, because open models can be trained on top of the existing weights that are uploaded to Hugging Face. So that’s the fun part about open models. You can download them from Hugging Face.
[19:16] You can train them on your specific tasks and make them even better, even if they’re small, like 9 billion parameters. But how do you do that, and how is he doing that? So in order to train a model like this, you’re going to need data. And in this case, since we’re trying to train a model to use tools correctly, then we’re going to need histories of conversations with the same agent where it runs the tools correctly. And I suppose that what was happening right here is that he saw that Astra was doing it perfectly. And he tried to use those transcripts, as you see right here, those existing traces of the agent to train the smaller model.
[19:52] And he probably faced an issue when he figured out that OpenAI actually does not ship the entire generation of the language model to you over the API or even over the subscription. They actually encrypt the reasoning tokens. Because remember that an agent or a language model first reasons and thinks about the answer that it’s going to give you, and then it gives you the answer. And those reasoning tokens are very important if you’re fine-tuning a model. So what he figured is he tried to hack his way into extracting the contents of those reasoning traces.
[20:26] He got banned from OpenAI twice, and that’s what we learned from this video. There were, however, easier ways to do it, probably. You could have probably used a non-OpenAI model, such as an open weights model, such as DeepSeek or GLM, and used those traces to train the smaller model. And that’s something that you could do. If, however, what you want to do is train a model for general tool calling, even if it’s smaller than 9B, for example, you could be fine-tuning a 0.8B parameter model, what you could do is go right here to Datasets and filter by only traces.
[21:01] And here you will have a bunch of public traces of AI agents that people have uploaded to Hugging Face so that you can fine-tune your small models on these traces right here. And, by the way, if you are running your own agents and have your traces in your machine, you can totally upload them to Hugging Face. Either put them on public or on private if you just want to back them up. And if you put them on public, of course, without licking your credentials, be sure to filter out your credentials before you make it public, you will help other people train their small models so that they can run tool calling assistance from their machine.
[21:37] Okay. Actually, what I want to show you is that there is a complete masterclass on fine-tuning agents right here in the YouTube channel. Let me show that to you in a moment. And it is right here in the Hugging Face channel. If you take a look at, I mean, the link is going to be in the description anyways, but it’s part of the post-training agents playlist that you see right here. And here you can see that you have five videos. If you want to do what I mentioned right here, you can start from the video number three, which is training agents. And shows you precisely what I told you that you could do right now, right here,
[22:09] which is training small models with the traces from a bigger model. And that’s essentially what’s going on. So to recap, there are two things that he could have done. PewDiePie could have either fine-tuned his smaller model with the traces that are already available in the Hub right here, and following the tutorials that I just linked right here. Or he could have run his same Odysseus agent, and he could have gathered all the traces from the agent and used those to train his smaller model. And in order for the traces to have the full reasoning tokens,
[22:40] he would have had to use another model, not necessarily OpenAI, because they encrypt the reasoning tokens, right? And if you are going to be using the traces from the Hugging Face Hub, you’re probably going to have to clean and format them before. This is, of course, mentioned and covered in the masterclass I mentioned. And then you just fine-tune it with whichever technique you select. That’s also covered in the masterclass I mentioned. And then you will have your complete agent harness made by yourself, or Odysseus, running with a model that you fine-tuned yourself. And that way you will be able to compare the before and after of your small model
[23:15] before fine-tuning it and after fine-tuning it. That’s why it’s always a very good idea to keep those traces and to help the community by anonymizing them, removing the credentials, and putting them in your public repo so that other people can use them to also train small models. So there you go. That’s essentially what we have learned today. It’s very straightforward. And again, this is a very high-level overview of what PewDiePie was trying to build and what he did. I hope that I have at least given you the starting point or the directions to follow if you want to do this yourself.
[23:46] If you want more in-depth tutorials on how to do these things, please do let me know. I can make more videos about this if you’re interested. Do definitely take a look at the masterclasses and the videos that I linked in the description and that I mentioned right here. They are made by some of the most amazing people and very well-respected experts in this field. So yeah, thanks a lot for watching. It has been a pleasure as usual and I’ll see you in the next one.