0
0
LangChainframework~5 mins

Connecting to OpenAI models in LangChain

Choose your learning style9 modes available
Introduction

Connecting to OpenAI models lets your program talk to smart AI that can understand and create text. This helps you build apps that can chat, answer questions, or write stories.

You want your app to answer questions like a helpful assistant.
You need to generate creative text like stories or emails automatically.
You want to analyze or summarize large amounts of text quickly.
You want to build chatbots that understand natural language.
You want to add AI features without building the AI yourself.
Syntax
LangChain
from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI(model_name="gpt-4", temperature=0.7)
response = chat.predict_messages([{"role": "user", "content": "Hello, how are you?"}])
print(response.content)

Use ChatOpenAI to create a connection to an OpenAI chat model.

The model_name sets which AI model you want to use, like "gpt-4" or "gpt-3.5-turbo".

Examples
This example connects to the GPT-3.5 Turbo model with no randomness (temperature=0) and asks a simple question.
LangChain
from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
response = chat.predict_messages([{"role": "user", "content": "What is the capital of France?"}])
print(response.content)
This example uses GPT-4 with more creativity (temperature=0.9) to generate a poem.
LangChain
from langchain.chat_models import ChatOpenAI

chat = ChatOpenAI(model_name="gpt-4", temperature=0.9)
response = chat.predict_messages([{"role": "user", "content": "Write a short poem about the sun."}])
print(response.content)
Sample Program

This program connects to the GPT-4 model with medium creativity. It asks for a fun fact about space and prints the AI's answer.

LangChain
from langchain.chat_models import ChatOpenAI

# Create a chat model connection to GPT-4
chat = ChatOpenAI(model_name="gpt-4", temperature=0.5)

# Ask the model a question
response = chat.predict_messages([{"role": "user", "content": "Tell me a fun fact about space."}])

# Print the AI's answer
print(response.content)
OutputSuccess
Important Notes

Always keep your OpenAI API key safe and do not share it publicly.

Temperature controls creativity: 0 means very focused answers, higher values like 0.9 make answers more creative.

Check your usage limits on OpenAI to avoid unexpected charges.

Summary

Connecting to OpenAI models with Langchain lets you use powerful AI in your apps easily.

You create a ChatOpenAI object with the model name and settings.

Then you send text prompts and get AI-generated responses to use in your program.