LangChain OpenTutorial
  • 🦜️🔗 The LangChain Open Tutorial for Everyone
  • 01-Basic
    • Getting Started on Windows
    • 02-Getting-Started-Mac
    • OpenAI API Key Generation and Testing Guide
    • LangSmith Tracking Setup
    • Using the OpenAI API (GPT-4o Multimodal)
    • Basic Example: Prompt+Model+OutputParser
    • LCEL Interface
    • Runnable
  • 02-Prompt
    • Prompt Template
    • Few-Shot Templates
    • LangChain Hub
    • Personal Prompts for LangChain
    • Prompt Caching
  • 03-OutputParser
    • PydanticOutputParser
    • PydanticOutputParser
    • CommaSeparatedListOutputParser
    • Structured Output Parser
    • JsonOutputParser
    • PandasDataFrameOutputParser
    • DatetimeOutputParser
    • EnumOutputParser
    • Output Fixing Parser
  • 04-Model
    • Using Various LLM Models
    • Chat Models
    • Caching
    • Caching VLLM
    • Model Serialization
    • Check Token Usage
    • Google Generative AI
    • Huggingface Endpoints
    • HuggingFace Local
    • HuggingFace Pipeline
    • ChatOllama
    • GPT4ALL
    • Video Q&A LLM (Gemini)
  • 05-Memory
    • ConversationBufferMemory
    • ConversationBufferWindowMemory
    • ConversationTokenBufferMemory
    • ConversationEntityMemory
    • ConversationKGMemory
    • ConversationSummaryMemory
    • VectorStoreRetrieverMemory
    • LCEL (Remembering Conversation History): Adding Memory
    • Memory Using SQLite
    • Conversation With History
  • 06-DocumentLoader
    • Document & Document Loader
    • PDF Loader
    • WebBaseLoader
    • CSV Loader
    • Excel File Loading in LangChain
    • Microsoft Word(doc, docx) With Langchain
    • Microsoft PowerPoint
    • TXT Loader
    • JSON
    • Arxiv Loader
    • UpstageDocumentParseLoader
    • LlamaParse
    • HWP (Hangeul) Loader
  • 07-TextSplitter
    • Character Text Splitter
    • 02. RecursiveCharacterTextSplitter
    • Text Splitting Methods in NLP
    • TokenTextSplitter
    • SemanticChunker
    • Split code with Langchain
    • MarkdownHeaderTextSplitter
    • HTMLHeaderTextSplitter
    • RecursiveJsonSplitter
  • 08-Embedding
    • OpenAI Embeddings
    • CacheBackedEmbeddings
    • HuggingFace Embeddings
    • Upstage
    • Ollama Embeddings With Langchain
    • LlamaCpp Embeddings With Langchain
    • GPT4ALL
    • Multimodal Embeddings With Langchain
  • 09-VectorStore
    • Vector Stores
    • Chroma
    • Faiss
    • Pinecone
    • Qdrant
    • Elasticsearch
    • MongoDB Atlas
    • PGVector
    • Neo4j
    • Weaviate
    • Faiss
    • {VectorStore Name}
  • 10-Retriever
    • VectorStore-backed Retriever
    • Contextual Compression Retriever
    • Ensemble Retriever
    • Long Context Reorder
    • Parent Document Retriever
    • MultiQueryRetriever
    • MultiVectorRetriever
    • Self-querying
    • TimeWeightedVectorStoreRetriever
    • TimeWeightedVectorStoreRetriever
    • Kiwi BM25 Retriever
    • Ensemble Retriever with Convex Combination (CC)
  • 11-Reranker
    • Cross Encoder Reranker
    • JinaReranker
    • FlashRank Reranker
  • 12-RAG
    • Understanding the basic structure of RAG
    • RAG Basic WebBaseLoader
    • Exploring RAG in LangChain
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • Conversation-With-History
    • Translation
    • Multi Modal RAG
  • 13-LangChain-Expression-Language
    • RunnablePassthrough
    • Inspect Runnables
    • RunnableLambda
    • Routing
    • Runnable Parallel
    • Configure-Runtime-Chain-Components
    • Creating Runnable objects with chain decorator
    • RunnableWithMessageHistory
    • Generator
    • Binding
    • Fallbacks
    • RunnableRetry
    • WithListeners
    • How to stream runnables
  • 14-Chains
    • Summarization
    • SQL
    • Structured Output Chain
    • StructuredDataChat
  • 15-Agent
    • Tools
    • Bind Tools
    • Tool Calling Agent
    • Tool Calling Agent with More LLM Models
    • Iteration-human-in-the-loop
    • Agentic RAG
    • CSV/Excel Analysis Agent
    • Agent-with-Toolkits-File-Management
    • Make Report Using RAG, Web searching, Image generation Agent
    • TwoAgentDebateWithTools
    • React Agent
  • 16-Evaluations
    • Generate synthetic test dataset (with RAGAS)
    • Evaluation using RAGAS
    • HF-Upload
    • LangSmith-Dataset
    • LLM-as-Judge
    • Embedding-based Evaluator(embedding_distance)
    • LangSmith Custom LLM Evaluation
    • Heuristic Evaluation
    • Compare experiment evaluations
    • Summary Evaluators
    • Groundedness Evaluation
    • Pairwise Evaluation
    • LangSmith Repeat Evaluation
    • LangSmith Online Evaluation
    • LangFuse Online Evaluation
  • 17-LangGraph
    • 01-Core-Features
      • Understanding Common Python Syntax Used in LangGraph
      • Title
      • Building a Basic Chatbot with LangGraph
      • Building an Agent with LangGraph
      • Agent with Memory
      • LangGraph Streaming Outputs
      • Human-in-the-loop
      • LangGraph Manual State Update
      • Asking Humans for Help: Customizing State in LangGraph
      • DeleteMessages
      • DeleteMessages
      • LangGraph ToolNode
      • LangGraph ToolNode
      • Branch Creation for Parallel Node Execution
      • Conversation Summaries with LangGraph
      • Conversation Summaries with LangGraph
      • LangGrpah Subgraph
      • How to transform the input and output of a subgraph
      • LangGraph Streaming Mode
      • Errors
      • A Long-Term Memory Agent
    • 02-Structures
      • LangGraph-Building-Graphs
      • Naive RAG
      • Add Groundedness Check
      • Adding a Web Search Module
      • LangGraph-Add-Query-Rewrite
      • Agentic RAG
      • Adaptive RAG
      • Multi-Agent Structures (1)
      • Multi Agent Structures (2)
    • 03-Use-Cases
      • LangGraph Agent Simulation
      • Meta Prompt Generator based on User Requirements
      • CRAG: Corrective RAG
      • Plan-and-Execute
      • Multi Agent Collaboration Network
      • Multi Agent Collaboration Network
      • Multi-Agent Supervisor
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • 08-LangGraph-Hierarchical-Multi-Agent-Teams
      • SQL-Agent
      • 10-LangGraph-Research-Assistant
      • LangGraph Code Assistant
      • Deploy on LangGraph Cloud
      • Tree of Thoughts (ToT)
      • Ollama Deep Researcher (Deepseek-R1)
      • Functional API
      • Reflection in LangGraph
  • 19-Cookbook
    • 01-SQL
      • TextToSQL
      • SpeechToSQL
    • 02-RecommendationSystem
      • ResumeRecommendationReview
    • 03-GraphDB
      • Movie QA System with Graph Database
      • 05-TitanicQASystem
      • Real-Time GraphRAG QA
    • 04-GraphRAG
      • Academic Search System
      • Academic QA System with GraphRAG
    • 05-AIMemoryManagementSystem
      • ConversationMemoryManagementSystem
    • 06-Multimodal
      • Multimodal RAG
      • Shopping QnA
    • 07-Agent
      • 14-MoARAG
      • CoT Based Smart Web Search
      • 16-MultiAgentShoppingMallSystem
      • Agent-Based Dynamic Slot Filling
      • Code Debugging System
      • New Employee Onboarding Chatbot
      • 20-LangGraphStudio-MultiAgent
      • Multi-Agent Scheduler System
    • 08-Serving
      • FastAPI Serving
      • Sending Requests to Remote Graph Server
      • Building a Agent API with LangServe: Integrating Currency Exchange and Trip Planning
    • 08-SyntheticDataset
      • Synthetic Dataset Generation using RAG
    • 09-Monitoring
      • Langfuse Selfhosting
