logo logo

Stay ahead in the fast-paced world of artificial intelligence. Subscribe to our newsletter and follow us on social media for daily updates, deep dives, and expert analysis โ€” only at Best AI Blog.

LangChain 1.x Tutorial (2026): A-to-Z Guide With Working Code

LangChain hit 1.0 in October 2025 and everything about how you build with it changed — the old chains and AgentExecutor are legacy now, and one clean abstraction, create_agent, sits at the center. This is a complete A-to-Z tutorial for LangChain 1.x (current line: 1.3) with working code you can run today.

A. What LangChain Is in 2026

LangChain today is a small, focused agent framework: you give it a model, tools, and a prompt; it runs the agent loop (think → call tool → observe → repeat) on top of the LangGraph runtime, which brings persistence, streaming, and human-in-the-loop for free. Legacy pieces (LLMChain, AgentExecutor, ConversationBufferMemory) were moved to a separate langchain-classic package.

LangChain 1.x stack: create_agent, LangGraph runtime, models, tools, LangSmith
LangChain 1.x in one picture: create_agent on top of the LangGraph runtime

B. Install & Setup

pip install -U langchain langchain-anthropic
# optional extras used later in this tutorial:
pip install -U langchain-openai langgraph

Set your API key (Claude in this tutorial — swap freely):

export ANTHROPIC_API_KEY="sk-ant-..."

C. Chat Models

init_chat_model gives you any provider behind one interface:

from langchain.chat_models import init_chat_model

model = init_chat_model("anthropic:claude-sonnet-5", temperature=0)

reply = model.invoke("Explain RAG in one sentence.")
print(reply.content)

Change "anthropic:claude-sonnet-5" to "openai:gpt-5.2" or "google_genai:gemini-3-pro" and nothing else in this tutorial changes.

D. Structured Output

Stop parsing strings — bind a schema and get validated objects:

from pydantic import BaseModel, Field

class Movie(BaseModel):
    title: str
    year: int = Field(description="Release year")
    rating: float = Field(description="IMDb-style rating 0-10")

structured = model.with_structured_output(Movie)
m = structured.invoke("Give me one classic sci-fi movie.")
print(m.title, m.year, m.rating)   # a real Movie object

E. Tools

Any Python function becomes a tool with the @tool decorator — the docstring matters, it’s what the model reads:

from langchain.tools import tool

@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    # call a real API here
    return f"Sunny, 31°C in {city}"

@tool
def convert_currency(amount: float, from_cur: str, to_cur: str) -> str:
    """Convert an amount between currencies at today's rate."""
    rate = 83.2 if (from_cur, to_cur) == ("USD", "INR") else 1.0
    return f"{amount} {from_cur} = {amount * rate:.2f} {to_cur}"

F. Your First Agent: create_agent

This is the heart of LangChain 1.x — one call replaces everything AgentExecutor used to do:

from langchain.agents import create_agent

agent = create_agent(
    model="anthropic:claude-sonnet-5",
    tools=[get_weather, convert_currency],
    system_prompt="You are a helpful travel assistant. Use tools when needed.",
)

result = agent.invoke(
    {"messages": [{"role": "user",
       "content": "Weather in Delhi? And convert 100 USD to INR."}]}
)
print(result["messages"][-1].content)

Behind the scenes the agent runs the ReAct loop: the model decides which tool to call, LangChain executes it, feeds the result back, and repeats until the model produces a final answer.

G. Memory: Multi-Turn Conversations

Persistence comes from the LangGraph runtime — add a checkpointer and a thread_id:

from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model="anthropic:claude-sonnet-5",
    tools=[get_weather],
    checkpointer=InMemorySaver(),
)

cfg = {"configurable": {"thread_id": "user-42"}}
agent.invoke({"messages": [{"role": "user", "content": "I'm Avneesh, planning a Goa trip."}]}, cfg)
r = agent.invoke({"messages": [{"role": "user", "content": "What's my name and where am I going?"}]}, cfg)
# remembers: "Avneesh", "Goa"

