Introduction
LangChain helps you build apps with language models easily. Direct API calls let you talk straight to the model but need more setup.
Jump into concepts and practice - no test required
LangChain helps you build apps with language models easily. Direct API calls let you talk straight to the model but need more setup.
from langchain.llms import OpenAI llm = OpenAI() response = llm('Hello!') print(response)
from langchain.llms import OpenAI llm = OpenAI() print(llm('What is the capital of France?'))
import requests headers = {'Authorization': 'Bearer YOUR_API_KEY'} data = {'model': 'gpt-4', 'messages': [{'role': 'user', 'content': 'What is the capital of France?'}], 'max_tokens': 10} response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=data) print(response.json()['choices'][0]['message']['content'])
This example shows how LangChain simplifies calling the OpenAI model. It handles the API behind the scenes and returns the answer.
from langchain.llms import OpenAI # Create a LangChain OpenAI instance llm = OpenAI(temperature=0) # Ask a question answer = llm('What is 2 plus 2?') print(f'Answer from LangChain: {answer.strip()}')
LangChain adds helpful features like chaining calls, memory, and tools.
Direct API calls give you full control but need more code and setup.
LangChain is great for building apps quickly and managing complexity.
LangChain wraps API calls to make language model use easier and more powerful.
Direct API calls require manual setup but offer full control.
Choose LangChain for app building and direct calls for simple or custom needs.
from langchain.llms import OpenAI
llm = OpenAI(model_name="gpt-3.5-turbo")
response = llm("Hello, how are you?")
print(response)
What will this code do compared to making a direct API call?import openai
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)
What is the likely cause of the error?