Powered by GitBook
On this page
  • Overview
  • Table of Contents
  • References
  • Environment Setup
  • Runtime Arguments Binding
  • Connecting OpenAI Functions
  • Connecting OpenAI Tools
  1. 13-LangChain-Expression-Language

Binding

PreviousGeneratorNextFallbacks

Last updated 28 days ago

  • Author:

  • Peer Review:

  • Proofread :

  • This is a part of

Overview

This tutorial covers a scenario where you need to pass constant arguments(not included in the output of the previous Runnable or user input) when calling a Runnable inside a Runnable sequence. In such cases, Runnable.bind() is a convenient way to pass these arguments

Table of Contents

References


Environment Setup

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup tools, useful functions and utilities for tutorials.

Load sample text and output the content.

%%capture --no-stderr
%pip install langchain-opentutorial
    [notice] A new release of pip is available: 24.2 -> 24.3.1
    [notice] To update, run: python.exe -m pip install --upgrade pip
# Install required packages
from langchain_opentutorial import package


package.install(
    [
        "langsmith",
        "langchain",
        "langchain_core",
        "langchain_openai",
    ],
    verbose=False,
    upgrade=False,
)
# Set environment variables
from langchain_opentutorial import set_env

set_env(
    {
        "OPENAI_API_KEY": "",
        "LANGCHAIN_API_KEY": "",
        "LANGCHAIN_TRACING_V2": "true",
        "LANGCHAIN_ENDPOINT": "https://api.smith.langchain.com",
        "LANGCHAIN_PROJECT": "Binding",  # title
    }
)
Environment variables have been set successfully.

