Blog

Building an AI Agent with LangChain

May 1, 2025 4:44 PM

View the webinar

In this blog post, we'll explore how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We'll cover the background of these technologies, how they work together, and provide a step-by-step guide to create your own agent.

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides a set of abstractions and tools that make it easier to build complex applications with LLMs (Large Language Models). LangChain enables developers to:

  • Connect LLMs to external data sources
  • Create chains of operations that can be executed in sequence
  • Build agents that can use tools to accomplish tasks
  • Manage memory and context for conversations

LangChain has become a popular choice for developers building AI applications because it simplifies the integration of LLMs into existing systems and workflows.

What is a React Agent?

The React agent pattern (Reasoning and Acting) is a powerful approach to building AI agents that can solve complex tasks. The name "React" comes from the pattern of alternating between:

1. Reasoning: The agent thinks about what to do next

2. Acting: The agent takes an action based on its reasoning

This pattern allows the agent to:

  • Break down complex problems into smaller steps
  • Use tools to gather information or perform actions
  • Learn from the results of its actions
  • Adapt its approach based on feedback

React agents are particularly effective for tasks that require multiple steps or the use of external tools, making them ideal for interacting with APIs like Extend.

The Extend AI Toolkit

The Extend AI Toolkit is an open-source library that provides tools for integrating with the Extend API in various AI agent frameworks, including LangChain.

It enables AI agents to:

  • Manage virtual cards
  • View credit card information
  • Track transactions
  • Categorize expenses

The toolkit abstracts away the complexity of API interactions, allowing developers to focus on building powerful AI agents that can help users manage their finances.

Setting up your environment

Before we start building our agent, let's set up our development environment:

1. Install Python 3.12 or higher if you don't already have it.

2. Create a virtual environment (recommended):

python -m venv venv   
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install the required packages:

pip install extend-ai-toolkit langchain langchain-openai python-dotenv

4. Set up your Extend API credentials:

   Create a `.env` file in your project directory with the following content:

EXTEND_API_KEY=your_api_key_here
EXTEND_API_SECRET=your_api_secret_here
ORGANIZATION_ID=your_org_id_here
OPENAI_API_KEY=your_openai_api_key_here

You'll need to obtain these credentials from your Extend account. If you don't have an account yet, you can sign up at app.paywithextend.com and follow our Getting Started Guide.

5. Set up your OpenAI API key:

