Square CloudSquare Cloud

LangChain, LlamaIndex, AI SDK or the provider SDK: which to use

For chatbots and simple flows, use the provider's SDK; for TypeScript apps with streaming chat, the AI SDK. For RAG over documents, LlamaIndex; for agents with many tools and integrations, LangChain.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand what LangChain, LlamaIndex, the AI SDK and the provider SDK solve
  • Compare the same tool calling flow written with each option
  • Know when the abstraction helps and when it gets in the way
On this page

Every call to a language model ends up in the same place: an HTTP request to the provider's API, with messages, tools and settings. LangChain, LlamaIndex, the AI SDK and the provider's official SDK differ in how much code they write for you and how much they hide.

To compare them for real, this guide writes the same flow with each option: a store support agent that checks an order's status through a tool (tool calling) before answering. LlamaIndex shows up with the flow where it is strongest, searching documents.

What does each option solve?#

Option Languages Focus Shines when
Provider SDK (openai, anthropic and similar) Python, JavaScript and more Typed client for one provider's API Simple flows and new provider features
AI SDK TypeScript One interface for many providers, plus UI building blocks Next.js, React, Vue or Svelte apps with streaming chat
LangChain Python and JavaScript/TypeScript Agents, middleware and integrations Agents with several tools, memory and human approval
LlamaIndex Python Data: load, index and retrieve RAG over PDFs, pages and databases

The provider SDK is the thinnest layer: every parameter is the API's own, with no translation. The AI SDK, open source and maintained by Vercel, describes itself as a TypeScript toolkit: AI SDK Core standardizes text generation, tool calling and agents across providers, and AI SDK UI adds hooks for chat interfaces. LangChain builds agents with create_agent, on top of LangGraph, which adds persistence, durable execution and pauses for human approval. LlamaIndex describes itself as an open source Python toolkit for RAG and agents, with data connectors, indexes and query engines; its TypeScript version has been deprecated, and the project's README says the company's primary focus has shifted to LlamaParse, its document platform. For the basics of RAG, see what RAG is.

What does the flow look like with the provider SDK?#

With OpenAI's Python SDK (pip install openai), using the Responses API, which OpenAI recommends for new projects. You write the loop: call the model, run the tools it asked for, send back the results and repeat until a final answer comes back.

python
import json
import os

from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from the environment
MODEL = os.environ["OPENAI_MODEL"]

TOOLS = [
    {
        "type": "function",
        "name": "order_status",
        "description": "Looks up the status of a store order by its number.",
        "strict": True,
        "parameters": {
            "type": "object",
            "properties": {"number": {"type": "string", "description": "Order number"}},
            "required": ["number"],
            "additionalProperties": False,
        },
    }
]


def order_status(number: str) -> str:
    # Your database lookup goes here
    return json.dumps({"number": number, "status": "shipped", "eta": "2 business days"})


def answer(question: str, max_steps: int = 5) -> str:
    items = [{"role": "user", "content": question}]
    for _ in range(max_steps):
        response = client.responses.create(
            model=MODEL,
            instructions="You are the store's support agent. Answer in at most 3 sentences.",
            tools=TOOLS,
            input=items,
        )
        items += response.output  # keep the calls the model asked for
        calls = [item for item in response.output if item.type == "function_call"]
        if not calls:
            return response.output_text  # no pending tool: final answer
        for call in calls:
            args = json.loads(call.arguments)
            items.append(
                {
                    "type": "function_call_output",
                    "call_id": call.call_id,
                    "output": order_status(**args),
                }
            )
    raise RuntimeError("the model did not finish within the step limit")


print(answer("Where is my order 1234?"))

That is about 40 lines, and all of them are in plain sight: what goes into the request, how many turns the loop takes, what happens if the model never stops. max_steps is your guard against an endless loop. The model ID lives in OPENAI_MODEL; copy the current value from the provider's models page.

And with the AI SDK?#

The AI SDK writes the loop for you. The tool is declared with a Zod schema, and stopWhen sets how many steps the loop may take (npm install ai @ai-sdk/openai zod, in a .mjs file):

js
import { openai } from "@ai-sdk/openai";
import { generateText, isStepCount, tool } from "ai";
import { z } from "zod";

