LangChain

How to Create a Generic OpenAI Functions Chain Using LangChain?

OpenAI function is an American research company that is used to build Artificial Intelligence models to integrate them into the real world. LangChain allows the user to create OpenAI functions while building LLMs using its modules and Python IDE like Google Collaboratory. Generic OpenAI functions can also be used to build chatbots that interact with humans in natural language by understanding and generating text.

This guide will explain the process of implementing OpenAI functions using LangChain.

How to Create Generic OpenAI Functions Chain Using LangChain?

To create generic OpenAI functions using LangChain, simply follow this easy guide containing multiple generic OpenAI functions:

Install Prerequisites

Install the LangChain framework to start creating the OpenAI functions:

pip install langchain

 

OpenAI modules are required for this example as it allows the use of OpenAI functions:

pip install openai

 

After installing the OpenAI module, simply set up the API key for the OpenAI using the code mentioned below:

import os
import getpass

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

 

Import Libraries

After integrating the OpenAI API key with the model, simply import necessary libraries like create_openai_fn_chain and create_structured_output_chain from LangChain:

from typing import Optional

from langchain.chains.openai_functions import (
    create_openai_fn_chain,
    create_structured_output_chain,
)
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.schema import HumanMessage, SystemMessage

 

Create a base model to be used for creating the generic OpenAI functions for a person with its attributes:

from pydantic import BaseModel, Field


class Person(BaseModel):
    """Identifying information about a person."""

    name: str = Field(..., description="The person's name")
#describing the details of the person to get from the prompt
    age: int = Field(..., description="The person's age")
    fav_food: Optional[str]=Field(None, description="The person's favorite food")

 

Method 1: Use Generic OpenAI Function Via Pydantic Class

Another type of OpenAI function is a generic function that can be configured using pydantic classes as mentioned in the following code:
from pydantic import BaseModel, Field

class RecordPerson(BaseModel):
    """Record some identifying information about a pe."""
#class to identify the man from the prompt
    name: str = Field(..., description="Name of the Person")
    age: int = Field(..., description="Age of person from prompt")
    fav_food: Optional[str] = Field(None, description="Favorite food of the person")

#class to identify the dog from the prompt
class RecordDog(BaseModel):
    """Information to gather related to dog from the prompt."""
    name: str = Field(..., description="Name of the dog")
    color: str = Field(..., description="Color of the dog")
    fav_food: Optional[str] = Field(None, description="Favorite food of dog")

 

The above code uses the BaseModel class to create classes for person and dog containing information regarding both entities:

After creating the classes for the generic OpenAI function, simply create the template for the prompt for the chatbot to answer the prompt accordingly:

llm = ChatOpenAI(temperature=0)
prompt_msgs = [
    SystemMessage(content="Brilliant algorithm for creating bots"),
    HumanMessage(
        content="Get function to call using the attributes described in the prompt using the following input:"
    ),
    HumanMessagePromptTemplate.from_template("{input}"),
    HumanMessage(content="Use accurate format"),
]
prompt = ChatPromptTemplate(messages=prompt_msgs)
#Prompt Template to get answers in the this format and create chains to record the answers for future references
chain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt, verbose=True)
chain.run("Mark is a tall brown guy who loves pasta")

 

Running the above prompt generates the required data like name, age, and favorite food from the prompt provided previously:

Method 2: Use Generic OpenAI Function Via Python Function

OpenAI function can also be used with the help of a simple Python function as displayed in the following code block:

class OptionalFavFood(BaseModel):
    """Either a food or null."""
#Python function to call the OpenAI function and get the answers in correct format
    food: Optional[str] = Field(
        None,
        description="If the name of the food is null then it should be unknown",
    )


def record_person(name: str, age: int, fav_food: OptionalFavFood) -> str:
    """Arguments to identify the man using its basic features.

    Args:
        name: Name of the person.
        age: Age of the person.
        fav_food: favorite food is Optional
    "
""
    return f"Recording person {name} of age {age} with favorite food {fav_food.food}!"


chain = create_openai_fn_chain([record_person], llm, prompt, verbose=True)
chain.run(
    "Smith is 15 years old, he loves to eat Pizza."
)

 

The above code simply defines a function in Python language named record_person with the details about the person like name, age, and favorite food as its arguments. It runs chains using the OpenAI function with LLM and prompt as its parameter to run the prompt about a person:

Output

The following screenshot displays the data extracted from the prompt after completing the chain:

That is all about creating a generic OpenAI functions chain.

Conclusion

To create a generic OpenAI function, simply install LangChain and OpenAI modules and set up the OpenAI API key to use its resources. Open AI generic functions are built to create chatbots that provide answers to the queries for the users after understanding the prompts. This blog demonstrated the process of creating generic function chains using LangChain.

About the author

Talha Mahmood

As a technical author, I am eager to learn about writing and technology. I have a degree in computer science which gives me a deep understanding of technical concepts and the ability to communicate them to a variety of audiences effectively.