> ## Documentation Index
> Fetch the complete documentation index at: https://paylink.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain Integration

> Integrate PayLink with LangChain for payment-enabled AI agents

# LangChain Integration

This guide demonstrates how to integrate PayLink with LangChain to create AI agents that can process payments as part of their workflows. The integration uses PayLink's LangChain adapter, which formats PayLink tools to be compatible with LangChain's tools API.

## Prerequisites

Before you begin, make sure you have:

* Installed the PayLink SDK
* Installed LangChain
* Access to a PayLink server with payment tools
* An OpenAI API key (or other supported LLM provider)

## Installation

Install the required packages:

```bash theme={null}
pip install paylink-sdk langchain langchain-openai
```

## Basic Integration

### Step 1: Initialize the PayLink Client

First, initialize the PayLink client using the LangChain adapter:

```python theme={null}
from paylink_sdk.langchain_adapter.toolkit import PayLinkClient

# Initialize the client
paylink_client = PayLinkClient()

# List available tools in LangChain-compatible format
tools = await paylink_client.list_tools()
```

The `PayLinkClient` from the `langchain_adapter.toolkit` module automatically formats PayLink tools in a way that's compatible with LangChain's tools API.

### Step 2: Set Up LangChain LLM

Initialize a language model from LangChain:

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
```

### Step 3: Bind the Tools to the LLM

Bind the PayLink tools to the language model:

```python theme={null}
llm_with_tools = llm.bind_tools(tools=tools)
```

### Step 4: Invoke the LLM with a Payment Request

Send a payment request to the LLM:

```python theme={null}
response = llm_with_tools.invoke("Initiate an stk push to 2547123456789 amount is 1ksh account reference invoice, transaction description invoice-123, transaction type CustomerBuyGoodsOnline")
```

The LLM will generate a tool call to the appropriate PayLink function.

### Step 5: Execute the PayLink Tool

Extract the tool name and arguments from the LLM response, then call the PayLink tool:

```python theme={null}
# Extract tool name and arguments from the response
# (This will depend on your specific implementation)
name = "stk_push"  # The tool name from the response
args = {
    "phone_number": "2547123456789",
    "amount": 1,
    "account_reference": "invoice",
    "transaction_desc": "invoice-123",
    "transaction_type": "CustomerBuyGoodsOnline",
}

# Call the PayLink tool
result = await paylink_client.call_tool(name, args)

# View the result
print(result)
```

## Error Handling

When integrating with payment systems, proper error handling is essential:

```python theme={null}
try:
    result = await paylink_client.call_tool(tool_name, tool_input)
    # Process successful payment
except Exception as e:
    # Handle payment failure
    error_message = str(e)
    print(f"Payment failed: {error_message}")
    
    # Return error information to the agent
    return {"error": error_message}
```

## Next Steps

Now that you've integrated PayLink with LangChain, you can:

* Create more complex agents with multiple tools
* Implement conversational memory for payment history
* Build multi-step payment workflows
* Add user authentication and authorization

Check out our [OpenAI integration guide](/ai-integration/openai) for an alternative approach to AI-powered payments.

## Troubleshooting

**Tool Execution Error**: If you receive an error during tool execution, ensure that:

* The PayLink server is running and accessible
* You're correctly parsing the tool input
* Your PayLink SDK is up to date

**Agent Not Using Tools**: If the agent isn't using the PayLink tools:

* Check that the tools were properly bound to the LLM
* Make sure the user request clearly indicates a payment action
* Try adjusting the system prompt to emphasize payment capabilities

For more assistance, refer to our [troubleshooting guide](/get-started/troubleshooting) or contact support.