💡 Production Note

Swap InMemorySaver for a Postgres/SQLite checkpointer in production — same code, durable conversations that survive restarts.

H. RAG: Give Your Agent Knowledge

The modern pattern is RAG-as-a-tool — retrieval is just another tool the agent can decide to use:

from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddings

docs = [
    "Our refund policy: full refund within 30 days of purchase.",
    "Support hours: 9am-6pm IST, Monday to Saturday.",
    "Premium plan costs $29/month and includes API access.",
]
store = InMemoryVectorStore.from_texts(docs, OpenAIEmbeddings())

@tool
def search_docs(query: str) -> str:
    """Search the company knowledge base."""
    hits = store.similarity_search(query, k=2)
    return "\n".join(d.page_content for d in hits)

support_agent = create_agent(
    model="anthropic:claude-sonnet-5",
    tools=[search_docs],
    system_prompt="Answer ONLY from the knowledge base. Say 'I don't know' otherwise.",
)

For real projects, swap InMemoryVectorStore for Qdrant, Pinecone, pgvector, or Chroma — the interface stays identical.

I. Streaming

Never make users wait for the full answer:

for chunk, metadata in agent.stream(
    {"messages": [{"role": "user", "content": "Weather in Mumbai?"}]},
    stream_mode="messages",
):
    if chunk.content:
        print(chunk.content, end="", flush=True)

stream_mode="updates" instead gives you step-by-step agent progress (which tool it’s calling and why) — great for showing “thinking” UI.

J. Production: Middleware & LangSmith

1.x added a middleware system — cross-cutting concerns without touching agent logic. For example, automatic retries with exponential backoff on failed model calls (built-in since 1.1), plus summarization middleware that compacts old messages when context grows. Add observability by setting two env vars — every agent run gets traced in LangSmith:

export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="lsv2_..."

K. Migrating from v0

v0 (legacy)v1 (current)
AgentExecutor + initialize_agentcreate_agent
LLMChainmodel + prompt directly (LCEL)
ConversationBufferMemorycheckpointer + thread_id
Old code still needed?pip install langchain-classic

L. Common Mistakes

⚠️ Avoid These

  • Vague tool docstrings — the model chooses tools by reading them. Be specific about what each tool does and when to use it.
  • Too many tools — beyond ~10-15, selection quality drops. Group related APIs into one tool with a parameter.
  • No max iterations — always bound the agent loop in production to cap costs.
  • Skipping evals — a 10-prompt golden set in CI catches regressions when you swap models.

✅ Key Takeaways

  • LangChain 1.x = create_agent + LangGraph runtime. Learn those two things and you know the framework.
  • Everything is provider-agnostic: swap Claude/GPT/Gemini with one string.
  • Memory = checkpointer, knowledge = RAG-as-a-tool, reliability = middleware.

Sources & further reading: Official LangChain docs · 1.0 announcement · GitHub · Changelog (1.3.x). Code tested against LangChain 1.3; APIs stable until 2.0 per the project’s compatibility promise.

React 19 + AI: The Complete 2026 Guide to Building AI-Powered React Apps

React is still the most popular way to build web UIs โ€” and in 2026 it has quietly become the best front-end for AI products too. With React 19.2 (the current stable line) and a mature AI tooling ecosystem, you can ship a streaming, tool-using AI app in an afternoon. This guide covers the full stack: what’s new in React 19, the architecture, real code, and the libraries worth your time.

React 19 Features That Matter for AI Apps

  • Actions & useActionState โ€” async mutations with built-in pending/error states. Perfect for “send prompt, await response” flows without hand-rolled loading flags.
  • useOptimistic โ€” show the user’s message in the chat instantly while the request is in flight. AI apps feel dramatically faster with this one hook.
  • use() + Suspense โ€” unwrap promises directly in components; pair with streaming server responses so the UI fills in as data arrives.
  • Server Components โ€” keep your API keys, RAG retrieval, and heavy AI logic on the server, and send only rendered UI to the client.

