You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
11 Hrs
32 Min
17 Seg

Construcci贸n de agentes con memoria

25/26
Resources

How to use community prompts in Lanchain?

Welcome to the exciting adventure of developing artificial intelligence agents. In this tour, we will see how the Lanchain community can improve our projects through the use of prompts available on its platform. Let's dive into it!

Lanchain offers a repository known as Lanchain Hub, where you can find a variety of prompts designed for different purposes, such as chatbots, code writing, and evaluation tasks. This community resource is essential to enrich our applications with proven and versatile solutions.

What is a prompt and how is it inserted in Lanchain?

A prompt is an instruction or set of instructions given to a language model to guide its response. In our case, a prompt can configure how an agent interprets commands or answers questions. By accessing the Lanchain Hub, you get a concrete example of a prompt and its format. This format includes several parts:

  • System: Initial prompt that sets the context.
  • Human: Input provided by the user.
  • Placeholder: Space reserved for additional information.

Once we copy the prompt, we take it to our workspace, using tools such as Google Colab.

How to create an agent in Lanchain?

The creation of an agent in Lanchain starts by importing the agent and the creation tools from the Lanchain API. Here is an example of how to do it:

from langchain import create_agent, tools# Create agent agentagent = create_agent(  large_language_model=model,  tools=tools,  prompt=prompt).

Once the agent is created, tasks can be assigned taking advantage of the loaded tools. We import the executor agent and configure it to interact with user input:

from langchain import execute_agent# Configure the agent executorexecute_agent = execute_agent(  agent=agent,  tools=tools_set).

How to perform queries and store memory in the agent?

Once the agent is running, we perform queries using the Invoke function. This allows us to send input to the agent and receive an appropriate output. This is how a basic query is structured:

response = agent.Invoke(input='Hello, how may I assist you today?').

Subsequently, an excellent functionality of agents is to add memory to them. This allows the agent to remember previous interactions. Here is the process for adding memory to the agent using the GetSessionHistory function:

# Get session historyhistory = GetSessionHistory(agent)# Queries with memoryagent.Invoke(input='What is my name?')agent.Invoke(input='My name is Bob')

What is the next step in the development of the agent?

The last challenge will present the integration of all these features in a professional environment, such as Visual Studio Code. The goal is to bring together each of the sections worked on in Google Colab and handle them in a more robust environment. This not only facilitates the development process, but also prepares the project for future implementation and continuous improvement.

With this knowledge, you are more than equipped to move forward and apply these skills to real projects - keep exploring and expanding your AI development skills!

Contributions 2

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

AgentExecutor es legacy API. Esto que me dijo ChatGPT puede ayudarles: *La raz贸n por la que la documentaci贸n oficial de LangChain marca `AgentExecutor` como \*\*legacy\*\* (obsoleto o en desuso) para el SDK de JavaScript/TypeScript es parte de su estrategia para optimizar y modernizar el ecosistema del SDK, haci茅ndolo m谩s coherente y eficiente. Aqu铆 est谩n los puntos principales detr谩s de esta decisi贸n:* *---* *### \*\*1. Simplicidad y Modernizaci贸n\*\** *El equipo de LangChain est谩 migrando hacia un enfoque m谩s modular y expl铆cito, eliminando abstracciones innecesarias. El uso de `AgentExecutor` sol铆a ser una forma gen茅rica y c贸moda de ejecutar agentes, pero a medida que los agentes han evolucionado, esta abstracci贸n se volvi贸 demasiado r铆gida o redundante para los nuevos flujos de trabajo.* *Por ejemplo:* *- En el SDK de Python, LangChain ha adoptado un enfoque m谩s directo con el uso de funciones espec铆ficas como `create\_openai\_functions\_agent`, mientras que en JavaScript se est谩 priorizando el uso de herramientas m谩s expl铆citas y adaptables como `Runnable` y `RunnableSequence`.* *---* *### \*\*2. Transici贸n a `Runnable`\*\** *En el SDK de JavaScript/TypeScript, LangChain ha introducido un nuevo sistema basado en la interfaz `Runnable`. Este sistema permite una mayor flexibilidad para componer y ejecutar agentes, herramientas y otros componentes de LangChain.* *El sistema `Runnable`:* *- Reemplaza al `AgentExecutor` como la forma est谩ndar de componer y ejecutar flujos de trabajo.* *- Proporciona un dise帽o m谩s declarativo y flexible para flujos complejos.* *- Es m谩s compatible con los paradigmas de programaci贸n reactiva y funcional, lo que lo hace m谩s adecuado para desarrolladores de JavaScript/TypeScript.* *Ejemplo de `Runnable`:* *```typescript* *import { RunnableSequence } from "langchain/schema";* *import { ChatOpenAI } from "langchain/chat\_models";* *const model = new ChatOpenAI();* *const runnable = new RunnableSequence({* *steps: \[* *{* *input: "Hello, how are you?",* *run: async (input) => model.call({ messages: \[{ role: "user", content: input }] }),* *},* *],* *});* *const result = await runnable.invoke({ input: "Hi there!" });* *console.log(result);* *```* *---* *### \*\*3. Mayor consistencia con otros SDKs\*\** *LangChain busca alinear la experiencia del usuario entre los diferentes SDKs (Python, JavaScript, Rust, etc.). En este proceso, est谩n eliminando patrones que eran espec铆ficos de un SDK y que no encajan bien con la arquitectura general. El sistema `Runnable` ya est谩 presente en m煤ltiples SDKs, lo que ayuda a estandarizar c贸mo se crean y ejecutan flujos.* *---* *### \*\*4. Limitaciones del `AgentExecutor`\*\** *Aunque el `AgentExecutor` funcionaba bien para casos b谩sicos, ten铆a limitaciones:* *- \*\*Poca flexibilidad:\*\* No era f谩cil extenderlo o integrarlo en flujos personalizados.* *- \*\*Complejidad innecesaria:\*\* La abstracci贸n era 煤til para algunos casos simples, pero introduc铆a sobrecarga para flujos m谩s avanzados.* *- \*\*Integraci贸n con herramientas modernas:\*\* El ecosistema JavaScript ha adoptado herramientas m谩s avanzadas, como Promises y operadores funcionales, lo que hace que `AgentExecutor` no sea la mejor opci贸n.* *---* *### \*\*5. Mejor rendimiento y escalabilidad\*\** *El enfoque basado en `Runnable` es m谩s liviano y eficiente, especialmente para aplicaciones que requieren un alto grado de personalizaci贸n o que operan con grandes vol煤menes de datos.* *---* *### Conclusi贸n* *Aunque `AgentExecutor` sigue siendo funcional por ahora, est谩 marcado como \*\*legacy\*\* porque LangChain quiere que los desarrolladores adopten las nuevas interfaces (`Runnable`, `RunnableSequence`) para garantizar compatibilidad futura y aprovechar las mejoras en dise帽o, flexibilidad y rendimiento.*
Porque se debe de hacer esto ![](https://static.platzi.com/media/user_upload/image-b6c350ca-d6a9-4239-9d51-a1d614a30258.jpg) yo intente hacer esto creado las variables y no funciono, para hacer el prompt ![](https://static.platzi.com/media/user_upload/image-6b1492e3-22c9-486c-b2b5-be44b42cec87.jpg) genero error cuando corri esta l铆nea agent\_executor.invoke({"input": "Hola"}) y deb铆 volver a la inicial Es mejor crear las cosas que usar estos sitios, como se crear铆a el prompt adecuado para ejecutar este agente, dado que con ese templete funciona y sin el template no