Official Content
  • This documentation is valid for:

The Agent Object allows you to create an AI agent with GeneXus Next

An artificial intelligence (AI) agent is a software entity that uses algorithms and computational techniques to perform tasks that typically require human intelligence. These agents can perceive their environment, reason about it, and take actions to achieve specific goals. AI agents can operate autonomously or assist humans in decision-making processes.

Capabilities of AI Agents

AI agents can perform a wide range of tasks, including but not limited to:

  • Natural language processing: Understanding and generating human language, enabling applications such as chatbots and virtual assistants.
  • Dynamic content generation: Agents can create personalized content, such as summaries, recommendations, and narratives, on the fly, adapting to user needs and preferences in real time.
  • Data analysis: Agents analyze large datasets to extract insights, identify patterns, and make predictions.
  • Recommendation systems: Providing personalized suggestions based on user behavior and preferences, commonly used in e-commerce and streaming services.
  • Business forecasting: Uses historical data to predict future trends, helping organizations make informed decisions regarding inventory, staffing, and marketing strategies.
  • Sales optimization: Analyzes sales data to identify opportunities for improvement, optimize pricing strategies, and enhance customer targeting.


Key Characteristics of AI Agents

1. Autonomy: AI agents can operate independently without human intervention, making decisions based on their programming and learned experiences.
2. Adaptability: They can learn from their environment and improve their performance over time through techniques such as machine learning.
3. Interactivity: Many AI agents can interact with users or other systems, facilitating communication and collaboration.
4. Goal-Oriented: AI agents are designed to achieve specific objectives, whether it be optimizing a process, solving a problem, or providing information.
5. Scalability: They can handle large volumes of data and interactions, making them suitable for businesses of all sizes.

Common Uses of AI Agents

AI agents are used across various industries and applications, including:

  • Customer support: Chatbots and virtual assistants that handle customer inquiries and provide support.
  • Healthcare: AI agents that assist in diagnostics, treatment recommendations, and patient monitoring.
  • Finance: Automated trading systems and fraud detection algorithms that analyze market trends and transactions.
  • E-commerce: AI agents enhance the online shopping experience through personalized product recommendations, dynamic pricing strategies, and customer support chatbots that assist with inquiries and order tracking.
  • Application security: AI agents can monitor applications for vulnerabilities, detect anomalies, and respond to potential security threats in real-time, enhancing overall cybersecurity measures.
  • Process improvement in manufacturing: AI agents can analyze production data to identify inefficiencies, optimize workflows, and predict maintenance needs, leading to increased productivity and reduced downtime.
  • Scientific Research: AI agents can assist researchers by analyzing vast amounts of scientific data, identifying patterns, and even generating hypotheses, thereby accelerating the pace of discovery.

In summary, AI agents are powerful tools that leverage Artificial Intelligence to perform complex tasks, enhance efficiency, and improve decision-making across various domains. Their ability to learn and adapt makes them increasingly valuable in today's technology-driven world.

The Agent Objects, in particular, can interact with various GeneXus objects such as Procedures, APIs, and other business logic objects. This capability allows the integration of generative AI with your business processes, enabling Agents to perform a wide range of Tasks—from updating records in your database to executing complex business operations. This seamless connection between AI and business logic enhances functionality and creates a truly intelligent application that can respond dynamically to user needs.

Syntax

Agent <AgentName>
{
    <Natural language prompt>

    #Rules
        parm(<Parameters>);
        [context(<DataProviders><Procedures>);]
        [use(<Tools>);]
    #End

    #Variables
        <Variable Definitions>
    #End
}

Where:

AgentName
   
This is the unique identifier for the Agent object. It should be a descriptive name following GeneXus naming conventions.

Natural language prompt

    Prompt with detailed instructions or description of the Task the Agent is to perform. This prompt may include variables received as Parameters. Is also possible to reference the context by using $context placeholder.

Syntax: sentences in natural language can include “{{&InputParameter1}}” “{{&InputParameter2}}” $context.

Rules
   