The Architecture

Architecture of a modern AI-powered React app 2026
The standard 2026 pattern: React UI → streaming API route → LLM provider

Every serious AI-React app in 2026 converges on this shape: the browser never talks to the LLM directly (keys stay server-side), the server streams tokens back over SSE, and the UI renders them incrementally.

Build It: Streaming Chat in ~40 Lines

The de-facto standard is the AI SDK (from Vercel, open-source, works with any React framework). Install:

npm install ai @ai-sdk/react @ai-sdk/anthropic

Server route (Next.js App Router โ€” app/api/chat/route.ts):

import { anthropic } from '@ai-sdk/anthropic';
import { streamText, convertToModelMessages } from 'ai';

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = streamText({
    model: anthropic('claude-sonnet-5'),
    system: 'You are a helpful assistant. Be concise.',
    messages: convertToModelMessages(messages),
  });

  return result.toUIMessageStreamResponse();
}

Client component:

'use client';
import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

export default function Chat() {
  const { messages, sendMessage, status } = useChat();
  const [input, setInput] = useState('');

  return (
    <div>
      {messages.map(m => (
        <div key={m.id} className={m.role}>
          {m.parts.map((p, i) =>
            p.type === 'text' ? <span key={i}>{p.text}</span> : null
          )}
        </div>
      ))}
      <form onSubmit={e => { e.preventDefault(); sendMessage({ text: input }); setInput(''); }}>
        <input value={input} onChange={e => setInput(e.target.value)}
               disabled={status !== 'ready'} placeholder="Ask anything..." />
      </form>
    </div>
  );
}

That’s a complete streaming chat app. Swap anthropic('claude-sonnet-5') for openai(...) or google(...) and nothing else changes โ€” that’s the point of the provider adapter layer.

Generative UI: Beyond Chat Bubbles

The 2026 pattern that separates good AI apps from chat clones is generative UI: the model calls tools, and each tool result renders as a real React component โ€” a chart, a booking card, a form. With the AI SDK you define tools server-side with a schema, then render tool parts by type on the client (a weather tool call becomes a <WeatherCard />, not a text blob). Users interact with components, not walls of text.

๐Ÿ’ก Rule of Thumb

If the model’s answer has structure โ€” lists, data, actions โ€” render it as a component. Reserve plain text for actual prose. This single decision is most of what makes an AI app feel “native”.

The 2026 Library Landscape

LibraryBest forNotes
AI SDKCore streaming + toolsThe default choice; framework-agnostic
assistant-uiReady-made chat UIComposable primitives, works with AI SDK
CopilotKitIn-app copilotsSidebar assistants that can act on app state
LangChain.js / LangGraph.jsComplex agent workflowsUse when you need multi-step orchestration
MCPStandardized toolsConnect your app’s tools to any MCP-capable model

Production Tips

  • Stream everything. Perceived latency is the #1 UX metric in AI apps; never make users stare at a spinner for 8 seconds.
  • Use useOptimistic for the user’s own messages, and show a typing indicator keyed on status.
  • Rate-limit and auth the API route โ€” your LLM bill is an attack surface.
  • Cache aggressively: system prompts and RAG chunks benefit from provider-side prompt caching (Anthropic and OpenAI both support it).
  • Evaluate before you ship: even a handful of golden-set prompts run in CI will catch regressions when you swap models.

Sources & further reading: React versions ยท AI SDK docs ยท Anthropic API docs ยท React blog.

AI Conferences and Seminars to Watch in Julyโ€“August 2026 (Online + In-Person)

The second half of 2026 is packed with AI events — from massive in-person summits to free online webinars. Whether you’re a developer, founder, or just AI-curious, here are the conferences and seminars worth your calendar for July and August 2026, both offline and online.