To use LangChain with GPT models, you'll need an OpenAI API key:

   1. Go to [OpenAI's platform](https://platform.openai.com/)

   2. Sign up for an account or log in if you already have one

   3. Navigate to the API keys section

   4. Click "Create new secret key"

   5. Give your key a name (e.g., "Extend Agent")

   6. Copy the generated API key and add it to your `.env` file as `OPENAI_API_KEY`

Note💡

OpenAI offers a free tier with limited usage, but you may need to add a payment method to access GPT-4 models.

Building the React Agent

Now, let's create a Python script that sets up a LangChain React agent with the Extend AI Toolkit. We'll break this down into logical sections to understand each component.

1. Imports and environment setup

First, let's import the necessary libraries and set up our environment variables:

import os

import asyncio

from dotenv import load_dotenv‍

from langchain_openai import ChatOpenAI

from langgraph.prebuilt import create_react_agent

from langchain_core.messages import SystemMessage, AIMessage, HumanMessage‍

from extend_ai_toolkit.langchain.toolkit import ExtendLangChainToolkit

from extend_ai_toolkit.shared import Configuration, Scope, Product, Actions‍

# Load environment variables
load_dotenv()‍

# Get required environment variables
api_key = os.environ.get("EXTEND_API_KEY")
api_secret = os.environ.get("EXTEND_API_SECRET")
org_id = os.environ.get("ORGANIZATION_ID")‍

# Validate environment variables
if not all([api_key, api_secret, org_id]):    

	raise ValueError("Missing required environment variables.
  Please set EXTEND_API_KEY, EXTEND_API_SECRET, 
  and ORGANIZATION_ID")

This section handles importing all necessary libraries and setting up environment variables. We use `python-dotenv` to load variables from our `.env` file and validate that all required credentials are present.

2. Language model configuration

Next, we set up our language model:

# Initialize the language model
llm = ChatOpenAI(
	model="gpt-4o", 
  # You can also use "gpt-3.5-turbo" for a 
  more cost-effective option
)

Here, we're using OpenAI's GPT-4o model through LangChain's `ChatOpenAI` class. You can also use GPT-3.5-turbo for a more cost-effective option, though it may have slightly reduced capabilities.

3. Extend Toolkit configuration

Now, let's configure the Extend AI Toolkit with appropriate permissions:

# Create the Extend LangChain toolkit with appropriate permissions
extend_langchain_toolkit = ExtendLangChainToolkit(
	org_id,
  api_key,
  api_secret,
  Configuration(
  	scope=[
    	Scope(Product.VIRTUAL_CARDS, actions=Actions(read=True)),
      Scope(Product.CREDIT_CARDS, actions=Actions(read=True)),
      Scope(Product.TRANSACTIONS, actions=Actions(read=True)),
     ],       
   	 org_id=org_id    
   	)
   )
   
   # Get the tools from the toolkit
   tools = []
   
   tools.extend(extend_langchain_toolkit.get_tools())

This section creates an instance of the Extend LangChain toolkit with read permissions for virtual cards, credit cards, and transactions. We then extract the tools from the toolkit, which will be used by our agent.

4. React Agent creation

Now, let's create our React agent:

# Create the React agent
langgraph_agent_executor = create_react_agent(
	llm,
  tools
)

This creates a React agent using LangGraph's `create_react_agent` function, which combines our language model with the Extend tools.

5. Chat interface implementation

Finally, let's implement the chat interface:

# Function to interact with the agent
async def chat_with_agent():
	print("\nWelcome to the Extend AI Assistant!")
  print("You can ask me to:")
  print("- List all credit cards")
  print("- List all virtual cards")
  print("- Show details for a specific virtual card")
  print("- Show transactions for a specific period")
  print("- Show details for a specific transaction")
  print("- Create or update virtual cards")
  print("\nType 'exit' to end the conversation.\n")
  
  while True:
  	# Get user input
    user_input = input("\nYou: ").strip()
    
    if user_input.lower() in ['exit', 'quit', 'bye']:
    	print("\nGoodbye!")
    	break
      
    # Process the query
    result = await langgraph_agent_executor.ainvoke({
    	"input": user_input,
      "messages": [
      	SystemMessage(content="You are a helpful assistant 
        that can interact with the Extend API to manage virtual cards, 
        credit cards, and transactions."),
        HumanMessage(content=user_input)
       ]
      })
      
      # Extract and print the assistant's message
      for message in result.get('messages', []):
      	if isinstance(message, AIMessage):
        	print("\nAssistant:", message.content)‍
          
if __name__ == "__main__":
	asyncio.run(chat_with_agent())

This section implements a simple chat interface that allows users to interact with the agent. It displays a welcome message with available capabilities, processes user input, and displays the agent's responses.

Running the agent

To run the agent, simply execute the script:

python extend_agent.py

You'll be presented with a welcome message and a list of capabilities. You can then ask the agent questions like:

  • "List all my virtual cards"
  • "Show me transactions from last month"
  • "Create a new virtual card for my marketing team"
  • "What's the status of my credit card with ID 'card_123'?"

The agent will use the React pattern to:

  1. Understand your request
  2. Determine which tools to use
  3. Execute the appropriate API calls
  4. Format and return the results

Extending the agent

The Extend AI Toolkit provides many more capabilities that you can add to your agent:

  1. Expense categories: Add tools for managing expense categories and labels.
  2. Receipt management: Enable the agent to handle receipt attachments.

To add these capabilities, simply update the `Configuration` object with the appropriate scopes and actions.

Conclusion

In this blog post, we've explored how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We've covered:

  • The basics of LangChain and React agents
  • How to set up the Extend AI Toolkit
  • How to create a custom agent with specific permissions
  • How to interact with the agent to manage virtual cards, credit cards, and transactions

This agent can serve as a foundation for building more complex financial management applications. By combining the power of LangChain with the Extend API, you can create AI assistants that help users manage their finances more effectively.

To learn more about the Extend AI Toolkit, visit the GitHub repository. For more information about LangChain, check out the LangChain documentation.

Happy coding!

Presented by

Dawn Lewis
Controller at Couranto

Bridget Cobb
Staff Accountant at Healthstream

Brittany Nolan
Sr. Product Marketing Manager at Extend (moderator)

Ashkan Abedian

Product Manager & Engineer
Blog

Building an AI Agent with LangChain

Virtual Card Spend
No items found.
Share post

In this blog post, we'll explore how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We'll cover the background of these technologies, how they work together, and provide a step-by-step guide to create your own agent.

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides a set of abstractions and tools that make it easier to build complex applications with LLMs (Large Language Models). LangChain enables developers to:

  • Connect LLMs to external data sources
  • Create chains of operations that can be executed in sequence
  • Build agents that can use tools to accomplish tasks
  • Manage memory and context for conversations

LangChain has become a popular choice for developers building AI applications because it simplifies the integration of LLMs into existing systems and workflows.

What is a React Agent?

The React agent pattern (Reasoning and Acting) is a powerful approach to building AI agents that can solve complex tasks. The name "React" comes from the pattern of alternating between:

1. Reasoning: The agent thinks about what to do next

2. Acting: The agent takes an action based on its reasoning

This pattern allows the agent to:

  • Break down complex problems into smaller steps
  • Use tools to gather information or perform actions
  • Learn from the results of its actions
  • Adapt its approach based on feedback

React agents are particularly effective for tasks that require multiple steps or the use of external tools, making them ideal for interacting with APIs like Extend.

The Extend AI Toolkit

The Extend AI Toolkit is an open-source library that provides tools for integrating with the Extend API in various AI agent frameworks, including LangChain.

It enables AI agents to:

  • Manage virtual cards
  • View credit card information
  • Track transactions
  • Categorize expenses

The toolkit abstracts away the complexity of API interactions, allowing developers to focus on building powerful AI agents that can help users manage their finances.

Setting up your environment

Before we start building our agent, let's set up our development environment:

1. Install Python 3.12 or higher if you don't already have it.

2. Create a virtual environment (recommended):

python -m venv venv   
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install the required packages:

pip install extend-ai-toolkit langchain langchain-openai python-dotenv

4. Set up your Extend API credentials:

   Create a `.env` file in your project directory with the following content:

EXTEND_API_KEY=your_api_key_here
EXTEND_API_SECRET=your_api_secret_here
ORGANIZATION_ID=your_org_id_here
OPENAI_API_KEY=your_openai_api_key_here

You'll need to obtain these credentials from your Extend account. If you don't have an account yet, you can sign up at app.paywithextend.com and follow our Getting Started Guide.

5. Set up your OpenAI API key:

To use LangChain with GPT models, you'll need an OpenAI API key:

   1. Go to [OpenAI's platform](https://platform.openai.com/)

   2. Sign up for an account or log in if you already have one

   3. Navigate to the API keys section

   4. Click "Create new secret key"

   5. Give your key a name (e.g., "Extend Agent")

   6. Copy the generated API key and add it to your `.env` file as `OPENAI_API_KEY`

Note💡

OpenAI offers a free tier with limited usage, but you may need to add a payment method to access GPT-4 models.

Building the React Agent

Now, let's create a Python script that sets up a LangChain React agent with the Extend AI Toolkit. We'll break this down into logical sections to understand each component.

1. Imports and environment setup

First, let's import the necessary libraries and set up our environment variables:

import os

import asyncio

from dotenv import load_dotenv‍

from langchain_openai import ChatOpenAI

from langgraph.prebuilt import create_react_agent

from langchain_core.messages import SystemMessage, AIMessage, HumanMessage‍

from extend_ai_toolkit.langchain.toolkit import ExtendLangChainToolkit

from extend_ai_toolkit.shared import Configuration, Scope, Product, Actions‍

# Load environment variables
load_dotenv()‍

# Get required environment variables
api_key = os.environ.get("EXTEND_API_KEY")
api_secret = os.environ.get("EXTEND_API_SECRET")
org_id = os.environ.get("ORGANIZATION_ID")‍

# Validate environment variables
if not all([api_key, api_secret, org_id]):    

	raise ValueError("Missing required environment variables.
  Please set EXTEND_API_KEY, EXTEND_API_SECRET, 
  and ORGANIZATION_ID")

This section handles importing all necessary libraries and setting up environment variables. We use `python-dotenv` to load variables from our `.env` file and validate that all required credentials are present.

2. Language model configuration

Next, we set up our language model:

# Initialize the language model
llm = ChatOpenAI(
	model="gpt-4o", 
  # You can also use "gpt-3.5-turbo" for a 
  more cost-effective option
)

Here, we're using OpenAI's GPT-4o model through LangChain's `ChatOpenAI` class. You can also use GPT-3.5-turbo for a more cost-effective option, though it may have slightly reduced capabilities.

3. Extend Toolkit configuration

Now, let's configure the Extend AI Toolkit with appropriate permissions:

# Create the Extend LangChain toolkit with appropriate permissions
extend_langchain_toolkit = ExtendLangChainToolkit(
	org_id,
  api_key,
  api_secret,
  Configuration(
  	scope=[
    	Scope(Product.VIRTUAL_CARDS, actions=Actions(read=True)),
      Scope(Product.CREDIT_CARDS, actions=Actions(read=True)),
      Scope(Product.TRANSACTIONS, actions=Actions(read=True)),
     ],       
   	 org_id=org_id    
   	)
   )
   
   # Get the tools from the toolkit
   tools = []
   
   tools.extend(extend_langchain_toolkit.get_tools())

This section creates an instance of the Extend LangChain toolkit with read permissions for virtual cards, credit cards, and transactions. We then extract the tools from the toolkit, which will be used by our agent.

4. React Agent creation

Now, let's create our React agent:

# Create the React agent
langgraph_agent_executor = create_react_agent(
	llm,
  tools
)

This creates a React agent using LangGraph's `create_react_agent` function, which combines our language model with the Extend tools.

5. Chat interface implementation

Finally, let's implement the chat interface:

# Function to interact with the agent
async def chat_with_agent():
	print("\nWelcome to the Extend AI Assistant!")
  print("You can ask me to:")
  print("- List all credit cards")
  print("- List all virtual cards")
  print("- Show details for a specific virtual card")
  print("- Show transactions for a specific period")
  print("- Show details for a specific transaction")
  print("- Create or update virtual cards")
  print("\nType 'exit' to end the conversation.\n")
  
  while True:
  	# Get user input
    user_input = input("\nYou: ").strip()
    
    if user_input.lower() in ['exit', 'quit', 'bye']:
    	print("\nGoodbye!")
    	break
      
    # Process the query
    result = await langgraph_agent_executor.ainvoke({
    	"input": user_input,
      "messages": [
      	SystemMessage(content="You are a helpful assistant 
        that can interact with the Extend API to manage virtual cards, 
        credit cards, and transactions."),
        HumanMessage(content=user_input)
       ]
      })
      
      # Extract and print the assistant's message
      for message in result.get('messages', []):
      	if isinstance(message, AIMessage):
        	print("\nAssistant:", message.content)‍
          
if __name__ == "__main__":
	asyncio.run(chat_with_agent())

This section implements a simple chat interface that allows users to interact with the agent. It displays a welcome message with available capabilities, processes user input, and displays the agent's responses.

Running the agent

To run the agent, simply execute the script:

python extend_agent.py

You'll be presented with a welcome message and a list of capabilities. You can then ask the agent questions like:

  • "List all my virtual cards"
  • "Show me transactions from last month"
  • "Create a new virtual card for my marketing team"
  • "What's the status of my credit card with ID 'card_123'?"

The agent will use the React pattern to:

  1. Understand your request
  2. Determine which tools to use
  3. Execute the appropriate API calls
  4. Format and return the results

Extending the agent

The Extend AI Toolkit provides many more capabilities that you can add to your agent:

  1. Expense categories: Add tools for managing expense categories and labels.
  2. Receipt management: Enable the agent to handle receipt attachments.

To add these capabilities, simply update the `Configuration` object with the appropriate scopes and actions.

Conclusion

In this blog post, we've explored how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We've covered:

  • The basics of LangChain and React agents
  • How to set up the Extend AI Toolkit
  • How to create a custom agent with specific permissions
  • How to interact with the agent to manage virtual cards, credit cards, and transactions

This agent can serve as a foundation for building more complex financial management applications. By combining the power of LangChain with the Extend API, you can create AI assistants that help users manage their finances more effectively.

To learn more about the Extend AI Toolkit, visit the GitHub repository. For more information about LangChain, check out the LangChain documentation.

Happy coding!

Blog

Building an AI Agent with LangChain

Author
Ashkan Abedian
Product Manager & Engineer
Virtual Card Spend
No items found.
Share post

In this blog post, we'll explore how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We'll cover the background of these technologies, how they work together, and provide a step-by-step guide to create your own agent.

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides a set of abstractions and tools that make it easier to build complex applications with LLMs (Large Language Models). LangChain enables developers to:

  • Connect LLMs to external data sources
  • Create chains of operations that can be executed in sequence
  • Build agents that can use tools to accomplish tasks
  • Manage memory and context for conversations

LangChain has become a popular choice for developers building AI applications because it simplifies the integration of LLMs into existing systems and workflows.

What is a React Agent?

The React agent pattern (Reasoning and Acting) is a powerful approach to building AI agents that can solve complex tasks. The name "React" comes from the pattern of alternating between:

1. Reasoning: The agent thinks about what to do next

2. Acting: The agent takes an action based on its reasoning

This pattern allows the agent to:

  • Break down complex problems into smaller steps
  • Use tools to gather information or perform actions
  • Learn from the results of its actions
  • Adapt its approach based on feedback

React agents are particularly effective for tasks that require multiple steps or the use of external tools, making them ideal for interacting with APIs like Extend.

The Extend AI Toolkit

The Extend AI Toolkit is an open-source library that provides tools for integrating with the Extend API in various AI agent frameworks, including LangChain.

It enables AI agents to:

  • Manage virtual cards
  • View credit card information
  • Track transactions
  • Categorize expenses

The toolkit abstracts away the complexity of API interactions, allowing developers to focus on building powerful AI agents that can help users manage their finances.

Setting up your environment

Before we start building our agent, let's set up our development environment:

1. Install Python 3.12 or higher if you don't already have it.

2. Create a virtual environment (recommended):

python -m venv venv   
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install the required packages:

pip install extend-ai-toolkit langchain langchain-openai python-dotenv

4. Set up your Extend API credentials:

   Create a `.env` file in your project directory with the following content:

EXTEND_API_KEY=your_api_key_here
EXTEND_API_SECRET=your_api_secret_here
ORGANIZATION_ID=your_org_id_here
OPENAI_API_KEY=your_openai_api_key_here

You'll need to obtain these credentials from your Extend account. If you don't have an account yet, you can sign up at app.paywithextend.com and follow our Getting Started Guide.

5. Set up your OpenAI API key:

To use LangChain with GPT models, you'll need an OpenAI API key:

   1. Go to [OpenAI's platform](https://platform.openai.com/)

   2. Sign up for an account or log in if you already have one

   3. Navigate to the API keys section

   4. Click "Create new secret key"

   5. Give your key a name (e.g., "Extend Agent")

   6. Copy the generated API key and add it to your `.env` file as `OPENAI_API_KEY`

Note💡

OpenAI offers a free tier with limited usage, but you may need to add a payment method to access GPT-4 models.

Building the React Agent

Now, let's create a Python script that sets up a LangChain React agent with the Extend AI Toolkit. We'll break this down into logical sections to understand each component.

1. Imports and environment setup

First, let's import the necessary libraries and set up our environment variables:

import os

import asyncio

from dotenv import load_dotenv‍

from langchain_openai import ChatOpenAI

from langgraph.prebuilt import create_react_agent

from langchain_core.messages import SystemMessage, AIMessage, HumanMessage‍

from extend_ai_toolkit.langchain.toolkit import ExtendLangChainToolkit

from extend_ai_toolkit.shared import Configuration, Scope, Product, Actions‍

# Load environment variables
load_dotenv()‍

# Get required environment variables
api_key = os.environ.get("EXTEND_API_KEY")
api_secret = os.environ.get("EXTEND_API_SECRET")
org_id = os.environ.get("ORGANIZATION_ID")‍

# Validate environment variables
if not all([api_key, api_secret, org_id]):    

	raise ValueError("Missing required environment variables.
  Please set EXTEND_API_KEY, EXTEND_API_SECRET, 
  and ORGANIZATION_ID")

This section handles importing all necessary libraries and setting up environment variables. We use `python-dotenv` to load variables from our `.env` file and validate that all required credentials are present.

2. Language model configuration

Next, we set up our language model:

# Initialize the language model
llm = ChatOpenAI(
	model="gpt-4o", 
  # You can also use "gpt-3.5-turbo" for a 
  more cost-effective option
)

Here, we're using OpenAI's GPT-4o model through LangChain's `ChatOpenAI` class. You can also use GPT-3.5-turbo for a more cost-effective option, though it may have slightly reduced capabilities.

3. Extend Toolkit configuration

Now, let's configure the Extend AI Toolkit with appropriate permissions:

# Create the Extend LangChain toolkit with appropriate permissions
extend_langchain_toolkit = ExtendLangChainToolkit(
	org_id,
  api_key,
  api_secret,
  Configuration(
  	scope=[
    	Scope(Product.VIRTUAL_CARDS, actions=Actions(read=True)),
      Scope(Product.CREDIT_CARDS, actions=Actions(read=True)),
      Scope(Product.TRANSACTIONS, actions=Actions(read=True)),
     ],       
   	 org_id=org_id    
   	)
   )
   
   # Get the tools from the toolkit
   tools = []
   
   tools.extend(extend_langchain_toolkit.get_tools())

This section creates an instance of the Extend LangChain toolkit with read permissions for virtual cards, credit cards, and transactions. We then extract the tools from the toolkit, which will be used by our agent.

4. React Agent creation

Now, let's create our React agent:

# Create the React agent
langgraph_agent_executor = create_react_agent(
	llm,
  tools
)

This creates a React agent using LangGraph's `create_react_agent` function, which combines our language model with the Extend tools.

5. Chat interface implementation

Finally, let's implement the chat interface:

# Function to interact with the agent
async def chat_with_agent():
	print("\nWelcome to the Extend AI Assistant!")
  print("You can ask me to:")
  print("- List all credit cards")
  print("- List all virtual cards")
  print("- Show details for a specific virtual card")
  print("- Show transactions for a specific period")
  print("- Show details for a specific transaction")
  print("- Create or update virtual cards")
  print("\nType 'exit' to end the conversation.\n")
  
  while True:
  	# Get user input
    user_input = input("\nYou: ").strip()
    
    if user_input.lower() in ['exit', 'quit', 'bye']:
    	print("\nGoodbye!")
    	break
      
    # Process the query
    result = await langgraph_agent_executor.ainvoke({
    	"input": user_input,
      "messages": [
      	SystemMessage(content="You are a helpful assistant 
        that can interact with the Extend API to manage virtual cards, 
        credit cards, and transactions."),
        HumanMessage(content=user_input)
       ]
      })
      
      # Extract and print the assistant's message
      for message in result.get('messages', []):
      	if isinstance(message, AIMessage):
        	print("\nAssistant:", message.content)‍
          
if __name__ == "__main__":
	asyncio.run(chat_with_agent())

This section implements a simple chat interface that allows users to interact with the agent. It displays a welcome message with available capabilities, processes user input, and displays the agent's responses.

Running the agent

To run the agent, simply execute the script:

python extend_agent.py

You'll be presented with a welcome message and a list of capabilities. You can then ask the agent questions like:

  • "List all my virtual cards"
  • "Show me transactions from last month"
  • "Create a new virtual card for my marketing team"
  • "What's the status of my credit card with ID 'card_123'?"

The agent will use the React pattern to:

  1. Understand your request
  2. Determine which tools to use
  3. Execute the appropriate API calls
  4. Format and return the results

Extending the agent

The Extend AI Toolkit provides many more capabilities that you can add to your agent:

  1. Expense categories: Add tools for managing expense categories and labels.
  2. Receipt management: Enable the agent to handle receipt attachments.

To add these capabilities, simply update the `Configuration` object with the appropriate scopes and actions.

Conclusion

In this blog post, we've explored how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We've covered:

  • The basics of LangChain and React agents
  • How to set up the Extend AI Toolkit
  • How to create a custom agent with specific permissions
  • How to interact with the agent to manage virtual cards, credit cards, and transactions

This agent can serve as a foundation for building more complex financial management applications. By combining the power of LangChain with the Extend API, you can create AI assistants that help users manage their finances more effectively.

To learn more about the Extend AI Toolkit, visit the GitHub repository. For more information about LangChain, check out the LangChain documentation.

Happy coding!

Blog

Building an AI Agent with LangChain

Presented by

Ashkan Abedian

Product Manager & Engineer

In this blog post, we'll explore how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We'll cover the background of these technologies, how they work together, and provide a step-by-step guide to create your own agent.

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides a set of abstractions and tools that make it easier to build complex applications with LLMs (Large Language Models). LangChain enables developers to:

  • Connect LLMs to external data sources
  • Create chains of operations that can be executed in sequence
  • Build agents that can use tools to accomplish tasks
  • Manage memory and context for conversations

LangChain has become a popular choice for developers building AI applications because it simplifies the integration of LLMs into existing systems and workflows.

What is a React Agent?

The React agent pattern (Reasoning and Acting) is a powerful approach to building AI agents that can solve complex tasks. The name "React" comes from the pattern of alternating between:

1. Reasoning: The agent thinks about what to do next

2. Acting: The agent takes an action based on its reasoning

This pattern allows the agent to:

  • Break down complex problems into smaller steps
  • Use tools to gather information or perform actions
  • Learn from the results of its actions
  • Adapt its approach based on feedback

React agents are particularly effective for tasks that require multiple steps or the use of external tools, making them ideal for interacting with APIs like Extend.

The Extend AI Toolkit

The Extend AI Toolkit is an open-source library that provides tools for integrating with the Extend API in various AI agent frameworks, including LangChain.

It enables AI agents to:

  • Manage virtual cards
  • View credit card information
  • Track transactions
  • Categorize expenses

The toolkit abstracts away the complexity of API interactions, allowing developers to focus on building powerful AI agents that can help users manage their finances.

Setting up your environment

Before we start building our agent, let's set up our development environment:

1. Install Python 3.12 or higher if you don't already have it.

2. Create a virtual environment (recommended):

python -m venv venv   
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install the required packages:

pip install extend-ai-toolkit langchain langchain-openai python-dotenv

4. Set up your Extend API credentials:

   Create a `.env` file in your project directory with the following content:

EXTEND_API_KEY=your_api_key_here
EXTEND_API_SECRET=your_api_secret_here
ORGANIZATION_ID=your_org_id_here
OPENAI_API_KEY=your_openai_api_key_here

You'll need to obtain these credentials from your Extend account. If you don't have an account yet, you can sign up at app.paywithextend.com and follow our Getting Started Guide.

5. Set up your OpenAI API key:

To use LangChain with GPT models, you'll need an OpenAI API key:

   1. Go to [OpenAI's platform](https://platform.openai.com/)

   2. Sign up for an account or log in if you already have one

   3. Navigate to the API keys section

   4. Click "Create new secret key"

   5. Give your key a name (e.g., "Extend Agent")

   6. Copy the generated API key and add it to your `.env` file as `OPENAI_API_KEY`

Note💡

OpenAI offers a free tier with limited usage, but you may need to add a payment method to access GPT-4 models.

Building the React Agent

Now, let's create a Python script that sets up a LangChain React agent with the Extend AI Toolkit. We'll break this down into logical sections to understand each component.

1. Imports and environment setup

First, let's import the necessary libraries and set up our environment variables:

import os

import asyncio

from dotenv import load_dotenv‍

from langchain_openai import ChatOpenAI

from langgraph.prebuilt import create_react_agent

from langchain_core.messages import SystemMessage, AIMessage, HumanMessage‍

from extend_ai_toolkit.langchain.toolkit import ExtendLangChainToolkit

from extend_ai_toolkit.shared import Configuration, Scope, Product, Actions‍

# Load environment variables
load_dotenv()‍

# Get required environment variables
api_key = os.environ.get("EXTEND_API_KEY")
api_secret = os.environ.get("EXTEND_API_SECRET")
org_id = os.environ.get("ORGANIZATION_ID")‍

# Validate environment variables
if not all([api_key, api_secret, org_id]):    

	raise ValueError("Missing required environment variables.
  Please set EXTEND_API_KEY, EXTEND_API_SECRET, 
  and ORGANIZATION_ID")

This section handles importing all necessary libraries and setting up environment variables. We use `python-dotenv` to load variables from our `.env` file and validate that all required credentials are present.

2. Language model configuration

Next, we set up our language model:

# Initialize the language model
llm = ChatOpenAI(
	model="gpt-4o", 
  # You can also use "gpt-3.5-turbo" for a 
  more cost-effective option
)

Here, we're using OpenAI's GPT-4o model through LangChain's `ChatOpenAI` class. You can also use GPT-3.5-turbo for a more cost-effective option, though it may have slightly reduced capabilities.

3. Extend Toolkit configuration

Now, let's configure the Extend AI Toolkit with appropriate permissions:

# Create the Extend LangChain toolkit with appropriate permissions
extend_langchain_toolkit = ExtendLangChainToolkit(
	org_id,
  api_key,
  api_secret,
  Configuration(
  	scope=[
    	Scope(Product.VIRTUAL_CARDS, actions=Actions(read=True)),
      Scope(Product.CREDIT_CARDS, actions=Actions(read=True)),
      Scope(Product.TRANSACTIONS, actions=Actions(read=True)),
     ],       
   	 org_id=org_id    
   	)
   )
   
   # Get the tools from the toolkit
   tools = []
   
   tools.extend(extend_langchain_toolkit.get_tools())

This section creates an instance of the Extend LangChain toolkit with read permissions for virtual cards, credit cards, and transactions. We then extract the tools from the toolkit, which will be used by our agent.

4. React Agent creation

Now, let's create our React agent:

# Create the React agent
langgraph_agent_executor = create_react_agent(
	llm,
  tools
)

This creates a React agent using LangGraph's `create_react_agent` function, which combines our language model with the Extend tools.

5. Chat interface implementation

Finally, let's implement the chat interface:

# Function to interact with the agent
async def chat_with_agent():
	print("\nWelcome to the Extend AI Assistant!")
  print("You can ask me to:")
  print("- List all credit cards")
  print("- List all virtual cards")
  print("- Show details for a specific virtual card")
  print("- Show transactions for a specific period")
  print("- Show details for a specific transaction")
  print("- Create or update virtual cards")
  print("\nType 'exit' to end the conversation.\n")
  
  while True:
  	# Get user input
    user_input = input("\nYou: ").strip()
    
    if user_input.lower() in ['exit', 'quit', 'bye']:
    	print("\nGoodbye!")
    	break
      
    # Process the query
    result = await langgraph_agent_executor.ainvoke({
    	"input": user_input,
      "messages": [
      	SystemMessage(content="You are a helpful assistant 
        that can interact with the Extend API to manage virtual cards, 
        credit cards, and transactions."),
        HumanMessage(content=user_input)
       ]
      })
      
      # Extract and print the assistant's message
      for message in result.get('messages', []):
      	if isinstance(message, AIMessage):
        	print("\nAssistant:", message.content)‍
          
if __name__ == "__main__":
	asyncio.run(chat_with_agent())

This section implements a simple chat interface that allows users to interact with the agent. It displays a welcome message with available capabilities, processes user input, and displays the agent's responses.

Running the agent

To run the agent, simply execute the script:

python extend_agent.py

You'll be presented with a welcome message and a list of capabilities. You can then ask the agent questions like:

  • "List all my virtual cards"
  • "Show me transactions from last month"
  • "Create a new virtual card for my marketing team"
  • "What's the status of my credit card with ID 'card_123'?"

The agent will use the React pattern to:

  1. Understand your request
  2. Determine which tools to use
  3. Execute the appropriate API calls
  4. Format and return the results

Extending the agent

The Extend AI Toolkit provides many more capabilities that you can add to your agent:

  1. Expense categories: Add tools for managing expense categories and labels.
  2. Receipt management: Enable the agent to handle receipt attachments.

To add these capabilities, simply update the `Configuration` object with the appropriate scopes and actions.

Conclusion

In this blog post, we've explored how to build an AI agent that can interact with the Extend API using LangChain and the React agent pattern. We've covered:

  • The basics of LangChain and React agents
  • How to set up the Extend AI Toolkit
  • How to create a custom agent with specific permissions
  • How to interact with the agent to manage virtual cards, credit cards, and transactions

This agent can serve as a foundation for building more complex financial management applications. By combining the power of LangChain with the Extend API, you can create AI assistants that help users manage their finances more effectively.

To learn more about the Extend AI Toolkit, visit the GitHub repository. For more information about LangChain, check out the LangChain documentation.

Happy coding!

Keep reading

No items found.

Talk to the experts

Learn more about Extend and find out if it's the right solution for your business.