This section contains the operational rules for the Agent, including Parameters, Context, and Tools.

Parameters

Defines the input and output Parameters of the Agent. Contains a Parm rule with one or more input Parameters and a single output Parameter. The output returned by the Agent is a string.

Syntax:  parm(in:&InputParameter1,[in:&InputParameterN], out:&OutputParameter)

context 

Specifies additional context information (data) to the Agent, provided by different data sources. Contains a Context clause followed by one or more Data Providers or Procedures. Optionally may be referenced by the Agent instructions prompt by using $context placeholder. The Context clause is optional.

Syntax: context(DataProvider1(&Parameter1), [DataProvider2(&Parameter2),...Procedure1(&Parameter3)]);

Tools

Indicates the APIs or external tools that the Agent can use. Contains a Use clause followed by one or more Procedures, Agent objects, or external Globant Enterprise AI Tools (public Tools available in Globant Enterprise AI Lab or your own private GEAI Tool), to help the agent to get the output. The Use clause is optional, but if it is used, must contain an argument.

Syntax: (GEAITool1…[,GEIAToolN] [,AgentObject1…,AgentObjectN] [,Procedure1…, ProcedureN]);

Variables
   
This section defines the variables used by the Agent, specifying their properties.

Syntax:
VariableName
[
    DataType = 'DataType',
    AverageLength = 'AverageLength',
    Collection = 'True/False',
    ControlType = 'ControlType'
]

How $context placeholder works

The $context placeholder is a feature that allows for the integration of context-specific data within the Agent's prompt. It is used to dynamically insert contextual information that the Agent needs to perform its Task more effectively. 

$context placeholder can be used in two ways:

  1. Implicit insertion
  2. Explicit placement

1. Implicit insertion: If the $context placeholder is not explicitly mentioned in the prompt, GeneXus Next automatically appends the context data to the end of the prompt. This ensures that the Agent always has access to the necessary context information without requiring manual specification in every prompt.

//GenreRecommendationAgent
  Suggest movies in the genre of "{{&FavoriteGenre}}" that the user might enjoy.

parm(&FavoriteGenre, out: &RecommendedMovies);
context(GenreMoviesDataProvider(&FavoriteGenre));


In this example, even though $context is not mentioned in the prompt, the context from GenreMoviesDataProvider will be appended automatically.

2. Explicit placement: By including $context in a specific location in the prompt, you can control where the context data appears. This is useful for scenarios where the context needs to be positioned strategically within the prompt to enhance the Agent's understanding and response generation.

//GenreRecommendationAgent
  Suggest movies in the genre of "{{&FavoriteGenre}}" that the user might enjoy.
  Here is some additional information: $context

parm(&FavoriteGenre, out: &RecommendedMovies);
context(GenreMoviesDataProvider(&FavoriteGenre));

Here, $context is placed explicitly within the prompt, ensuring that the contextual data is inserted exactly where needed for the most relevant output.

By understanding and using the $context feature, you can enhance the capabilities of GeneXus Agents, ensuring they provide context-aware, accurate, and valuable responses tailored to user needs and interactions.

How to call an Agent object

To use an Agent object, you can call it in three different ways:

  1. As stand-alone call
  2. Integrated into a chat
  3. Integrated into a Business Process Diagram

1. Stand-alone call

This is the simplest way to execute an Agent object. It consists of calling the Agent directly from code:

&Result = AgentObjectName(&InputParameter1, [&InputParameterN,] [&CallResult])

Where:

AgentObjectName
   Is the name of the Agent object you want to call.

&InputParameter1, [&InputParameterN]
   Input Parameters required by the Agent object.

&CallResult
   Variable based on External Object GeneXus.common.CallResult helps managing the result of the operation.  The use of &CallResult parameter is optional, and may be not included in the call. 

However, it is very useful in the following situations:

  • Connection issues: If there is a problem connecting to the underlying model or the network, this will be reflected in &CallResult.
  • Model errors: Issues related to the LLM, such as timeouts or unexpected behavior, will also be captured.
  • Output generation problems: If the model fails to generate the desired output or returns unexpected results, these will be noted in &CallResult. By examining &CallResult, you can determine if the Agent has performed as expected or if any corrective action is needed.