AI events calendar July-August 2026
Quick visual calendar — details for each event below

Ai4 2026 — Las Vegas, USA (August 4–6) · In-Person

๐Ÿ“ Venue & Registration

  • Venue: Venetian Convention & Expo Center, 201 Sands Ave, Las Vegas, NV 89169, USA
  • Dates: August 4–6, 2026
  • Register: ai4.io/vegas

The biggest industry AI event of the summer. Ai4 brings together 1,000+ speakers and around 12,000 attendees from 90+ countries, covering applied AI across finance, healthcare, retail, government, and more. Tickets range from $1,395 to $3,195, so it’s aimed at professionals — but the networking density is hard to match anywhere else.

🎯 Best for

Business leaders, enterprise AI teams, and anyone hunting for partnerships or customers.

Autonomous: The Future of Robotics & Physical AI — California, USA (July 16) · In-Person

๐Ÿ“ Venue & Registration

  • Venue: The Midway, 900 Marin St, San Francisco, CA 94124, USA (Dogpatch, near Chase Center)
  • Dates: July 16, 2026 · doors 8:00 AM, program 9:00 AM–5:00 PM
  • Register: autonomousfuture.co (capped at 500 attendees)

Physical AI is the theme of 2026 — robots, embodied agents, and AI that acts in the real world. This single-day California event focuses exactly there. If you follow the humanoid robotics wave, this is a compact way to hear where the field is heading.

🎯 Best for

Robotics engineers, hardware founders, investors tracking physical AI.

AI for Good (ITU) — Online, Year-Round Webinars · Free

๐Ÿ“ Venue & Registration

The United Nations’ ITU runs a continuously updated AI events calendar with free online sessions nearly every week — recent topics include the human–machine relationship in the age of AI. This is the easiest zero-cost way to stay plugged into serious AI policy and applied-AI discussions from anywhere in the world.

We covered the flagship summit earlier this year in our post on AI for Good Summit 2025: Turning Tech Into Global Impact.

🎯 Best for

Anyone, anywhere — it’s free and online.

Academic & Research Conferences (August)

๐Ÿ“ Venue & Registration

  • Boston, USA — Next-Generation AI Technologies, August 14, 2026 · venue shared on registration · listing & registration
  • New York, USA — CS, Machine Learning & Big Data, August 17, 2026 · venue shared on registration · listing & registration

Per conference listing aggregators, August is the densest month for academic AI gatherings in the US, including an International Conference on Next-Generation AI Technologies in Boston (August 14) and an International Conference on Computer Science, Machine Learning and Big Data in New York (August 17). Note that ICML 2026 — the year’s premier ML research conference — already wrapped up in Seoul (July 6–11), so paper-watchers should look toward the NeurIPS cycle next.

🎯 Best for

Researchers, students, and anyone building an academic profile.

How to Choose: Online vs Offline

  • Go in-person if your goal is hiring, fundraising, or sales — hallway conversations are the real product. Big cloud and AI vendors also run regional summits; we saw this pattern at AWS Summit NYC 2025, where Anthropic showcased Claude.
  • Go online if your goal is learning — webinars and virtual tracks deliver 80% of the content for 0% of the travel cost.
  • Watch the recordings — most large conferences publish keynotes on YouTube within weeks. Subscribe once, learn free forever.

📅 Quick Calendar Recap

  • July 16: Autonomous: Robotics & Physical AI — California (offline)
  • Weekly: AI for Good webinars — online, free
  • Aug 4–6: Ai4 2026 — Las Vegas (offline, flagship)
  • Aug 14: Next-Gen AI Technologies — Boston (offline)
  • Aug 17: CS, ML & Big Data — New York (offline)

Dates and details are per organizer sites and listings (Unite.AI · DataCamp · AllConferenceAlert) as of July 13, 2026 — always confirm on the official event page before booking travel.