const orderStatus = tool({
  description: "Looks up the status of a store order by its number.",
  inputSchema: z.object({
    number: z.string().describe("Order number"),
  }),
  // Your database lookup goes here
  execute: async ({ number }) => ({ number, status: "shipped", eta: "2 business days" }),
});

const { text } = await generateText({
  model: openai(process.env.OPENAI_MODEL),
  instructions: "You are the store's support agent. Answer in at most 3 sentences.",
  tools: { order_status: orderStatus },
  stopWhen: isStepCount(5), // up to 5 steps (tool call + answer)
  prompt: "Where is my order 1234?",
});

console.log(text);

Switching providers means changing the model line and the package. The same code with streamText instead of generateText returns the text as it is generated, and the AI SDK UI hooks render it in the browser; the mechanism underneath is in how to stream AI responses. The example follows AI SDK 7, which is ESM-only and needs a recent Node.js (the minimum version is in the migration guide). It renamed system to instructions (the old name is still accepted, as deprecated) and stepCountIs to isStepCount, so tutorials written for version 6 use the old names.

And with LangChain?#

In LangChain, create_agent takes the model, the tools and the system prompt, and builds the loop (pip install langchain langchain-openai). The tool is a plain function: the @tool decorator uses the docstring as the description and the type hints as the schema.

python
import json
import os

from langchain.agents import create_agent
from langchain.tools import tool


@tool
def order_status(number: str) -> str:
    """Looks up the status of a store order by its number."""
    return json.dumps({"number": number, "status": "shipped", "eta": "2 business days"})


agent = create_agent(
    model=f"openai:{os.environ['OPENAI_MODEL']}",
    tools=[order_status],
    system_prompt="You are the store's support agent. Answer in at most 3 sentences.",
)

result = agent.invoke({"messages": [{"role": "user", "content": "Where is my order 1234?"}]})
print(result["messages"][-1].text)

The result is the whole message list (question, tool call, tool result, answer), which helps when debugging. The openai: prefix picks the provider; anthropic: or google_genai: switch providers with the matching integration package. The payoff comes as the agent grows: middleware for guardrails and retries, a checkpointer to keep the conversation, and LangSmith to trace every step.

Where does LlamaIndex fit?#

LlamaIndex's strength is not the tool loop but the path to your data. RAG over a docs folder takes a few lines (pip install llama-index):

python
import os

from llama_index.core import (
    Settings,
    SimpleDirectoryReader,
    StorageContext,
    VectorStoreIndex,
    load_index_from_storage,
)
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.llms.openai import OpenAI

Settings.llm = OpenAI(model=os.environ["OPENAI_MODEL"])
Settings.embed_model = OpenAIEmbedding(model=os.environ["OPENAI_EMBED_MODEL"])

INDEX_DIR = "index"

if os.path.isdir(INDEX_DIR):
    # Reuse the saved index: no new embeddings
    storage = StorageContext.from_defaults(persist_dir=INDEX_DIR)
    index = load_index_from_storage(storage)
else:
    documents = SimpleDirectoryReader("docs").load_data()
    index = VectorStoreIndex.from_documents(documents)
    index.storage_context.persist(persist_dir=INDEX_DIR)

query_engine = index.as_query_engine(similarity_top_k=3)
print(query_engine.query("How many days do I have to return a product?"))

The code reads the files, generates the embeddings, saves the index to disk and answers with the three excerpts closest to the question. Saving the index avoids paying to embed every document on each start. Without Settings, LlamaIndex falls back to default OpenAI models, so declare both. And its OpenAI class checks the model name against an internal list: a model released after your installed version fails with the error below until you update llama-index-llms-openai.

ValueError: Unknown model 'model-name'. Please provide a valid OpenAI model name in: ...

To keep the vectors in a database instead of files, see what a vector database is and, for a step-by-step guide on PostgreSQL, how to build a RAG chatbot with pgvector.

When does the abstraction help and when does it get in the way?#

It helps when:

  • You switch or compare providers. The AI SDK and LangChain put them all behind the same interface.
  • The loop gets complex: many tools, memory across conversations, human approval before an action, retries.
  • The interface is a streaming chat in a React or Next.js app.
  • Data comes from many sources (PDFs, pages, databases) and has to become an index.