CallResult has the following methods:

  • Success(): Boolean
  • Fail(): Boolean
  • GetMessages(): Messages

Handling Results:

If &CallResult.Success()
    // Process the successful result

Else
    // Handle errors
&ErrorMessage = &CallResult.GetMessages().ToJson()
Endif

2. Integrated into a chat

GeneXus Next Agents support stateful interactions, allowing for complex conversations that maintain context over multiple exchanges. This feature is particularly useful for customer support, virtual assistants, and any application requiring interactive dialogue.

Here's how to do it:

&ChatResponse = AgentObjectName.Chat(&ChatHistory, &NewMessage [, &CallResult])

Where:

AgentObjectName
   Is the name of the Agent object you want to call.

&ChatHistory 
   Is a simple array of messages that includes both user inputs and agent responses. This format helps maintain a clear, chronological conversation history that can be used to generate context-aware replies.

Each entry in the ChatHistory array contains:

  • Role: Specifies who is sending the message ("user" or "agent").
  • Content: The actual text of the message

Sample of ChatHistory:

{
    "role": "user",
    "content": "What movies are available today?"
  },
  {
    "role": "agent",
    "content": "Here are the movies available today: Movie1, Movie2, Movie3."
  },
  {
    "role": "user",
    "content": "Tell me more about Movie1."
  }


&CallResult
   Variable that gives information about the result of the operation. The use of &CallResult parameter is optional, and may be not included in the call.

ChatResponse 
    Variable based on external object GeneXus.common.CallResult that helps managing the result of the operation.

Each entry in the ChatHistory array contains:

  • Role: Always set to "agent" for the response.
  • Content: The text generated by the agent based on the user’s input and conversation context.

Sample of ChatResponse:

{
    "role": "agent",
    "content": "Movie1 is a thrilling adventure film released in 2024, starring famous actors..."
  }

 

Best Practices for Chat-Based Agents

  • Maintain context: Ensure the chat history accurately reflects all user inputs and agent responses, maintaining continuity and context across exchanges.
  • Clear and concise responses: Craft responses that are direct and informative, providing value without overwhelming the user.
  • Adapt to user needs: Be prepared to adjust responses based on the user's behavior and queries, offering flexibility and adaptability in the conversation.
  • Monitor interactions: Regularly review chat histories to understand user behavior and improve the Agent’s accuracy and relevance over time.

GeneXus Agents can deliver rich, interactive conversational experiences that are familiar and intuitive, enhancing user engagement and satisfaction.

3. Integrated into a Business Process Diagram

The Agent object may be integrated into a Business Process Diagram to help make a decision or perform an Agent Task, turning the diagram into an Agentic Workflow

How to integrate an Agent object into a Business Process Diagram

To integrate an Agent object into a Business Process Diagram, you need to add an Agent Task. This task is available in the Toolbox:

Agent task in toolbox genexus next

or by changing the Type property of a standard task to Agent. Once the task is in the diagram, you can associate it with an Agent object using the Agent property of the task.

Agent task in BPD - GeneXus Next

This links the Task to the Agent, so it runs in the process.

Using an Agent object in a Gateway condition

In Exclusive and Inclusive Gateways, the condition evaluation can be handled by an Agent object. To do this, set the Condition Agent property of the Gateway as follows:

Agent object in Gateway BPD - GeneXus Next

By the addition of AI features to a Business Process Diagram, developers and modelers can create powerful AI-driven workflow diagrams that help in automating complex Tasks, offering enhanced user experiences and operational efficiencies.

Agent Object Runtime

Agent Objects are designed to operate with the Globant Enterprise AI (GEAI) platform, which serves as the default runtime environment. By default, each Agent object is exposed as an API within GEAI, allowing for easy integration and interaction with other systems and applications. That means every agent name is unique and you can't define two agents with the same name in the same GEAI project, although the agents' objects were created in different Knowledge Bases. 

