# LangChain SDK Integration

URL: https://interfaze.ai/docs/integrations/langchain-sdk

Interfaze supports the Chat Completion API standard, so you can use it out of the box with LangChain by pointing it to Interfaze's base URL and API key.

## Installation

**npm / yarn · typescript**

```typescript
npm install @langchain/openai @langchain/core
# or
yarn add @langchain/openai @langchain/core
```

**pip · python**

```python
pip install langchain-openai langchain-core
```

## Official Documentation

- [LangChain Documentation](https://js.langchain.com/docs/)
- [LangChain OpenAI Integration](https://js.langchain.com/docs/integrations/llms/openai)
- [LangChain Streaming](https://js.langchain.com/docs/guides/expression_language/streaming)

> **Note:** Interfaze supports the Chat Completion API standard and not the Response API standard.

## Basic Setup

**LangChain SDK · typescript**

```typescript
import { ChatOpenAI } from "@langchain/openai";

const interfaze = new ChatOpenAI({
  configuration: {
    baseURL: "https://api.interfaze.ai/v1",
  },
  apiKey: "<your-api-key>",
  model: "interfaze-beta",
});
```

**LangChain SDK · python**

```python
from langchain_openai import ChatOpenAI

interfaze = ChatOpenAI(
    base_url="https://api.interfaze.ai/v1",
    api_key="<your-api-key>",
    model="interfaze-beta",
)
```

## Examples

### Text Generation

**LangChain SDK · typescript**

```typescript
import { ChatOpenAI } from "@langchain/openai";
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.ai/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)
```

### Image / File Input

**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)
```

### Streaming

Learn more about [streaming](https://interfaze.ai/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

Learn more about [function calling](https://interfaze.ai/docs/function-calling).

**LangChain SDK · typescript**

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

// Step 1: Define tools
const tools = [
  {
    type: "function" as const,
    function: {
      name: "get_horoscope",
      description: "Get today's horoscope for an astrological sign.",
      parameters: {
        type: "object",
        properties: {
          sign: {
            type: "string",
            description: "An astrological sign like Taurus or Aquarius",
          },
        },
        required: ["sign"],
      },
    },
  },
];

// Step 2: Get tool call from model
const response = await interfaze.invoke(
  [new HumanMessage("Get my horoscope for Taurus")],
  { tools, tool_choice: "auto" },
);

// Step 3: Check if tool was called and execute function
if (response.additional_kwargs.tool_calls?.length) {
  const toolCall = response.additional_kwargs.tool_calls[0];
  const args = JSON.parse(toolCall.function.arguments);

  const result = `Today's horoscope for ${args.sign}: You will have a great day!`;

  // Step 4: Provide result back to model
  const finalResponse = await interfaze.invoke(
    [
      new HumanMessage("Get my horoscope for Taurus"),
      response,
      { role: "tool", tool_call_id: toolCall.id, content: result },
    ],
    { tools, tool_choice: "auto" },
  );

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

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
import json

# Step 1: Define tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_horoscope",
            "description": "Get today's horoscope for an astrological sign.",
            "parameters": {
                "type": "object",
                "properties": {
                    "sign": {
                        "type": "string",
                        "description": "An astrological sign like Taurus or Aquarius",
                    },
                },
                "required": ["sign"],
            },
        },
    },
]

interfaze_with_tools = interfaze.bind(tools=tools, tool_choice="auto")

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

# Step 3: Check if tool was called and execute function
if response.additional_kwargs.get("tool_calls"):
    tool_call = response.additional_kwargs["tool_calls"][0]
    args = json.loads(tool_call["function"]["arguments"])

    result = f"Today's horoscope for {args['sign']}: You will have a great day!"

    # Step 4: Provide result back to model
    final_response = interfaze_with_tools.invoke([
        HumanMessage(content="Get my horoscope for Taurus"),
        response,
        {"role": "tool", "tool_call_id": tool_call["id"], "content": result},
    ])

    print(final_response.content)
```
