LangChain integration for RunPod serverless endpoints
Project description
RunPod LangChain Integration
A custom LangChain chat model for integrating RunPod serverless endpoints with LangChain.
🚀 Features
- ✅ Full LangChain
BaseChatModelcompatibility - ✅ Support for all message types (System, Human, AI)
- ✅ LCEL chain support
- ✅ Parameter customization (temperature, max_tokens, stop sequences)
- ✅ Proper response parsing from RunPod format
- ✅ Multi-turn conversation support
📦 Installation
Prerequisites
pip install langchain-core requests python-dotenv
Setup
- Copy the
runpod_langchaindirectory to your project - Create a
.envfile with your RunPod credentials:
RUNPOD_ENDPOINT_ID=your-endpoint-id
RUNPOD_API_KEY=your-api-key
🎯 Usage
Basic Usage
from runpod_langchain import RunPodChatModel
import os
llm = RunPodChatModel(
endpoint_id=os.getenv("RUNPOD_ENDPOINT_ID"),
api_key=os.getenv("RUNPOD_API_KEY"),
max_tokens=512,
temperature=0.7
)
response = llm.invoke("What is Python?")
print(response.content)
With Message Types
from langchain_core.messages import SystemMessage, HumanMessage
messages = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content="What is machine learning?")
]
response = llm.invoke(messages)
print(response.content)
LCEL Chains (Recommended)
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("human", "{input}")
])
chain = prompt | llm | StrOutputParser()
result = chain.invoke({"input": "Tell me a joke"})
Multi-turn Conversations
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
conversation = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content="My name is Alice.")
]
response1 = llm.invoke(conversation)
# Continue conversation
conversation.append(AIMessage(content=response1.content))
conversation.append(HumanMessage(content="What's my name?"))
response2 = llm.invoke(conversation)
Override Parameters
# Override default parameters per request
response = llm.invoke(
"Write something creative",
max_tokens=100,
temperature=1.0
)
📁 Project Structure
runpod_langchain/
├── __init__.py # Package initialization
├── chat_model.py # RunPodChatModel implementation
examples.py # Usage examples
README.md # This file
🔧 API Reference
RunPodChatModel
Parameters:
endpoint_id(str): Your RunPod endpoint IDapi_key(str): Your RunPod API keymax_tokens(int, default=512): Maximum tokens to generatetemperature(float, default=0.7): Sampling temperature (0.0-2.0)
Methods:
invoke(messages, **kwargs): Generate a response_generate(messages, stop, run_manager, **kwargs): Internal generation method
Supported kwargs in invoke:
max_tokens: Override default max tokenstemperature: Override default temperaturestop: List of stop sequences
🎓 Examples
Run the examples file:
python examples.py
This will run 5 different examples showing various usage patterns.
🔍 How It Works
- Message Conversion: Converts LangChain messages to prompt format
- API Call: Makes POST request to RunPod serverless endpoint
- Response Parsing: Extracts text from RunPod's response format
- LangChain Integration: Returns properly formatted ChatResult
RunPod Response Format
RunPod typically returns responses in this format:
[{
'choices': [{
'tokens': ['token1', 'token2', ...]
}],
'usage': {
'input': 10,
'output': 50
}
}]
The RunPodChatModel automatically parses this and extracts the text.
🐛 Troubleshooting
Import Errors
If you get ModuleNotFoundError: No module named 'langchain.chains':
- You only need
langchain-core, not the fulllangchainpackage - Use LCEL chains instead of legacy
LLMChain
Response Format Issues
If responses look wrong:
- Check that your RunPod endpoint returns the expected format
- Modify
_extract_text()method if your endpoint uses a different format
API Errors
If you get 404 or authentication errors:
- Verify your
RUNPOD_ENDPOINT_IDis correct - Verify your
RUNPOD_API_KEYis correct - Ensure you're using a serverless endpoint, not a vLLM pod
📝 Notes
- This integration is designed for RunPod serverless endpoints
- For vLLM pods, use
ChatOpenAIinstead - Streaming is not currently supported (serverless endpoints typically don't support it)
- Async methods are not implemented
🤝 Contributing
Feel free to extend this implementation with:
- Streaming support (if your endpoint supports it)
- Async methods (
_agenerate) - Additional error handling
- Custom response parsers
📄 License
MIT License - Feel free to use and modify as needed.
🔗 Resources
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file runpod_langchain-0.1.0.tar.gz.
File metadata
- Download URL: runpod_langchain-0.1.0.tar.gz
- Upload date:
- Size: 10.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
447599dac1eb69b9d3e5e6a17aa84433811aca5b8a22b203a36517243f8495d1
|
|
| MD5 |
67d697cf0c3caf60b7eec4c402d1a165
|
|
| BLAKE2b-256 |
3989d2c3dd3e14a6f6b19be88bbc8b1661a2f76b66dbbffb99da66867f686b0a
|
File details
Details for the file runpod_langchain-0.1.0-py3-none-any.whl.
File metadata
- Download URL: runpod_langchain-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e8dfc34c319af9633b7ed05c8ce45359e22b3dd96532e5a94188101daf9a3ac2
|
|
| MD5 |
7fc7cfa53ef1ae97f51e6376849a3249
|
|
| BLAKE2b-256 |
f2429821b3f9463c2217d5973d713577ae3a0112c57440b9c86dd39c29b03bc5
|