Verifiers v1 Explained: Prime Intellect’s New Architecture for Agentic RL Training and Evals

Prime Intellect has released verifiers v1 (shipped as verifiers 0.2.0 under the new verifiers.v1 namespace) — a ground-up rewrite of its environment stack for agentic reinforcement learning and evaluations. If you train or benchmark AI agents, this release changes how you’ll structure that work. Here’s a technical breakdown.

Why a Rewrite Was Needed

Modern evaluations don’t just send a prompt and score a reply anymore. Today’s coding agents use tools, compact their own context, and spawn subagents. The old verifiers (v0) bundled an environment’s data, agent logic, and infrastructure into one package — fine for linear chat rollouts, but a poor fit for branching, long-horizon agentic workloads.

The Three-Piece Architecture

Verifiers v1 architecture: taskset, harness, runtime, interception server
v1 decouples tasksets, harnesses and runtimes; the interception server proxies every LLM call
  • Taskset — defines the work: the data, the tools available, and the scoring (reward) logic.
  • Harness — the thing that solves the task and produces a rollout. This can be a ReAct loop, a CLI agent like Codex or Terminus 2, or your own custom agent.
  • Runtime — where the rollout executes: locally or inside a sandbox, with lifecycle managed by the framework.

💡 The Big Idea

Because the pieces are decoupled, any taskset can run under any compatible harness. Write your benchmark once, then test it against completely different agent architectures without rewriting reward logic.

The Interception Server: The Clever Part

The central component is a verifiers-managed interception server that sits between the agent’s runtime and the inference server. It proxies every request and response, and while doing so it records the full trace, sets sampling parameters, and can even rewrite tool responses — a practical mitigation against reward hacking during training.

Each server multiplexes a fixed number of rollouts (32 by default), and a pool scales elastically with concurrency. During evaluation, an EvalClient acts as a blind HTTP proxy; during training, a TrainClient wraps renderers for faithful token-in RL training. Since harnesses speak different API dialects, v1 ships adapters for three: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages — all normalized into canonical types so your scoring stays agent-independent.

v0 vs v1: What Actually Changed

Aspectverifiers v0verifiers v1
Environment modelData, logic, infra bundledSplit: taskset / harness / runtime
Trace growthQuadratic in turnsLinear (unique nodes)
Non-linear rolloutsAssumed linearNative compaction & subagents
Harness couplingTightly coupledAny compatible harness
Training dataRecomputed for prime-rlConsumed directly from trace

A Minimal Taskset in Code

import verifiers.v1 as vf

class AdditionData(vf.TaskData):
    answer: int

class AdditionTask(vf.Task[AdditionData]):
    @vf.reward
    async def exact_match(self, trace: vf.Trace) -> float:
        return float(trace.last_reply == str(self.data.answer))

class AdditionTaskset(vf.Taskset[AdditionTask, vf.TasksetConfig]):
    def load(self) -> list[AdditionTask]:
        return [
            AdditionTask(
                AdditionData(idx=i, prompt=f"What is {i} + {i}?", answer=2 * i),
                self.config.task,
            )
            for i in range(100)
        ]

The taskset defines data and scoring with zero knowledge of which agent will attempt it. You then pick a harness and model via a TOML config and launch from the CLI.

Real-World Usage Already

  • Terminal-Bench 2 was ported into v1 with a single small class, and matched Harbor’s performance on the same tasks in internal testing. Harbor is the first fully supported third-party format; NeMo Gym and OpenEnv have alpha support.
  • On the training side, the same environments plug directly into prime-rl. In one ablation, GLM-4.5-Air was trained on ScaleSWE across six H200 nodes for two days and evaluated on SWE-Bench-Verified, demonstrating stable agentic RL training.

Why This Matters

Agentic RL infrastructure has been fragmenting fast — every lab has its own environment format, and benchmarks don’t transfer. A taskset/harness/runtime split with dialect adapters is a genuine step toward write-once, evaluate-anywhere. If you’re building agent benchmarks or training pipelines in 2026, verifiers v1 is worth a serious look.