You can alternatively set OPENAI_API_KEY in .env file and load it.

[Note] This is not necessary if you've already set OPENAI_API_KEY in previous steps.

# Configuration File for Managing API Keys as Environment Variables
from dotenv import load_dotenv

# Load API Key Information
load_dotenv(override=True)
True

Runtime Arguments Binding

This section explains how to use Runnable.bind() to pass constant arguments to a Runnable within a sequence, especially when those arguments aren't part of the previous Runnable's output or user input.

Passing variables to prompts:

  1. Use RunnablePassthrough to pass the {equation_statement} variable to the prompt.

  2. Use StrOutputParser to parse the model's output into a string, creating a runnable object.

  3. Call the runnable.invoke() method to pass the equation statement (e.g., "x raised to the third plus seven equals 12") and get the result.

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            # Write the following equation using algebraic symbols and then solve it.
            "Write out the following equation using algebraic symbols then solve it. "
            "Please avoid LaTeX-style formatting and use plain symbols."
            "Use the format:\n\nEQUATION:...\nSOLUTION:...\n",
        ),
        (
            "human",
            "{equation_statement}",  # Accepts the equation statement from the user as a variable.
        ),
    ]
)
# Initialize the ChatOpenAI model and set temperature to 0.
model = ChatOpenAI(model="gpt-4o", temperature=0)

# Pass the equation statement to the prompt and parse the model's output as a string.
runnable = (
    {"equation_statement": RunnablePassthrough()} | prompt | model | StrOutputParser()
)

# Input an example equation statement and print the result.
result = runnable.invoke("x raised to the third plus seven equals 12")
print(result)
EQUATION: x^3 + 7 = 12
    
    SOLUTION:
    1. Subtract 7 from both sides of the equation to isolate the x^3 term:
       x^3 + 7 - 7 = 12 - 7
       x^3 = 5
    
    2. Take the cube root of both sides to solve for x:
       x = 5^(1/3)
    
    Therefore, the solution is:
    x ≈ 1.71 (rounded to two decimal places)

Using bind() method with stop words

For controlling the end of the model's output using a specific stop word, you can use model.bind() to instruct the model to halt its generation upon encountering the stop token such as SOLUTION.

runnable = (
    # Create a runnable passthrough object and assign it to the "equation_statement" key.
    {"equation_statement": RunnablePassthrough()}
    | prompt  # Add the prompt to the pipeline.
    | model.bind(
        stop="SOLUTION"
    )  # Bind the model and set it to stop generating at the "SOLUTION" token.
    | StrOutputParser()  # Add the string output parser to the pipeline.
)
# Execute the pipeline with the input "x raised to the third plus seven equals 12" and print the result.
print(runnable.invoke("x raised to the third plus seven equals 12"))
EQUATION: x^3 + 7 = 12
    
    

Connecting OpenAI Functions

bind() is particularly useful for connecting OpenAI Functions with compatible OpenAI models.

Let's define openai_function according to a schema.

