DEV Community

vinod
vinod

Posted on

LangChain and OpenRouter in Python

🚀 create_agent Using LangChain and OpenRouter in Python

Artificial Intelligence doesn’t have to be complicated. In this short tutorial, I’ll show you how to build a simple create_agent using Python, LangChain, and OpenRouter in just a few steps. This is perfect for beginners who want to understand how AI APIs work in real projects.


👉 GitHub Repository: https://github.com/yourusername/langchain_python

🧠 What We’re Building

We’ll create a small Python script that:

  • Connects to an AI model using OpenRouter
  • Uses LangChain to manage the conversation
  • Asks a simple question
  • Prints the AI’s response in the terminal

Example question:

“What is artificial intelligence in simple terms?”


📁 Project Structure

langchain_python/
└── python_example/
    ├── createagent.py
    ├── .env
    └── README.md
Enter fullscreen mode Exit fullscreen mode

✅ Prerequisites

Before starting, make sure you have:

  • Python 3.9+
  • An OpenRouter API key
  • Basic knowledge of running Python scripts

📦 Step 1: Install Required Packages

Go to the python_example folder and run:

pip install langchain langchain-openai python-dotenv
Enter fullscreen mode Exit fullscreen mode

🔐 Step 2: Add Your API Key Safely

Create a file named .env inside python_example and add:

OPENROUTER_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

This keeps your API key secure and out of your source code.


🧑‍💻 Step 3: The Python Script (createagent.py)

Your script does the following:

  • Loads the API key from .env
  • Connects to OpenRouter using an OpenAI-compatible setup
  • Creates a simple LangChain agent
  • Sends a user question
  • Prints the AI’s response safely

The key idea is simple:

You send a message → the AI processes it → you print the response.


🧑‍💻 Step 4: The Python code

import os
from langchain.agents import create_agent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

# Load environment variables
load_dotenv()

# Get API key
OPENROUTER_KEY = os.getenv("OPENROUTER_API_KEY")
if not OPENROUTER_KEY:
    raise ValueError("Missing OPENROUTER_API_KEY in environment")

# Set OpenAI-compatible environment variables for OpenRouter
os.environ["OPENAI_API_KEY"] = OPENROUTER_KEY
os.environ["OPENAI_BASE_URL"] = "https://openrouter.ai/api/v1"

# Create LLM
llm = ChatOpenAI(
    model="mistralai/mistral-7b-instruct:free",
    temperature=0.7,
    api_key=OPENROUTER_KEY,
)

# Create agent
agent = create_agent(
    llm,
    tools=[],
    system_prompt="You are a helpful assistant. Answer in simple words."
)

# User input
user_question = "What is artificial intelligence in simple terms?"

# Invoke agent
response = agent.invoke({
    "messages": [
        {"role": "user", "content": user_question}
    ]
})

# Extract and print AI response safely
if "messages" in response and len(response["messages"]) > 0:
    ai_message = response["messages"][-1]
    print(ai_message.content)
else:
    print("No response received from the agent.")

Enter fullscreen mode Exit fullscreen mode

▶️ Step 5: Run the Project

From the python_example folder, run:

python createagent.py
Enter fullscreen mode Exit fullscreen mode

🧾 Sample Output

Artificial intelligence is when computers are taught to think and learn like humans to perform tasks such as answering questions and making decisions.
Enter fullscreen mode Exit fullscreen mode

💡 What You Learn From This Project

With this small example, you learn:

  • How to use environment variables in Python
  • How to connect Python to an AI model
  • How LangChain agents work at a basic level
  • How to safely extract and print an AI response

✅ Final Thoughts

This project is a great starting point for anyone entering AI development with Python. With just a few steps, you’ve built a working AI-powered chatbot using modern tools like LangChain and OpenRouter.

If you’re learning AI integration, this is the perfect first milestone. ✅


Top comments (0)