Default runtime behavior

When an agent is created in GeneXus, it is automatically configured to run on the Globant Enterprise AI platform at runtime. This default setup ensures that all Agent objects are exposed as APIs, making them readily accessible for external calls and integrations. This exposure as an API allows you to leverage the Agents in various contexts, such as web applications, mobile apps, and third-party services.

Environment-Level Configuration

The Globant Enterprise AI runtime is configured at the Environment level, meaning that the settings and models used by default are specified once for the entire development Environment. This configuration includes selecting the language models and defining their usage policies, ensuring consistency across all agents running within that Environment. 

Model Overrides for Customization

Although the Environment configuration provides a standard setup, each Agent object can override these settings as needed. This flexibility allows you to specify a different model or adjust other properties at the Agent level, tailoring the behavior of individual Agents according to specific requirements or use cases.

Best Practices when using Agents

To maximize the effectiveness of GeneXus Next Agents, consider the following best practices:

  • Keep prompts clear and concise: Ensure prompts are straightforward and directly related to the Agent’s task, minimizing ambiguity and maximizing performance.
  • Leverage context effectively: Use Data Providers to supply relevant context that enhances the Agent’s ability to provide accurate and personalized responses.
  • Test thoroughly: Before deploying an Agent, test it in various scenarios to ensure it performs as expected and handles edge cases gracefully.
  • Monitor and optimize: Continuously monitor agent performance and user feedback to identify areas for improvement and optimization.


Keys takeaways

You can call an Agent object in Procedures, Transactions, Web Panels, Business Components, and Data Providers. This means that Agent objects can be integrated with other objects like these. 

This integration allows you to enhance various aspects of your application with AI capabilities, enabling you to add intelligent processing, decision-making, and dynamic content generation throughout your application. 

By leveraging Agent objects in different contexts, you can create more sophisticated and responsive applications that take full advantage of natural language processing and generative AI in your business logic.

Samples

Sample 1: DescriptionsAgent

This sample describes an Agent that takes a short text input and expands it into a detailed description. To do so:

Agent DescriptionsAgent
{
    Expand the following short text into a detailed description: "{{&ShortText}}"

    #Rules
        parm(in:&ShortText, out: &ExpandedText);
    #End

    #Variables
        ShortText
        [
            DataType = 'VarChar(40)'
        ]

        ExpandedText
        [
            DataType = 'VarChar(512)'
        ]
    #End
}

The DescriptionsAgent takes a short text (&ShortText) as input and produces detailed information about the subject mentioned (&ExpandedText) as output. 

In this example, ShortText is defined as a 40-character VarChar, which limits the length of the input text, while ExpandedText is a 512-character VarChar, providing enough space for a detailed description. 

Calling the agent

To use the agent and obtain the expanded description, you simply call it by passing the input text. The result will be returned in the corresponding output variable as shown below:

&ExpandedText = DescriptionsAgent(&ShortText)

The agent result should be like this:

DescriptionsAgentResult sample 1 - agent object

Sample 2: ProductCategoryAgent

Suppose you need to identify the category identifier of a product based on its category description. To do so, you can define an Agent object as follows:

Agent ProductCategoryAgent
{
    Determine the product category with this description: {{&ProductDescription}}.

    #Rules
        parm(in:&ProductDescription, out:&CategoryId);
        context(CategoryList());
    #End

    #Variables
        ProductDescription
        [
            DataType = 'VarChar(40)',
            AverageLength = '0',
            Collection = 'False',
            ControlType = 'Edit'
        ]

        CategoryId
        [
            DataType = 'Numeric(4.0)'
        ]
    #End
}

The ProductCategoryAgent receives a product description text (&ProductDescription) as input and returns a category identifier (&CategoryId) selected by the agent from the category collection provided by CategoryList Data Provider. 

In the Rules section, in addition to defining these Parameters, a context (a Data Provider named CategoryList()) is included that provides the Agent with a list of available categories for sorting. 

