10. Runtime Arguments Binding

Sometimes when calling Runnable within a Runnable sequence, you may need to pass a constant factor that is not included in the output or user input of the previous Runnable.

This time Runnable.bind() You can easily pass these factors using.

Copy

%pip install -qU langchain langchain-openai

RunnablePassthrough Using {equation_statement} Pass the variable to the prompt, StrOutputParser Using parsing the output of the model to a string runnable Create an object.

  • runnable.invoke() Call the method to pass the equation sentence "x raised to the third plus seven equals 12" and output the result.

Copy

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, then solve it.
            "Write out the following equation using algebraic symbols then solve it. "
            "Use the format\n\nEQUATION:...\nSOLUTION:...\n\n",
        ),
        (
            "human",
            "{equation_statement}",  # Receives the equation sentence entered by the user as a variable.
        ),
    ]
)
# Initialize the ChatOpenAI model and set the temperature to 0.
model = ChatOpenAI(model="gpt-4", temperature=0)

# It takes an equation sentence as input and passes it to the prompt, and parses the results generated by the model into a string.
runnable = (
    {"equation_statement": RunnablePassthrough()} | prompt | model | StrOutputParser()
)

# Enter an example equation sentence and print the result.
print(runnable.invoke("x raised to the third plus seven equals 12"))

Copy

And specific stop I want to call the model using words. model.bind() Use to call the language model, and output only the generated text to the "SOLUTION" token.

Copy

Copy

OpenAI Functions feature connection

One of the particularly useful ways to utilize binding is to connect OpenAI Functions to compatible OpenAI models.

Below is the code that defines OpenAI Functions for the schema.

Copy

bind() Using methods solver Ra binds the function call of the name to the model.

Copy

Copy

Connect OpenAI tools

Let me explain how to connect and utilize the tools (tools) provided by OpenAI.

tools objects help you use the various features of OpenAI easily.

For example, tool.run When you call a method and enter a question in natural language, it will generate an answer to that question.

Copy

  • bind() Using methods tools Bind to the model.

  • invoke() Call the method and say, "Can you tell me about the current weather in San Francisco, New York and Los Angeles?"Ra conveys the question to the model.

Copy

Copy

Last updated