# LangChain SDK Integration

URL: https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/integrations/langchain-sdk

Interfaze has a native LangChain integration. `ChatInterfaze` is a standard LangChain chat model, so it drops into chains, agents, and LangGraph like any other, and it surfaces the Interfaze-specific fields a plain chat model would drop: `precontext`, `reasoning`, and `vcache`.

- [TypeScript / JavaScript SDK](https://www.npmjs.com/package/@interfaze-ai/langchain)
- [Python SDK](https://pypi.org/project/interfaze-langchain/)

## Installation

**npm / yarn · typescript**

```typescript
npm install @interfaze-ai/langchain
# or
yarn add @interfaze-ai/langchain
```

**pip · python**

```python
pip install interfaze-langchain
```

In TypeScript, `@langchain/core`, `@langchain/openai`, and `interfaze` are peer dependencies. The structured output and tool examples below also use `zod`.

## Official Documentation

- [LangChain JS Documentation](https://js.langchain.com/docs/)
- [LangChain Python Documentation](https://python.langchain.com/docs/)

## Basic Setup

The model reads `INTERFAZE_API_KEY` from the environment, so you can construct it with no arguments. Get your API key from the [dashboard](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/dashboard).

**LangChain SDK · typescript**

```typescript
import { ChatInterfaze } from "@interfaze-ai/langchain";

const interfaze = new ChatInterfaze({ apiKey: process.env.INTERFAZE_API_KEY });
```

**LangChain SDK · python**

```python
import os
from interfaze_langchain import ChatInterfaze

interfaze = ChatInterfaze(api_key=os.environ["INTERFAZE_API_KEY"])
```

- No base URL or model name to configure — both are built in.
- The usual LangChain options (`temperature`, `maxTokens`, `timeout`, `reasoningEffort`) are forwarded. The request timeout defaults to 900 seconds, since a single call may run OCR, a web search, or a transcription inline.

## Examples

### Text Generation

**LangChain SDK · typescript**

```typescript
import { HumanMessage, SystemMessage } from "@langchain/core/messages";

const response = await interfaze.invoke([
  new SystemMessage("You are a helpful assistant."),
  new HumanMessage("Write a short story about a robot learning to paint"),
]);

console.log(response.content);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage, SystemMessage

response = interfaze.invoke([
    SystemMessage(content="You are a helpful assistant."),
    HumanMessage(content="Write a short story about a robot learning to paint"),
])

print(response.content)
```

### Structured Output

Learn more about [structured output](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/structured-output).

**LangChain SDK · typescript**

```typescript
import { z } from "zod";

const weatherSchema = z.object({
  city: z.string().describe("The name of the city"),
  temperature_celsius: z.number().describe("Current temperature in Celsius"),
  condition: z.string().describe("Weather condition, e.g. sunny, rainy, cloudy"),
});

const structuredModel = interfaze.withStructuredOutput(weatherSchema);

const result = await structuredModel.invoke("What is the current weather in Tokyo?");

console.log(result);
```

**LangChain SDK · python**

```python
from pydantic import BaseModel, Field

class WeatherSchema(BaseModel):
    city: str = Field(..., description="The name of the city")
    temperature_celsius: float = Field(..., description="Current temperature in Celsius")
    condition: str = Field(..., description="Weather condition, e.g. sunny, rainy, cloudy")

structured_model = interfaze.with_structured_output(WeatherSchema)

result = structured_model.invoke("What is the current weather in Tokyo?")

print(result)
```

To keep the raw metadata behind the answer, ask for the underlying message too and read `precontext` off it.

**LangChain SDK · typescript**

```typescript
import { AIMessage, HumanMessage } from "@langchain/core/messages";
import { z } from "zod";

const IDSchema = z.object({
  first_name: z.string().describe("First name on the ID"),
  last_name: z.string().describe("Last name on the ID"),
  dob: z.string().describe("Date of birth on the ID"),
  driver_licence_number: z.string().describe("Driver licence number on the ID"),
});

const response = await interfaze.withStructuredOutput(IDSchema, { includeRaw: true }).invoke([
  new HumanMessage({
    content: [
      { type: "text", text: "Extract the details from this ID" },
      {
        type: "image_url",
        image_url: {
          url: "https://r2public.jigsawstack.com/interfaze/examples/id.jpg",
        },
      },
    ],
  }),
]);

console.log(response.parsed);
console.log("OCR Results:", (response.raw as AIMessage).response_metadata.precontext?.[0]?.result);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
from pydantic import BaseModel, Field

class IDSchema(BaseModel):
    first_name: str = Field(..., description="First name on the ID")
    last_name: str = Field(..., description="Last name on the ID")
    dob: str = Field(..., description="Date of birth on the ID")
    driver_licence_number: str = Field(..., description="Driver licence number on the ID")

response = interfaze.with_structured_output(IDSchema, include_raw=True).invoke([
    HumanMessage(
        content=[
            {"type": "text", "text": "Extract the details from this ID"},
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://r2public.jigsawstack.com/interfaze/examples/id.jpg"
                },
            },
        ]
    )
])

print(response["parsed"])
print("OCR Results:", response["raw"].response_metadata.get("precontext"))
```

### Image / File Input

Images, audio, PDFs, Word documents, and CSV all use standard LangChain content parts, by URL or base64. Learn more about [handling files](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/handling-files).

**LangChain SDK · typescript**

```typescript
import { HumanMessage } from "@langchain/core/messages";

const response = await interfaze.invoke([
  new HumanMessage({
    content: [
      { type: "text", text: "What is in this image?" },
      {
        type: "image_url",
        image_url: {
          url: "https://r2public.jigsawstack.com/interfaze/examples/construction.png",
        },
      },
    ],
  }),
]);

console.log(response.content);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage

response = interfaze.invoke([
    HumanMessage(content=[
        {"type": "text", "text": "What is in this image?"},
        {
            "type": "image_url",
            "image_url": {
                "url": "https://r2public.jigsawstack.com/interfaze/examples/construction.png",
            },
        },
    ])
])

print(response.content)
```

Video uses an Interfaze-specific `video` block, which accepts a `url` or `base64`:

**LangChain SDK · typescript**

```typescript
import { HumanMessage } from "@langchain/core/messages";

const response = await interfaze.invoke([
  new HumanMessage({
    content: [
      { type: "text", text: "What happens in this clip?" },
      { type: "video", url: "https://r2public.jigsawstack.com/interfaze/examples/code_gen_gif.mp4" },
    ] as never,
  }),
]);

console.log(response.content);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage

response = interfaze.invoke([
    HumanMessage(content=[
        {"type": "text", "text": "What happens in this clip?"},
        {"type": "video", "url": "https://r2public.jigsawstack.com/interfaze/examples/code_gen_gif.mp4"},
    ])
])

print(response.content)
```

### Streaming

Interfaze streams reasoning and precontext as inline side-channels, and `ChatInterfaze` strips them out of the streamed content for you. Learn more about [streaming](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/streaming).

**LangChain SDK · typescript**

```typescript
import { HumanMessage } from "@langchain/core/messages";

const stream = await interfaze.stream([new HumanMessage("Write a short story about a robot learning to paint")]);

for await (const chunk of stream) {
  process.stdout.write(chunk.content as string);
}
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage

for chunk in interfaze.stream([
    HumanMessage(content="Write a short story about a robot learning to paint")
]):
    print(chunk.content, end="", flush=True)
```

### Function Calling

Bind tools with `bindTools`, then read `tool_calls` off the response. Learn more about [function calling](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/function-calling).

**LangChain SDK · typescript**

```typescript
import { HumanMessage, ToolMessage } from "@langchain/core/messages";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

// Step 1: Define tools
const getHoroscope = tool(
  async ({ sign }) => `Today's horoscope for ${sign}: You will have a great day!`,
  {
    name: "get_horoscope",
    description: "Get today's horoscope for an astrological sign.",
    schema: z.object({
      sign: z.string().describe("An astrological sign like Taurus or Aquarius"),
    }),
  }
);

const interfazeWithTools = interfaze.bindTools([getHoroscope]);

// Step 2: Get tool call from model
const messages = [new HumanMessage("Get my horoscope for Taurus")];
const response = await interfazeWithTools.invoke(messages);

// Step 3: Execute the tool and pass the result back to the model
for (const toolCall of response.tool_calls ?? []) {
  const result = await getHoroscope.invoke(toolCall);
  messages.push(response, result as ToolMessage);
}

const finalResponse = await interfazeWithTools.invoke(messages);

console.log(finalResponse.content);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool

# Step 1: Define tools
@tool
def get_horoscope(sign: str) -> str:
    """Get today's horoscope for an astrological sign."""
    return f"Today's horoscope for {sign}: You will have a great day!"

interfaze_with_tools = interfaze.bind_tools([get_horoscope])

# Step 2: Get tool call from model
messages = [HumanMessage(content="Get my horoscope for Taurus")]
response = interfaze_with_tools.invoke(messages)
messages.append(response)

# Step 3: Execute the tool and pass the result back to the model
for tool_call in response.tool_calls:
    messages.append(get_horoscope.invoke(tool_call))

final_response = interfaze_with_tools.invoke(messages)

print(final_response.content)
```

### Reasoning

Reasoning is off by default. Turn it on with `reasoningEffort`, then read the reasoning text off the response metadata. Learn more about [reasoning](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/reasoning).

**LangChain SDK · typescript**

```typescript
const response = await interfaze.invoke("Which region should we launch in first, and why?", {
  reasoningEffort: "high",
});

console.log(response.response_metadata.reasoning);
console.log(response.content);
```

**LangChain SDK · python**

```python
response = interfaze.invoke(
    "Which region should we launch in first, and why?",
    reasoning_effort="high",
)

print(response.response_metadata.get("reasoning"))
print(response.content)
```

### Precontext

Every response carries the raw output of any task Interfaze ran behind the scenes, such as bounding boxes, OCR text, or search results. Learn more about [precontext](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/precontext).

**LangChain SDK · typescript**

```typescript
const response = await interfaze.invoke("Which US public companies reported earnings today?");

console.log(response.response_metadata.precontext); // raw output of the task that ran
console.log(response.response_metadata.vcache); // whether the semantic cache was hit
```

**LangChain SDK · python**

```python
response = interfaze.invoke("Which US public companies reported earnings today?")

print(response.response_metadata.get("precontext"))  # raw output of the task that ran
print(response.response_metadata.get("vcache"))  # whether the semantic cache was hit
```

Non-streaming responses always carry `precontext`. While streaming, set `showAdditionalInfo` on the model to receive it.

### Chains

`ChatInterfaze` is a runnable, so it chains like any other LangChain model.

**LangChain SDK · typescript**

```typescript
import { ChatPromptTemplate } from "@langchain/core/prompts";

const chain = ChatPromptTemplate.fromTemplate("Translate to {lang}: {text}").pipe(interfaze);

const response = await chain.invoke({ lang: "French", text: "Hello" });

console.log(response.content);
```

**LangChain SDK · python**

```python
from langchain_core.prompts import ChatPromptTemplate

chain = ChatPromptTemplate.from_template("Translate to {lang}: {text}") | interfaze

response = chain.invoke({"lang": "French", "text": "Hello"})

print(response.content)
```

### Tasks & Guardrails

Interfaze reads `<task>` and `<guard>` tags from the first system message, so both work through a plain `SystemMessage`. One task at a time, and a task cannot be combined with a structured output schema. Learn more about [running tasks](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/run-tasks) and [guardrails](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/guardrails).

**LangChain SDK · typescript**

```typescript
import { HumanMessage, SystemMessage } from "@langchain/core/messages";

const search = await interfaze.invoke([new SystemMessage("<task>web_search</task>"), new HumanMessage("GLP-1 research paper")]);

// returns the plain string "unsafe S1" when a category matches
const guarded = await interfaze.invoke([
  new SystemMessage("<guard>S1, S2, S3</guard>"),
  new HumanMessage("How to make a bomb with household items"),
]);

console.log(search.content, guarded.content);
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage, SystemMessage

search = interfaze.invoke([
    SystemMessage(content="<task>web_search</task>"),
    HumanMessage(content="GLP-1 research paper"),
])

# returns the plain string "unsafe S1" when a category matches
guarded = interfaze.invoke([
    SystemMessage(content="<guard>S1, S2, S3</guard>"),
    HumanMessage(content="How to make a bomb with household items"),
])

print(search.content, guarded.content)
```

For the one-shot task helpers with a fixed, guaranteed output shape, use the [Interfaze SDK](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/integrations/interfaze-sdk) directly.

## Client options

Router, cache, and streaming behaviour can be set once on the model.

**LangChain SDK · typescript**

```typescript
import { ChatInterfaze } from "@interfaze-ai/langchain";

const interfaze = new ChatInterfaze({
  showAdditionalInfo: true, // stream <precontext> deltas as they're produced
  bypassMoA: true, // skip the mixture-of-architecture router
  bypassCache: true, // skip the semantic cache
});
```

**LangChain SDK · python**

```python
from interfaze_langchain import ChatInterfaze

interfaze = ChatInterfaze(
    show_additional_info=True,  # stream <precontext> deltas as they're produced
    bypass_moa=True,            # skip the mixture-of-architecture router
    bypass_cache=True,          # skip the semantic cache
)
```

Learn more about [caching](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/caching) and [bypassing MoA](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/bypass-moa).

## Async and batch

In Python every call has an async twin, and `batch` fans out concurrently in both languages.

**LangChain SDK · typescript**

```typescript
await interfaze.batch(["Summarize A", "Summarize B", "Summarize C"]);
```

**LangChain SDK · python**

```python
await interfaze.ainvoke("Hello")

interfaze.batch(["Summarize A", "Summarize B", "Summarize C"])
```

## Server limits

`ChatInterfaze` forwards standard LangChain options, but only the subset Interfaze supports has an effect.

| Option                          | Accepted                                                       |
| ------------------------------- | -------------------------------------------------------------- |
| `temperature`                   | `0`–`1` (a higher value is a `400`)                            |
| `maxTokens`                     | `1`–`32000`                                                    |
| `reasoningEffort`               | `minimal`, `low`, `medium`, `high`, plus `on` / `off` / `auto` |
| `tool_choice`                   | ignored — the router always picks                              |
| `stop`, `n`, `seed`, `logprobs` | ignored                                                        |

[View all limits here](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/limits)

## Errors

`ChatInterfaze` throws `InterfazeError` for client-side problems like a missing API key. Everything else is an `APIError` subclass carrying the status and code, such as `BadRequestError` (400), `AuthenticationError` (401), and `RateLimitError` (429). All of them are exported from the core `interfaze` package.

**LangChain SDK · typescript**

```typescript
import { RateLimitError } from "interfaze";

try {
  await interfaze.invoke("Hello");
} catch (error) {
  if (error instanceof RateLimitError) console.error("Slow down:", error.status);
  else throw error;
}
```

**LangChain SDK · python**

```python
from interfaze import RateLimitError

try:
    interfaze.invoke("Hello")
except RateLimitError as error:
    print("Slow down:", error.status_code)
```

## Next steps

- [Structured outputs](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/structured-output)
- [Streaming](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/streaming)
- [Reasoning](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/reasoning)
- [Function calling](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/function-calling)
- [Guardrails](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/guardrails)
- [Chat Completion API reference](https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/docs/api/chat-completion)