The Variables section defines ProductDescription as a 40-character VarChar with additional properties such as AverageLength, Collection, and ControlType, suggesting that this variable could be used in a user interface. 

CategoryId is declared only with Data type and without specific properties, implying that the context of the application can determine its type and use.

Calling the agent

To get the category Id from a product description, call the Agent by passing the input text, as follows:

&CategoryId = ProductCategoryAgent(&ProductDescription)

Where variable &CategoryId is based on CategoryId attribute (typically N(4.0)) 
 

Sample 3: ProductRecommenderAgent

The goal of this sample is to provide context to an Agent object and using an external Tool.

Suppose you want to get product recommendations based on a customer's purchase history and preferences. To achieve this, define an Agent object as shown below: 

Agent ProductRecommenderAgent
{
    Recommend products for customer: "{{&CustomerID}}" based on: $context

    #Rules
        #Rules
        parm(in:&CustomerId, out:&RecommendedProducts);
        context(CustomerPurchaseHistory(&CustomerId),ProductCatalog());
    #End

    #Variables
        CustomerID
        [
            DataType = 'Numeric(8,0)',
        ]

        RecommendedProducts
        [
            DataType = 'VarChar(100)',
        ]
    #End
}

The ProductRecommenderAgent takes a customer ID (&CustomerID) as input and produces a list of recommended products (&RecommendedProducts) as output.

The Rules section defines the input and output Parameters, as well as the context and Tools used by the Agent. The context includes the customer's purchase history (given by the CustomerPurchaseHistory Data Provider) and the product catalog (given by the ProductCatalog data provider), which provide essential information for making recommendations. 

In the Variables section, CustomerID is defined as Numeric(8,0).  RecommendedProducts is defined as VarChar(100).

Complete sample calling the Agent

DataProviders

DataProvider CustomerPurchaseHistory
{
    CustomerPurchases from Invoice
        Where CustomerId = &CustomerId
    {
        CustomerPurchasesItem
        {
            InvoiceId
            InvoiceTotalAmount
        }
    }
    #Rules
        Parm(in:&CustomerId);
    #End

    #Variables
        CustomerId
            [
                DataType = 'Attribute:CustomerId'
            ]
    #End
}

DataProvider ProductCatalog
{
        ProductCatalogSDT from Product
        {
            ProductCatalogSDTItem
            {
                    ProductId
                    ProductName
                    ProductPrice
                    ProductDescription
            }
        }
}

Calling the agent:

&CustomerId = 1
&RecommendedProduct = RecommendProductsAgent(&CustomerId, &CallResult)
if &CallResult.Fail()
    &Messages = &CallResult.GetMessages()
for &Message in &Messages
        msg(&Message.Description)
    endfor
endif

The agent result should be like the following:

Sample3_RecommendedProductsOutput Agent object

Sample 4: SearchWebAgent

The goal of this sample is to ask Agent object to search a web site.

Suppose you want to get which products are on sale from a particular web site. To achieve this, you have to define an Agent object to find general information on the web using a public Globant Enteprise AI Tool, as shown below: 