openai_function = {
    "name": "solver",  # Function name
    # Function description: Formulate and solve an equation.
    "description": "Formulates and solves an equation",
    "parameters": {  # Function parameters
        "type": "object",  # Parameter type: object
        "properties": {  # Parameter properties
            "equation": {  # Equation property
                "type": "string",  # Type: string
                "description": "The algebraic expression of the equation",  # Description
            },
            "solution": {  # Solution property
                "type": "string",  # Type: string
                "description": "The solution to the equation",  # Description
            },
        },
        "required": [
            "equation",
            "solution",
        ],  # Required parameters: equation and solution
    },
}

Binding the solver function.

We can then use the bind() method to associate a function call (like solver) with the language model.

# Write the following equation using algebraic symbols and then solve it
prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "Write out the following equation using algebraic symbols then solve it.",
        ),
        ("human", "{equation_statement}"),
    ]
)


model = ChatOpenAI(model="gpt-4o", temperature=0).bind(
    function_call={"name": "solver"},  # Bind the OpenAI function schema
    functions=[openai_function],
)


runnable = {"equation_statement": RunnablePassthrough()} | prompt | model


# Equation: x raised to the third plus seven equals 12


runnable.invoke("x raised to the third plus seven equals 12")
AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"equation":"x^3 + 7 = 12","solution":"x^3 = 12 - 7; x^3 = 5; x = 5^(1/3)"}', 'name': 'solver'}, 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 44, 'prompt_tokens': 95, 'total_tokens': 139, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_50cad350e4', 'finish_reason': 'stop', 'logprobs': None}, id='run-bb333525-2117-4a09-bf1c-c6bdca21b50c-0', usage_metadata={'input_tokens': 95, 'output_tokens': 44, 'total_tokens': 139, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})

Connecting OpenAI Tools

This section explains how to connect and use OpenAI tools within your LangChain applications. The tools object simplifies using various OpenAI features. For example, calling the tool.run method with a natural language query allows the model to utilize the specified tool to generate a response.

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",  # Function name to get current weather
            "description": "Fetches the current weather for a given location",  # Description
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and state, e.g.: San Francisco, CA",  # Location description
                    },
                    # Temperature unit
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],  # Required parameter: location
            },
        },
    }
]

Binding tools and invoking the model:

  1. Use bind() to associate tools with the language model.

  2. Call the invoke() method on the bound model, by providing a natural language question as input.

# Initialize the ChatOpenAI model and bind the tools.
model = ChatOpenAI(model="gpt-4o").bind(tools=tools)
# Invoke the model to ask about the weather in San Francisco, New York, and Los Angeles.
model.invoke(
    "Can you tell me the current weather in San Francisco, New York, and Los Angeles?"
)
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_ixydz9CyFSyB0LHUATftfdXA', 'function': {'arguments': '{"location": "San Francisco, CA"}', 'name': 'get_current_weather'}, 'type': 'function'}, {'id': 'call_VFAGF4YanFQVg1lJQ9x1miR3', 'function': {'arguments': '{"location": "New York, NY"}', 'name': 'get_current_weather'}, 'type': 'function'}, {'id': 'call_RMYL8pWFlMarWkOPkigKQSug', 'function': {'arguments': '{"location": "Los Angeles, CA"}', 'name': 'get_current_weather'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 71, 'prompt_tokens': 90, 'total_tokens': 161, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_50cad350e4', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-50665b85-c055-413a-8a40-3c1070aa3c45-0', tool_calls=[{'name': 'get_current_weather', 'args': {'location': 'San Francisco, CA'}, 'id': 'call_ixydz9CyFSyB0LHUATftfdXA', 'type': 'tool_call'}, {'name': 'get_current_weather', 'args': {'location': 'New York, NY'}, 'id': 'call_VFAGF4YanFQVg1lJQ9x1miR3', 'type': 'tool_call'}, {'name': 'get_current_weather', 'args': {'location': 'Los Angeles, CA'}, 'id': 'call_RMYL8pWFlMarWkOPkigKQSug', 'type': 'tool_call'}], usage_metadata={'input_tokens': 90, 'output_tokens': 71, 'total_tokens': 161, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})

Set up the environment. You may refer to for more details.

You can check out the for more details.

Environment Setup
langchain-opentutorial
Wonyoung Lee
Chaeyoon Kim
LangChain Open Tutorial
LangChain RunnablePassthrough API reference
LangChain ChatPromptTemplate API reference
Overview
Environment Setup
Runtime Arguments Binding
Connecting OpenAI Functions
Connecting OpenAI Tools