langchain-react-agent.ipynb•8.27 kB
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import asyncio\n",
"from dotenv import load_dotenv\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_core.messages import SystemMessage, AIMessage, HumanMessage\n",
"\n",
"from extend_ai_toolkit.langchain.toolkit import ExtendLangChainToolkit\n",
"from extend_ai_toolkit.shared import Configuration, Scope, Product, Actions\n",
"\n",
"from IPython.display import display, clear_output\n",
"import ipywidgets as widgets\n",
"\n",
"import nest_asyncio\n",
"nest_asyncio.apply()"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables\n",
"load_dotenv()\n",
"\n",
"# Get required environment variables\n",
"api_key = os.environ.get(\"EXTEND_API_KEY\")\n",
"api_secret = os.environ.get(\"EXTEND_API_SECRET\")\n",
"\n",
"# Validate environment variables\n",
"if not all([api_key, api_secret]):\n",
" raise ValueError(\"Missing required environment variables. Please set EXTEND_API_KEY and EXTEND_API_SECRET\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"llm = ChatOpenAI(\n",
" model=\"gpt-4o\",\n",
")\n",
"\n",
"extend_langchain_toolkit = ExtendLangChainToolkit.default_instance(\n",
" api_key,\n",
" api_secret,\n",
" Configuration(\n",
" scope=[\n",
" Scope(Product.VIRTUAL_CARDS, actions=Actions(read=True,update=True)),\n",
" Scope(Product.CREDIT_CARDS, actions=Actions(read=True)),\n",
" Scope(Product.TRANSACTIONS, actions=Actions(read=True,update=True)),\n",
" Scope(Product.EXPENSE_CATEGORIES, actions=Actions(read=True)),\n",
" Scope(Product.RECEIPT_ATTACHMENTS, actions=Actions(read=True)),\n",
" ]\n",
" )\n",
")\n",
"\n",
"tools = []\n",
"tools.extend(extend_langchain_toolkit.get_tools())\n",
"\n",
"# Create the react agent\n",
"langgraph_agent_executor = create_react_agent(\n",
" llm,\n",
" tools\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"async def chat_with_agent():\n",
" print(\"\\nWelcome to the Extend AI Assistant!\")\n",
" print(\"I'll send a sequence of predefined messages to the agent and show the responses.\\n\")\n",
" \n",
" # Define the messages to send\n",
" messages = [\n",
" \"please show me transactions from feb 2025 from langchain inc\",\n",
" \"please tell me about my expense categories and labels\",\n",
" \"please tell me which transactions from feb 2025 are missing receipts\" ]\n",
" \n",
" # Send each message and print the response\n",
" for i, user_input in enumerate(messages, 1):\n",
" print(f\"\\n--- Message {i}: {user_input} ---\")\n",
" print(\"Assistant: \", end=\"\", flush=True)\n",
" \n",
" # Process the query\n",
" result = await langgraph_agent_executor.ainvoke({\n",
" \"input\": user_input,\n",
" \"messages\": [\n",
" SystemMessage(content=\"You are a helpful assistant that can interact with the Extend API to manage virtual cards, credit cards, and transactions.\"),\n",
" HumanMessage(content=user_input)\n",
" ]\n",
" })\n",
" \n",
" # Extract and print the assistant's message\n",
" for message in result.get('messages', []):\n",
" if isinstance(message, AIMessage):\n",
" print(message.content)\n",
" \n",
" # Add a separator between messages\n",
" print(\"\\n\" + \"-\" * 50)\n",
" \n",
" print(\"\\nAll messages have been processed.\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Welcome to the Extend AI Assistant!\n",
"I'll send a sequence of predefined messages to the agent and show the responses.\n",
"\n",
"\n",
"--- Message 1: please show me transactions from feb 2025 from langchain inc ---\n",
"Assistant: \n",
"Here are the transactions from February 2025 with Langchain Inc.:\n",
"\n",
"1. **Transaction ID:** txn_2ahU0UDCn6e7CwnjKEMP24\n",
" - **Amount:** $39.00\n",
" - **Status:** CLEARED\n",
" - **Cardholder Name:** Jonathan Bailey\n",
" - **Recipient Name:** Jonathan Bailey\n",
" - **Merchant:** LANGCHAIN, INC.\n",
" - **Merchant Category Code (MCC):** Computer Software Stores\n",
" - **Review Status:** PENDING_REVIEW\n",
" - **Receipt Required:** No\n",
" - **Receipt Attachments Count:** 0\n",
" - **Synced to ERP:** No\n",
"\n",
"2. **Transaction ID:** txn_2mxwPYd582B9TtzQlI7Sd9\n",
" - **Amount:** $39.00\n",
" - **Status:** CLEARED\n",
" - **Cardholder Name:** Jonathan Bailey\n",
" - **Recipient Name:** Jonathan Bailey\n",
" - **Merchant:** LANGCHAIN, INC.\n",
" - **Merchant Category Code (MCC):** Computer Software Stores\n",
" - **Review Status:** PENDING_REVIEW\n",
" - **Receipt Required:** No\n",
" - **Receipt Attachments Count:** 0\n",
" - **Synced to ERP:** No\n",
"\n",
"3. **Transaction ID:** txn_3xEnXq2v3x15nPY4gQj4uN\n",
" - **Amount:** $34.36\n",
" - **Status:** CLEARED\n",
" - **Cardholder Name:** Jonathan Bailey\n",
" - **Recipient Name:** Jonathan Bailey\n",
" - **Merchant:** LANGCHAIN, INC.\n",
" - **Merchant Category Code (MCC):** Computer Software Stores\n",
" - **Review Status:** PENDING_REVIEW\n",
" - **Receipt Required:** No\n",
" - **Receipt Attachments Count:** 0\n",
" - **Synced to ERP:** No\n",
"\n",
"If you need more information on any of these transactions or further assistance, please let me know!\n",
"\n",
"--------------------------------------------------\n",
"\n",
"--- Message 2: please tell me about my expense categories and labels ---\n",
"Assistant: \n",
"\n",
"Here are your active expense categories and their associated labels:\n",
"\n",
"### 1. Dues & Subscriptions\n",
"- **Labels:**\n",
" - **Cloud Hosting Platforms** (Code: Cloud)\n",
" - **Software subscriptions** (Code: Software)\n",
"\n",
"### 2. Meals & Entertainment\n",
"- **Labels:**\n",
" - **Clients Meals** (Code: Clients)\n",
" - **Staff Meals** (Code: Staff)\n",
"\n",
"These categories and labels help organize your expenses effectively. Let me know if you need more information or assistance!\n",
"\n",
"--------------------------------------------------\n",
"\n",
"--- Message 3: please tell me which transactions are missing receipts ---\n",
"Assistant: \n",
"There are no transactions currently missing receipts. If you have any other questions or need further assistance, feel free to ask!\n",
"\n",
"--------------------------------------------------\n",
"\n",
"All messages have been processed.\n"
]
}
],
"source": [
"await chat_with_agent()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}