Agent SearchWebAgent
{
    You must answer the question in "{{&question}}" 
    If you need to look something up online because 
    you don't know the answer, use the corresponding tool.
    
    #Rules
    parm(in:&question, out:&answer);
    use("com.globant.geai.web_scrapper_httpx");
    #End
    
    #Variables
    question
        [
            DataType = 'VarChar(512)'
        ]
    
    answer
        [
            DataType = 'VarChar(512)'
        ]

The Agent receives a query to find on sale products in a particular category in a web site. In the Agent definition, you have to instruct it to try to find and answer and use a public Tool to deal with the process of extracting content and data from a website. 

In the Variables section, &question and &answer variables are defined as VarChar(512).

Calling the agent

To request information from a website, call the agent by passing the question as input. The answer will be returned in the output variable after using the associated web scraping Tool.

&question = "Can you tell me the products of category Computers that are on sale on the website: https://www.amazon.com"
&answer = SearchWebSiteAgent(&question)

The Agent result should be like this:

Sample4_SearchWebAgentOutput agent object

Sample 5: Agents interacting among them

The goal of this sample is to ask an Agent object to debate with two other agents, and taking a decision on a matter. 

Suppose you want to know the answer to a question on a particular topic, and two experts with opposing views debate the issue.

The debate is moderated by an impartial researcher who ensures that each expert defends their position over several iterations. Eventually, based on the arguments presented, the moderator reaches their own conclusion, explaining the reasoning behind it. 

You can achieve this using three Agent objects, each fulfilling the role you need.

In the following example, you want to know if intelligent life exists outside Earth.

To do that, you have to create first an agent named IntelligentLifeYesAgent to represent the expert pro-intelligent life outside Earth:

Agent IntelligentLifeYesAgent
{
    You are an astrophysicist and astronomer with vast experience, and you are convinced that 
    intelligent life exists beyond Earth.
    If asked whether intelligent life exists outside of Earth, you should argue why it does.
    If given counterarguments against this position, you must refute them. Answer the following "{{&question}}"

    #Rules
        parm(in:&question, out:&answer);
    #End

    #Variables
        question
            [
                DataType = 'VarChar(50)'
            ]
    
        answer
            [
                DataType = 'VarChar(512)'
            ]
    #End

}

and another agent named IntelligentLifeNoAgent to represent the expert against existing intelligent life outside Earth:
 

Agent IntelligentLifeYesAgent
{
    You are an astrophysicist and astronomer with vast experience, and you are convinced that 
    intelligent life does not exist beyond Earth.
    If asked whether intelligent life exists outside of Earth, you should argue why it does not.
    If given counterarguments against this position, you must refute them. Answer the following "{{&question}}"

    #Rules
        parm(in:&question, out:&answer);
    #End

    #Variables
        question
            [
                DataType = 'VarChar(50)'
            ]
    
        answer
            [
                DataType = 'VarChar(512)'
            ]
    #End

}

Then, create a third Agent for the moderator role, with the duty to give us a final conclusion about the existence of intelligent life outside Earth. The agent is named IntelligentLifeModeratorAgent as follows:

Agent IntelligentLifeModeratorAgent
{
    You are a researcher and journalist internationally recognized for your professionalism, 
    coordinating a debate between two scientists highly specialized in astrophysics and 
    astronomy. The goal is to clarify whether intelligent life exists beyond Earth, or not.
    The first question is: "{{&InputArgument}}"
    Use the tools IntelligentLifeYesAgent and IntelligentLifeNoAgent to converse with each of the scientists.
    You have no more than three interactions between them to reach a conclusion.
    At the end, summarize what each scientist presents and provide a result.
    You must choose a final answer to the question of whether or not intelligent life 
    exists beyond Earth, taking into account the responses from each scientist.

    #Rules
        parm(in:&InputArgument, out:&Result);
        use(IntelligentLifeYesAgent, IntelligentLifeNoAgent);
    #End

    #Variables
        InputArgument
            [
                DataType = 'VarChar(512)'
            ]
    
        Result
            [
                DataType = 'VarChar(512)'
            ]
    #End

}

Calling the Agent

To obtain the final conclusion from the debate between the expert Agents, call the moderator Agent by passing the question as input. The moderator will interact with the two expert Agents internally, analyze their arguments, and return a summarized result with the final answer.

The agent IntelligentLifeModeratorAgent is called as following:
 

&question = "Is there intelligent life outside of Earth?"
&answer = IntelligentLifeModeratorAgent(&question, &CallResult)

The moderator agent called the other two agents three times and evaluated their answers, and finally the moderator arose to a final conclusion, giving us an answer as follows:

Sample5_AgentsDebateResult agent object

This example shows how it is possible to make three Agents interact between them several times to solve a problem.

Subcribe to this category's changes
Sub CategoriesAdd a new subcategory in this category
PagesAdd a new page in this category
Last update: June 2025 | © GeneXus. All rights reserved. GeneXus Powered by Globant