Sources & further reading: Prime Intellect announcement · MarkTechPost coverage · verifiers on GitHub.

Apple vs OpenAI: Inside the Trade Secret Lawsuit That Just Shook the AI Hardware Race

On July 10, 2026, Apple filed a lawsuit against OpenAI in the U.S. District Court for the Northern District of California, accusing the ChatGPT maker of trade secret theft and breach of contract. This isn’t a routine legal spat between tech giants — it lands right in the middle of OpenAI’s push to build its first hardware device, a product that could compete directly with the iPhone.

Key Points at a Glance

  • Who: Apple vs OpenAI, with two former Apple employees named — Chief Hardware Officer Tang Tan and engineer Chang Liu.
  • What: Allegations of stolen confidential documents, misused project code names, and recruiting tactics designed to extract Apple’s secrets.
  • Why it matters: OpenAI is rumored to be building an AI-first phone where agents replace apps — potentially the biggest threat to Apple’s core business in years.
  • What Apple wants: A court order blocking OpenAI from using its trade secrets, return of confidential materials, and evidence preservation.

How the Conflict Escalated

Timeline: how the Apple vs OpenAI conflict escalated
Timeline of key events leading to the July 2026 lawsuit

The Allegations Against Tang Tan

Tang Tan spent 24 years at Apple, most recently as VP of product design for the iPhone and Apple Watch, before becoming OpenAI’s Chief Hardware Officer. According to the complaint, Tan used Apple’s confidential project code names during recruiting conversations, asked job candidates to bring Apple hardware components to interviews, and even coached departing Apple employees on how to slip past the company’s security procedures.

Apple alleges this behavior wasn’t rogue conduct by one executive — the filing claims it was directed by OpenAI’s senior leadership as part of a deliberate strategy to extract confidential information about component selection, vendor processes, and unannounced products.

The Laptop That Never Came Back

The second named employee, Chang Liu, worked eight years at Apple as a senior systems electrical engineer. The lawsuit claims he never returned his Apple-issued laptop after leaving for OpenAI in 2026, and used it to download confidential technical documents — engineering presentations, technical specifications, and proprietary project data covering unannounced products.

Apple also alleges Liu shared internal information with other Apple employees who were applying to OpenAI, advising at least one on what to study before the interview. One striking detail from the filing: OpenAI allegedly used a proprietary Apple metal finishing technique after misleading a manufacturing partner into believing it had Apple’s permission.

The Real Story: The AI Hardware War

The timing tells you everything. OpenAI acquired Jony Ive’s device startup io in 2025 for $6.5 billion, putting Apple’s most famous former designer in charge of its hardware ambitions. Industry analyst Ming-Chi Kuo has suggested OpenAI’s first device could be a smartphone built around AI agents instead of apps.

If that device ships, it won’t just be another gadget — it would challenge the app-centric model that powers Apple’s services revenue. Apple says it sent OpenAI a warning letter in February 2026 and got no response. Filing suit gives Apple something it couldn’t get otherwise: legal discovery, meaning access to OpenAI’s internal communications.

What Happens Next

Expect OpenAI to respond publicly within days and file a motion to dismiss within weeks. Trade secret cases of this scale often take 18–24 months to resolve, and many end in settlement. But even before any verdict, the discovery process could expose details about OpenAI’s hardware roadmap that it would much rather keep private.

⚠️ Why This Matters for the Industry

This case is a warning shot about the AI talent war: hiring aggressively from a competitor is legal — but what those hires bring with them can turn into a billion-dollar liability. Every AI lab recruiting from Big Tech will be reviewing its onboarding policies this week.

Sources & further reading: TechCrunch report · Full court filing (DocumentCloud) · OpenAI phone rumors. All claims described above are allegations from Apple’s complaint; OpenAI has not yet responded in court.