0
0
LangChainframework~5 mins

LangChain vs direct API calls

Choose your learning style9 modes available
Introduction

LangChain helps you build apps with language models easily. Direct API calls let you talk straight to the model but need more setup.

You want to quickly build a chatbot with memory and tools.
You need simple access to a language model without extra features.
You want to combine language models with other data sources or logic.
You prefer full control over API requests and responses.
You want to add features like chaining multiple calls or caching.
Syntax
LangChain
from langchain.llms import OpenAI
llm = OpenAI()
response = llm('Hello!')
print(response)
LangChain wraps API calls in easy-to-use classes and functions.
Direct API calls require manual HTTP requests and handling responses.
Examples
Using LangChain to ask a question simply.
LangChain
from langchain.llms import OpenAI
llm = OpenAI()
print(llm('What is the capital of France?'))
Direct API call to OpenAI's chat endpoint using requests library.
LangChain
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'])
Sample Program

This example shows how LangChain simplifies calling the OpenAI model. It handles the API behind the scenes and returns the answer.

LangChain
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()}')
OutputSuccess
Important Notes

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.

Summary

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.