Cómo crear un agente LLM de uso general | de Maya Murad | diciembre de 2024

Para implementar estos comportamientos de manera efectiva, deberá realizar algunas tareas de ingeniería inmediatas. También es posible que desee utilizar un generación estructurada técnica. Básicamente, esto significa dar forma al resultado del LLM para que coincida con un formato o esquema específico, de modo que las respuestas del agente sean consistentes con el estilo de comunicación que busca.

Ejemplo: A continuación se muestra un extracto del mensaje del sistema para un agente estilo ReAct del Marco del agente de abejas.

# Communication structure
You communicate only in instruction lines. The format is: "Instruction: expected output". You must only use these instruction lines and must not enter empty lines or anything else between instruction lines.
You must skip the instruction lines Function Name, Function Input and Function Output if no function calling is required.

Message: User's message. You never use this instruction line.
Thought: A single-line plan of how to answer the user's message. It must be immediately followed by Final Answer.
Thought: A single-line step-by-step plan of how to answer the user's message. You can use the available functions defined above. This instruction line must be immediately followed by Function Name if one of the available functions defined above needs to be called, or by Final Answer. Do not provide the answer here.
Function Name: Name of the function. This instruction line must be immediately followed by Function Input.
Function Input: Function parameters. Empty object is a valid parameter.
Function Output: Output of the function in JSON format.
Thought: Continue your thinking process.
Final Answer: Answer the user or ask for more information or clarification. It must always be preceded by Thought.

## Examples
Message: Can you translate "How are you" into French?
Thought: The user wants to translate a text into French. I can do that.
Final Answer: Comment vas-tu?

Paso 3. Definir las instrucciones principales del agente

Tendemos a dar por sentado que los LLM vienen con un montón de funciones listas para usar. Algunos de ellos son fantásticos, pero es posible que otros no sean exactamente lo que necesitas. Para obtener el rendimiento que busca, es importante detallar todas las funciones que desea (y no desea) en el mensaje del sistema.

Esto podría incluir instrucciones como:

  • Nombre y función del agente: Cómo se llama el agente y qué debe hacer.
  • Tono y concisión: Qué formal o informal debe sonar y qué breve debe ser.
  • Cuándo utilizar herramientas: Decidir cuándo confiar en herramientas externas frente al conocimiento propio del modelo.
  • Manejo de errores: Qué debe hacer el agente cuando algo sale mal con una herramienta o proceso.

Ejemplo: A continuación se muestra un fragmento de la sección de instrucciones del Marco del agente de abejas.

# Instructions
User can only see the Final Answer, all answers must be provided there.
You must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by Final Answer.
You must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by either Function Name or Final Answer.
Functions must be used to retrieve factual or historical information to answer the message.
If the user suggests using a function that is not available, answer that the function is not available. You can suggest alternatives if appropriate.
When the message is unclear or you need more information from the user, ask in Final Answer.

# Your capabilities
Prefer to use these capabilities over functions.
- You understand these languages: English, Spanish, French.
- You can translate and summarize, even long documents.

# Notes
- If you don't know the answer, say that you don't know.
- The current time and date in ISO format can be found in the last message.
- When answering the user, use friendly formats for time and date.
- Use markdown syntax for formatting code snippets, links, JSON, tables, images, files.
- Sometimes, things don't go as planned. Functions may not provide useful information on the first few tries. You should always try a few different approaches before declaring the problem unsolvable.
- When the function doesn't give you what you were asking for, you must either use another function or a different function input.
- When using search engines, you try different formulations of the query, possibly even in a different language.
- You cannot do complex calculations, computations, or data manipulations without using functions.m

Paso 4. Defina y optimice sus herramientas principales

Las herramientas son las que les dan a tus agentes sus superpoderes. Con un conjunto limitado de herramientas bien definidas, puede lograr una amplia funcionalidad. Las herramientas clave que se deben incluir son la ejecución de código, la búsqueda web, la lectura de archivos y el análisis de datos.

Para cada herramienta, deberá definir lo siguiente e incluirlo como parte del mensaje del sistema:

  • Nombre de la herramienta: Un nombre único y descriptivo para la capacidad.
  • Descripción de la herramienta: Una explicación clara de qué hace la herramienta y cuándo utilizarla. Esto ayuda al agente a determinar cuándo elegir la herramienta adecuada.
  • Esquema de entrada de herramientas: Un esquema que describe los parámetros obligatorios y opcionales, sus tipos y sus restricciones. El agente usa esto para completar las entradas que necesita según la consulta del usuario.
  • Un indicador de dónde/cómo ejecutar la herramienta.

Ejemplo: A continuación se muestra un extracto de la implementación de una herramienta Arxiv de Comunidad Langchain.

class ArxivInput(BaseModel):
"""Input for the Arxiv tool."""

query: str = Field(description="search query to look up")

class ArxivQueryRun(BaseTool): # type: ignore[override, override]
"""Tool that searches the Arxiv API."""

name: str = "arxiv"
description: str = (
"A wrapper around Arxiv.org "
"Useful for when you need to answer questions about Physics, Mathematics, "
"Computer Science, Quantitative Biology, Quantitative Finance, Statistics, "
"Electrical Engineering, and Economics "
"from scientific articles on arxiv.org. "
"Input should be a search query."
)
api_wrapper: ArxivAPIWrapper = Field(default_factory=ArxivAPIWrapper) # type: ignore[arg-type]
args_schema: Type[BaseModel] = ArxivInput

def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the Arxiv tool."""
return self.api_wrapper.run(query)p

En determinados casos, necesitarás optimizar las herramientas para obtener el rendimiento que buscas. Esto podría implicar modificar el nombre o la descripción de la herramienta con alguna ingeniería rápida, establecer configuraciones avanzadas para manejar errores comunes o filtrar la salida de la herramienta.

Paso 5. Decidir una estrategia de manejo de la memoria.

Los LLM están limitados por su ventana de contexto: la cantidad de tokens que pueden “recordar” a la vez. Esta memoria puede llenarse rápidamente con cosas como interacciones pasadas en conversaciones de varios turnos, resultados prolongados de herramientas o contexto adicional en el que se basa el agente. Por eso es crucial tener una estrategia sólida de manejo de la memoria.

Memoria, en el contexto de un agente, se refiere a la capacidad del sistema para almacenar, recordar y utilizar información de interacciones pasadas. Esto permite al agente mantener el contexto a lo largo del tiempo, mejorar sus respuestas en función de intercambios anteriores y brindar una experiencia más personalizada.

Estrategias comunes de manejo de la memoria:

  • Memoria deslizante: mantener el ultimo k La conversación gira en la memoria y abandona los mayores.
  • Memoria de fichas: mantener el ultimo norte fichas y olvídate del resto.
  • Memoria resumida: Utilice el LLM para resumir la conversación en cada turno y soltar los mensajes individuales.

Además, también puede hacer que un LLM detecte momentos clave para almacenarlos en la memoria a largo plazo. Esto permite al agente “recordar” datos importantes sobre el usuario, lo que hace que la experiencia sea aún más personalizada.