It gets in the way when:

  • The flow is a single call. The framework becomes more code than the problem.
  • Something goes wrong. Between your code and the request there are layers that build prompts and payloads, and you need them open to understand the error.
  • The API changes between versions. A major upgrade takes work: AI SDK 7, for example, now rejects system messages inside messages by default.
  • The provider ships a feature. It lands in the official SDK first; the framework follows later.

A rule of thumb: start with the provider SDK and adopt a framework when you feel a specific pain it solves. The options also combine: LlamaIndex can handle retrieval only, and the provider SDK the answer. If your question is how to expose tools to external AI clients, compare MCP vs function calling.

Which one should you pick for each scenario?#

Scenario Recommendation
Chatbot on one provider, in Python or Node.js Provider SDK
Next.js or React app with streaming chat AI SDK
Comparing or switching between providers AI SDK (TypeScript) or LangChain (Python and TypeScript)
Answering from PDFs, manuals and pages LlamaIndex
Agent with many tools, memory and human approval LangChain with create_agent, or LangGraph directly
A new provider feature on launch day Provider SDK
First AI project Provider SDK, to see what happens underneath

No option wins everywhere. Pick by the shape of the problem and your team's language. If the agent will run for minutes, the next step is deciding where to host an AI agent.

How to do this on Square Cloud#

Any of the four options goes in as an ordinary project dependency, in package.json or requirements.txt. Square Cloud's runtimes include Node.js, TypeScript (no build step) and Python, and on start the platform installs dependencies: npm install when there is no node_modules, or pip install -r requirements.txt. Set OPENAI_API_KEY and OPENAI_MODEL (plus OPENAI_EMBED_MODEL for the LlamaIndex example) in the app's environment variables; changes apply on the next restart, with no rebuild. The API listens on 0.0.0.0 on the port in the PORT variable, uses at least 512 MB of the plan's RAM pool, and streamed SSE responses pass through the proxy unbuffered.

The index LlamaIndex saves to disk survives restarts and deploys, because the disk is persistent and a new deploy overwrites only the files in the ZIP. For vectors in a database, PostgreSQL hosting, from the Standard plan, comes with the pgvector extension.

If you'd rather not keep an account with a model provider, the AI Gateway (from Standard, R$44.99 per month) serves cubic, the platform's AI model, through an OpenAI-compatible API. With the OpenAI SDK:

python
import os

from openai import OpenAI

client = OpenAI(
    base_url="https://api.squarecloud.app/v2/ai",
    api_key=os.environ["SQUARECLOUD_API_KEY"],  # account key with the ai:chat scope
)

response = client.chat.completions.create(
    model="cubic",
    messages=[
        {"role": "system", "content": "You are the store's support agent. Answer in at most 3 sentences."},
        {"role": "user", "content": "Do you deliver on Saturdays?"},
    ],
)
print(response.choices[0].message.content)

The gateway supports function calling in the OpenAI format (up to 32 tools) and streaming, keeps no state (send the history with every request) and has no embeddings, so a RAG index needs another provider for those. See runtimes and plans on API hosting.

AI

Host AI apps in always-on containers

API hosting

FAQs

Do I need LangChain to use AI in my project?

No. A chatbot or a flow with a few tools fits in the provider's official SDK in a few dozen lines. LangChain starts to pay off when you need to switch providers, build agents with memory and human approval, or use its ready-made integrations.

What is the difference between LangChain and LlamaIndex?

LangChain is centered on agents: the tool calling loop, middleware and provider integrations. LlamaIndex is centered on data: loading documents, indexing them, retrieving the right excerpts and answering from them, the pattern called RAG.

Does the AI SDK only work on Vercel?

No. The AI SDK is a TypeScript library that runs on Node.js and in frameworks such as Next.js, React, Vue and Svelte, on any host. Model providers come as separate packages, such as @ai-sdk/openai.

Does a framework make the app slower?

Rarely in a way you would notice: response time is dominated by the model. A framework's cost shows up elsewhere: more dependencies, more layers to debug and API changes between versions.

Next articleBest way to host an AI agentAn AI agent runs a tool calling loop that can last minutes. Compare serverless, an always-on container, a VPS and a queue with a worker, and see which to use.