# Using Interfaze as a Tool Inside Your Agent

URL: https://interfaze.ai/blog/using-interfaze-as-a-tool-inside-your-agent

You might already have a complex agent workflow built but need to increase the accuracy for tasks. Sometimes it's better document extraction for more visibility to your agent, or higher quality web data extracted for clearer context.

You can easily wire Interfaze as a tool inside your existing agent pipeline without changing your existing workflow.

[**Run-task mode**](https://interfaze.ai/docs/run-tasks) lets you run specific parts of the model without running the full model. The output is raw structured JSON, no prose, no wrappers, just the data your agent needs for better context leading to better accuracy.

## When to use Interfaze as a tool?

- **You already have a complex agent workflow.** Adding OCR, live web data, or audio transcription as tool calls is the cleanest path.

- **High reasoning continuous loop tasks.** Tasks that can run for a long time and would need higher quality context at different stages of the task on different documents, websites, etc.

## How run-task mode works

Add a `<task>` tag to the system prompt and set the response format to an empty schema. Interfaze activates only a small part of the full model and runs only the requested capability.

Learn more about [run-task mode](https://interfaze.ai/docs/run-tasks).

```xml
<task>web_search</task>
```

The output always follows this shape:

```json
{
  "name": "web_search",
  "result": { ... }
}
```

The `result` schema is task-specific and consistent on every run. Pass it back as tool output and your agent's context is immediately enriched.

Available tasks:

| Task               | What it does                                              |
| ------------------ | --------------------------------------------------------- |
| `ocr`              | Extract text and structured data from images or documents |
| `object_detection` | Detect and locate objects in images                       |
| `web_search`       | Real-time web search with sources                         |
| `scraper`          | Extract structured content from any web page              |
| `speech_to_text`   | Transcribe audio files with timestamps                    |
| `translate`        | Translate text between languages                          |

## Setting up the Interfaze client

All examples below include this client initialization in each tab.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

tab-Vercel AI SDK
import { createOpenAI } from "@ai-sdk/openai";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

language-python

tab-OpenAI SDK
from openai import OpenAI
import os

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)

tab-LangChain SDK
from langchain_openai import ChatOpenAI
import os

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)
```

## Example 1: Document analysis with OCR

Register Interfaze OCR as a tool in your agent. When the model encounters a PDF or document URL, it calls the tool and gets back clean structured text to reason over.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});
const model = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runInterfazeTask(task: string, prompt: string) {
  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${task}</task>` },
      { role: "user", content: prompt },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });
  return JSON.parse(res.choices[0].message.content!).result;
}

const ocrTool = {
  type: "function" as const,
  function: {
    name: "ocr",
    description: "Extract text and structured data from images or documents.",
    parameters: {
      type: "object",
      properties: {
        url: { type: "string", description: "URL of the image or document." },
      },
      required: ["url"],
    },
  },
};

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "user",
    content: "Extract the title, authors, abstract, and key findings from this research paper: https://arxiv.org/pdf/2602.04101",
  },
];

const res = await model.chat.completions.create({
  model: "gpt-5.4",
  messages,
  tools: [ocrTool],
  tool_choice: "auto",
});

messages.push(res.choices[0].message);

for (const call of res.choices[0].message.tool_calls ?? []) {
  const { url } = JSON.parse(call.function.arguments);
  const result = await runInterfazeTask("ocr", `Extract the title, authors, abstract, and key findings from: ${url}`);
  messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}

const final = await model.chat.completions.create({ model: "gpt-5.4", messages });
console.log(final.choices[0].message.content);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

const { text } = await generateText({
  model: openai("gpt-5.4"),
  tools: {
    ocr: tool({
      description: "Extract text and structured data from images or documents.",
      inputSchema: z.object({
        url: z.string().describe("URL of the image or document."),
      }),
      execute: async ({ url }) =>
        runInterfazeTask("ocr", `Extract all text and data from: ${url}`),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: "Extract the title, authors, abstract, and key findings from this research paper: https://arxiv.org/pdf/2602.04101",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const ocrTool = tool(
  async ({ url }) =>
    JSON.stringify(await runInterfazeTask("ocr", `Extract the title, authors, abstract, and key findings from: ${url}`)),
  {
    name: "ocr",
    description: "Extract text and structured data from images or documents.",
    schema: z.object({ url: z.string().describe("URL of the image or document.") }),
  }
);

const model = new ChatOpenAI({ model: "gpt-5.4" }).bindTools([ocrTool]);

const messages = [
  new HumanMessage(
    "Extract the title, authors, abstract, and key findings from this research paper: https://arxiv.org/pdf/2602.04101"
  ),
];

const response = await model.invoke(messages);
messages.push(response);

for (const call of response.tool_calls ?? []) {
  const result = await ocrTool.invoke(call.args);
  messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}

const final = await model.invoke(messages);
console.log(final.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)
model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_interfaze_task(task: str, prompt: str) -> dict:
    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{task}</task>"},
            {"role": "user", "content": prompt},
        ],
    )
    return json.loads(res.choices[0].message.content)["result"]

ocr_tool = {
    "type": "function",
    "function": {
        "name": "ocr",
        "description": "Extract text and structured data from images or documents.",
        "parameters": {
            "type": "object",
            "properties": {"url": {"type": "string", "description": "URL of the image or document."}},
            "required": ["url"],
        },
    },
}

messages = [
    {"role": "user", "content": "Extract the title, authors, abstract, and key findings from this research paper: https://arxiv.org/pdf/2602.04101"}
]

res = model.chat.completions.create(model="gpt-5.4", messages=messages, tools=[ocr_tool], tool_choice="auto")
messages.append(res.choices[0].message)

for call in res.choices[0].message.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = run_interfaze_task("ocr", f"Extract the title, authors, abstract, and key findings from: {args['url']}")
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

final = model.chat.completions.create(model="gpt-5.4", messages=messages)
print(final.choices[0].message.content)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def ocr(url: str) -> str:
    """Extract text and structured data from images or documents."""
    return json.dumps(run_interfaze_task("ocr", f"Extract the title, authors, abstract, and key findings from: {url}"))

model = ChatOpenAI(model="gpt-5.4").bind_tools([ocr])

messages = [HumanMessage(content="Extract the title, authors, abstract, and key findings from this research paper: https://arxiv.org/pdf/2602.04101")]
response = model.invoke(messages)
messages.append(response)

for call in response.tool_calls or []:
    result = ocr.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

final = model.invoke(messages)
print(final.content)
```

## Example 2: Documentation and bug search for coding tasks

Give your coding agent a web search tool backed by Interfaze. It looks up live docs, searches existing bug reports, and pulls changelogs before writing code, so it never hallucinates a deprecated API.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});
const model = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runInterfazeTask(task: string, prompt: string) {
  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${task}</task>` },
      { role: "user", content: prompt },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });
  return JSON.parse(res.choices[0].message.content!).result;
}

const webSearchTool = {
  type: "function" as const,
  function: {
    name: "web_search",
    description: "Search the web for real-time information, documentation, or bug reports.",
    parameters: {
      type: "object",
      properties: {
        query: { type: "string", description: "The search query." },
      },
      required: ["query"],
    },
  },
};

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "system",
    content: "You are a coding assistant. Always search for the latest docs before writing code.",
  },
  {
    role: "user",
    content: "Write a React hook for infinite scroll using TanStack Query v5.",
  },
];

const res = await model.chat.completions.create({
  model: "gpt-5.4",
  messages,
  tools: [webSearchTool],
  tool_choice: "auto",
});

messages.push(res.choices[0].message);

for (const call of res.choices[0].message.tool_calls ?? []) {
  const { query } = JSON.parse(call.function.arguments);
  const result = await runInterfazeTask("web_search", query);
  messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}

const final = await model.chat.completions.create({ model: "gpt-5.4", messages });
console.log(final.choices[0].message.content);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

const { text } = await generateText({
  model: openai("gpt-5.4"),
  system: "You are a coding assistant. Always search for the latest docs before writing code.",
  tools: {
    web_search: tool({
      description: "Search the web for real-time information, documentation, or bug reports.",
      inputSchema: z.object({
        query: z.string().describe("The search query."),
      }),
      execute: async ({ query }) => runInterfazeTask("web_search", query),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: "Write a React hook for infinite scroll using TanStack Query v5.",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const webSearchTool = tool(
  async ({ query }) => JSON.stringify(await runInterfazeTask("web_search", query)),
  {
    name: "web_search",
    description: "Search the web for real-time information, documentation, or bug reports.",
    schema: z.object({ query: z.string().describe("The search query.") }),
  }
);

const model = new ChatOpenAI({ model: "gpt-5.4" }).bindTools([webSearchTool]);

const messages = [
  new SystemMessage("You are a coding assistant. Always search for the latest docs before writing code."),
  new HumanMessage("Write a React hook for infinite scroll using TanStack Query v5."),
];

const response = await model.invoke(messages);
messages.push(response);

for (const call of response.tool_calls ?? []) {
  const result = await webSearchTool.invoke(call.args);
  messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}

const final = await model.invoke(messages);
console.log(final.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)
model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_interfaze_task(task: str, prompt: str) -> dict:
    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{task}</task>"},
            {"role": "user", "content": prompt},
        ],
    )
    return json.loads(res.choices[0].message.content)["result"]

web_search_tool = {
    "type": "function",
    "function": {
        "name": "web_search",
        "description": "Search the web for real-time information, documentation, or bug reports.",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string", "description": "The search query."}},
            "required": ["query"],
        },
    },
}

messages = [
    {"role": "system", "content": "You are a coding assistant. Always search for the latest docs before writing code."},
    {"role": "user", "content": "Write a Python function to batch process S3 uploads using boto3 with retry logic."},
]

res = model.chat.completions.create(model="gpt-5.4", messages=messages, tools=[web_search_tool], tool_choice="auto")
messages.append(res.choices[0].message)

for call in res.choices[0].message.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = run_interfaze_task("web_search", args["query"])
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

final = model.chat.completions.create(model="gpt-5.4", messages=messages)
print(final.choices[0].message.content)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def web_search(query: str) -> str:
    """Search the web for real-time information, documentation, or bug reports."""
    return json.dumps(run_interfaze_task("web_search", query))

model = ChatOpenAI(model="gpt-5.4").bind_tools([web_search])

messages = [
    SystemMessage(content="You are a coding assistant. Always search for the latest docs before writing code."),
    HumanMessage(content="Write a Python function to batch process S3 uploads using boto3 with retry logic."),
]

response = model.invoke(messages)
messages.append(response)

for call in response.tool_calls or []:
    result = web_search.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

final = model.invoke(messages)
print(final.content)
```

## Example 3: Competitor and research scraping

Wire the Interfaze scraper as a tool for your research agent. The model calls it when it needs content from a URL and gets back clean structured data to work with.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});
const model = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runInterfazeTask(task: string, prompt: string) {
  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${task}</task>` },
      { role: "user", content: prompt },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });
  return JSON.parse(res.choices[0].message.content!).result;
}

const scraperTool = {
  type: "function" as const,
  function: {
    name: "scraper",
    description: "Extract structured content from any public web page.",
    parameters: {
      type: "object",
      properties: {
        url: { type: "string", description: "URL of the page to scrape." },
        instruction: { type: "string", description: "What to extract from the page." },
      },
      required: ["url"],
    },
  },
};

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "user",
    content: "Summarize the key features and capabilities on https://interfaze.ai",
  },
];

const res = await model.chat.completions.create({
  model: "gpt-5.4",
  messages,
  tools: [scraperTool],
  tool_choice: "auto",
});

messages.push(res.choices[0].message);

for (const call of res.choices[0].message.tool_calls ?? []) {
  const { url, instruction } = JSON.parse(call.function.arguments);
  const result = await runInterfazeTask(
    "scraper",
    `${instruction ?? "Extract the main content from"} ${url}`
  );
  messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}

const final = await model.chat.completions.create({ model: "gpt-5.4", messages });
console.log(final.choices[0].message.content);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

const { text } = await generateText({
  model: openai("gpt-5.4"),
  tools: {
    scraper: tool({
      description: "Extract structured content from any public web page.",
      inputSchema: z.object({
        url: z.string().describe("URL of the page to scrape."),
        instruction: z.string().optional().describe("What to extract from the page."),
      }),
      execute: async ({ url, instruction }) =>
        runInterfazeTask("scraper", `${instruction ?? "Extract the main content from"} ${url}`),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: "Summarize the key features and capabilities on https://interfaze.ai",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const scraperTool = tool(
  async ({ url, instruction }) =>
    JSON.stringify(
      await runInterfazeTask("scraper", `${instruction ?? "Extract the main content from"} ${url}`)
    ),
  {
    name: "scraper",
    description: "Extract structured content from any public web page.",
    schema: z.object({
      url: z.string().describe("URL of the page to scrape."),
      instruction: z.string().optional().describe("What to extract from the page."),
    }),
  }
);

const model = new ChatOpenAI({ model: "gpt-5.4" }).bindTools([scraperTool]);

const messages = [
  new HumanMessage("Summarize the key features and capabilities on https://interfaze.ai"),
];

const response = await model.invoke(messages);
messages.push(response);

for (const call of response.tool_calls ?? []) {
  const result = await scraperTool.invoke(call.args);
  messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}

const final = await model.invoke(messages);
console.log(final.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)
model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_interfaze_task(task: str, prompt: str) -> dict:
    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{task}</task>"},
            {"role": "user", "content": prompt},
        ],
    )
    return json.loads(res.choices[0].message.content)["result"]

scraper_tool = {
    "type": "function",
    "function": {
        "name": "scraper",
        "description": "Extract structured content from any public web page.",
        "parameters": {
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": "URL of the page to scrape."},
                "instruction": {"type": "string", "description": "What to extract from the page."},
            },
            "required": ["url"],
        },
    },
}

messages = [
    {"role": "user", "content": "Summarize the key features and capabilities on https://interfaze.ai"}
]

res = model.chat.completions.create(model="gpt-5.4", messages=messages, tools=[scraper_tool], tool_choice="auto")
messages.append(res.choices[0].message)

for call in res.choices[0].message.tool_calls or []:
    args = json.loads(call.function.arguments)
    instruction = args.get("instruction", "Extract the main content from")
    result = run_interfaze_task("scraper", f"{instruction} {args['url']}")
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

final = model.chat.completions.create(model="gpt-5.4", messages=messages)
print(final.choices[0].message.content)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def scraper(url: str, instruction: str = "Extract the main content from") -> str:
    """Extract structured content from any public web page."""
    return json.dumps(run_interfaze_task("scraper", f"{instruction} {url}"))

model = ChatOpenAI(model="gpt-5.4").bind_tools([scraper])

messages = [HumanMessage(content="Summarize the key features and capabilities on https://interfaze.ai")]
response = model.invoke(messages)
messages.append(response)

for call in response.tool_calls or []:
    result = scraper.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

final = model.invoke(messages)
print(final.content)
```

## Example 4: Blazing fast meeting summarization

Register speech-to-text as a tool. The model transcribes a full recording in seconds and immediately summarizes it, turning a 60-minute call into a clean summary and action item list without any manual steps.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});
const model = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runInterfazeTask(task: string, prompt: string) {
  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${task}</task>` },
      { role: "user", content: prompt },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });
  return JSON.parse(res.choices[0].message.content!).result;
}

const sttTool = {
  type: "function" as const,
  function: {
    name: "speech_to_text",
    description: "Transcribe an audio file to text.",
    parameters: {
      type: "object",
      properties: {
        audio_url: { type: "string", description: "URL of the audio file." },
      },
      required: ["audio_url"],
    },
  },
};

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "user",
    content:
      "Summarize this call and list any follow-up items: https://r2public.jigsawstack.com/interfaze/examples/stt_call.mp3",
  },
];

const res = await model.chat.completions.create({
  model: "gpt-5.4",
  messages,
  tools: [sttTool],
  tool_choice: "auto",
});

messages.push(res.choices[0].message);

for (const call of res.choices[0].message.tool_calls ?? []) {
  const { audio_url } = JSON.parse(call.function.arguments);
  const result = await runInterfazeTask("speech_to_text", `Transcribe this audio: ${audio_url}`);
  messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}

const final = await model.chat.completions.create({ model: "gpt-5.4", messages });
console.log(final.choices[0].message.content);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

const { text } = await generateText({
  model: openai("gpt-5.4"),
  tools: {
    speech_to_text: tool({
      description: "Transcribe an audio file to text.",
      inputSchema: z.object({
        audio_url: z.string().describe("URL of the audio file."),
      }),
      execute: async ({ audio_url }) =>
        runInterfazeTask("speech_to_text", `Transcribe this audio: ${audio_url}`),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: "Summarize this call and list any follow-up items: https://r2public.jigsawstack.com/interfaze/examples/stt_call.mp3",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const sttTool = tool(
  async ({ audio_url }) =>
    JSON.stringify(
      await runInterfazeTask("speech_to_text", `Transcribe this audio: ${audio_url}`)
    ),
  {
    name: "speech_to_text",
    description: "Transcribe an audio file to text.",
    schema: z.object({ audio_url: z.string().describe("URL of the audio file.") }),
  }
);

const model = new ChatOpenAI({ model: "gpt-5.4" }).bindTools([sttTool]);

const messages = [
  new HumanMessage(
    "Summarize this call and list any follow-up items: https://r2public.jigsawstack.com/interfaze/examples/stt_call.mp3"
  ),
];

const response = await model.invoke(messages);
messages.push(response);

for (const call of response.tool_calls ?? []) {
  const result = await sttTool.invoke(call.args);
  messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}

const final = await model.invoke(messages);
console.log(final.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)
model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_interfaze_task(task: str, prompt: str) -> dict:
    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{task}</task>"},
            {"role": "user", "content": prompt},
        ],
    )
    return json.loads(res.choices[0].message.content)["result"]

stt_tool = {
    "type": "function",
    "function": {
        "name": "speech_to_text",
        "description": "Transcribe an audio file to text.",
        "parameters": {
            "type": "object",
            "properties": {"audio_url": {"type": "string", "description": "URL of the audio file."}},
            "required": ["audio_url"],
        },
    },
}

messages = [
    {
        "role": "user",
        "content": "Summarize this call and list any follow-up items: https://r2public.jigsawstack.com/interfaze/examples/stt_call.mp3",
    }
]

res = model.chat.completions.create(model="gpt-5.4", messages=messages, tools=[stt_tool], tool_choice="auto")
messages.append(res.choices[0].message)

for call in res.choices[0].message.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = run_interfaze_task("speech_to_text", f"Transcribe this audio: {args['audio_url']}")
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

final = model.chat.completions.create(model="gpt-5.4", messages=messages)
print(final.choices[0].message.content)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def speech_to_text(audio_url: str) -> str:
    """Transcribe an audio file to text."""
    return json.dumps(run_interfaze_task("speech_to_text", f"Transcribe this audio: {audio_url}"))

model = ChatOpenAI(model="gpt-5.4").bind_tools([speech_to_text])

messages = [
    HumanMessage(
        content="Summarize this call and list any follow-up items: https://r2public.jigsawstack.com/interfaze/examples/stt_call.mp3"
    )
]
response = model.invoke(messages)
messages.append(response)

for call in response.tool_calls or []:
    result = speech_to_text.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

final = model.invoke(messages)
print(final.content)
```

## Example 5: Multilingual content pipeline

Register translate as a tool. The model calls it when it needs to understand foreign-language content, then analyzes or summarizes without a second round-trip.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});
const model = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runInterfazeTask(task: string, prompt: string) {
  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${task}</task>` },
      { role: "user", content: prompt },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });
  return JSON.parse(res.choices[0].message.content!).result;
}

const translateTool = {
  type: "function" as const,
  function: {
    name: "translate",
    description: "Translate text between languages.",
    parameters: {
      type: "object",
      properties: {
        text: { type: "string", description: "Text to translate." },
        target_language: { type: "string", description: "Target language." },
      },
      required: ["text", "target_language"],
    },
  },
};

const messages: OpenAI.ChatCompletionMessageParam[] = [
  {
    role: "user",
    content: "Summarize the key findings from this French research abstract: \"Les modèles de langage de grande taille ont transformé le traitement automatique du langage naturel. Cependant, leur coût computationnel reste un obstacle majeur à leur déploiement à grande échelle. Cette étude propose une nouvelle approche de distillation qui réduit la taille du modèle de 80% tout en conservant 95% des performances sur les benchmarks standards.\"",
  },
];

const res = await model.chat.completions.create({
  model: "gpt-5.4",
  messages,
  tools: [translateTool],
  tool_choice: "auto",
});

messages.push(res.choices[0].message);

for (const call of res.choices[0].message.tool_calls ?? []) {
  const { text, target_language } = JSON.parse(call.function.arguments);
  const result = await runInterfazeTask("translate", `Translate to ${target_language}: ${text}`);
  messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}

const final = await model.chat.completions.create({ model: "gpt-5.4", messages });
console.log(final.choices[0].message.content);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

const { text } = await generateText({
  model: openai("gpt-5.4"),
  tools: {
    translate: tool({
      description: "Translate text between languages.",
      inputSchema: z.object({
        text: z.string().describe("Text to translate."),
        target_language: z.string().describe("Target language."),
      }),
      execute: async ({ text, target_language }) =>
        runInterfazeTask("translate", `Translate to ${target_language}: ${text}`),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: "Summarize the key findings from this French research abstract: \"Les modèles de langage de grande taille ont transformé le traitement automatique du langage naturel. Cependant, leur coût computationnel reste un obstacle majeur à leur déploiement à grande échelle. Cette étude propose une nouvelle approche de distillation qui réduit la taille du modèle de 80% tout en conservant 95% des performances sur les benchmarks standards.\"",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const translateTool = tool(
  async ({ text, target_language }) =>
    JSON.stringify(
      await runInterfazeTask("translate", `Translate to ${target_language}: ${text}`)
    ),
  {
    name: "translate",
    description: "Translate text between languages.",
    schema: z.object({
      text: z.string().describe("Text to translate."),
      target_language: z.string().describe("Target language."),
    }),
  }
);

const model = new ChatOpenAI({ model: "gpt-5.4" }).bindTools([translateTool]);

const messages = [
  new HumanMessage("Summarize the key findings from this French research abstract: \"Les modèles de langage de grande taille ont transformé le traitement automatique du langage naturel. Cependant, leur coût computationnel reste un obstacle majeur à leur déploiement à grande échelle. Cette étude propose une nouvelle approche de distillation qui réduit la taille du modèle de 80% tout en conservant 95% des performances sur les benchmarks standards.\""),
];

const response = await model.invoke(messages);
messages.push(response);

for (const call of response.tool_calls ?? []) {
  const result = await translateTool.invoke(call.args);
  messages.push(new ToolMessage({ content: result, tool_call_id: call.id }));
}

const final = await model.invoke(messages);
console.log(final.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)
model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_interfaze_task(task: str, prompt: str) -> dict:
    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{task}</task>"},
            {"role": "user", "content": prompt},
        ],
    )
    return json.loads(res.choices[0].message.content)["result"]

translate_tool = {
    "type": "function",
    "function": {
        "name": "translate",
        "description": "Translate text between languages.",
        "parameters": {
            "type": "object",
            "properties": {
                "text": {"type": "string", "description": "Text to translate."},
                "target_language": {"type": "string", "description": "Target language."},
            },
            "required": ["text", "target_language"],
        },
    },
}

messages = [
    {"role": "user", "content": "Summarize the key findings from this French research abstract: \"Les modèles de langage de grande taille ont transformé le traitement automatique du langage naturel. Cependant, leur coût computationnel reste un obstacle majeur à leur déploiement à grande échelle. Cette étude propose une nouvelle approche de distillation qui réduit la taille du modèle de 80% tout en conservant 95% des performances sur les benchmarks standards.\""}
]

res = model.chat.completions.create(model="gpt-5.4", messages=messages, tools=[translate_tool], tool_choice="auto")
messages.append(res.choices[0].message)

for call in res.choices[0].message.tool_calls or []:
    args = json.loads(call.function.arguments)
    result = run_interfaze_task("translate", f"Translate to {args['target_language']}: {args['text']}")
    messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

final = model.chat.completions.create(model="gpt-5.4", messages=messages)
print(final.choices[0].message.content)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage, ToolMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def translate(text: str, target_language: str) -> str:
    """Translate text between languages."""
    return json.dumps(run_interfaze_task("translate", f"Translate to {target_language}: {text}"))

model = ChatOpenAI(model="gpt-5.4").bind_tools([translate])

french_abstract = "Les modèles de langage de grande taille ont transformé le traitement automatique du langage naturel. Cependant, leur coût computationnel reste un obstacle majeur à leur déploiement à grande échelle. Cette étude propose une nouvelle approche de distillation qui réduit la taille du modèle de 80% tout en conservant 95% des performances sur les benchmarks standards."

messages = [HumanMessage(content=f"Summarize the key findings from this French research abstract: \"{french_abstract}\"")]
response = model.invoke(messages)
messages.append(response)

for call in response.tool_calls or []:
    result = translate.invoke(call["args"])
    messages.append(ToolMessage(content=result, tool_call_id=call["id"]))

final = model.invoke(messages)
print(final.content)
```

## Drop-in tool array for your agent

Copy this into your existing agent. The executor function handles all the wiring: one implementation, six tools.

```tabs
language-typescript

tab-OpenAI SDK
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const interfaze = new OpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

export const interfazeToolDefinitions = [
  {
    type: "function" as const,
    function: {
      name: "ocr",
      description: "Extract text and structured data from images or documents.",
      parameters: {
        type: "object",
        properties: {
          url: { type: "string", description: "URL of the image or document." },
        },
        required: ["url"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "web_search",
      description: "Search the web for real-time information, news, or documentation.",
      parameters: {
        type: "object",
        properties: {
          query: { type: "string", description: "The search query." },
        },
        required: ["query"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "scraper",
      description: "Extract structured content from any public web page.",
      parameters: {
        type: "object",
        properties: {
          url: { type: "string", description: "URL to scrape." },
          instruction: { type: "string", description: "What to extract." },
        },
        required: ["url"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "speech_to_text",
      description: "Transcribe audio files to text with timestamps.",
      parameters: {
        type: "object",
        properties: {
          audio_url: { type: "string", description: "URL of the audio file." },
        },
        required: ["audio_url"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "object_detection",
      description: "Detect and locate objects in images, returning bounding boxes and labels.",
      parameters: {
        type: "object",
        properties: {
          image_url: { type: "string", description: "URL of the image." },
          prompt: { type: "string", description: "Description of what objects to detect." },
        },
        required: ["image_url"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "translate",
      description: "Translate text between languages.",
      parameters: {
        type: "object",
        properties: {
          text: { type: "string", description: "Text to translate." },
          target_language: { type: "string", description: "Target language." },
        },
        required: ["text", "target_language"],
      },
    },
  },
];

export async function executeInterfazeTool(
  toolName: string,
  args: Record<string, string>
): Promise<unknown> {
  const promptMap: Record<string, string> = {
    ocr: `Extract the title, authors, abstract, and key findings from: ${args.url}`,
    web_search: args.query,
    scraper: `${args.instruction ?? "Extract the main content from"} ${args.url}`,
    speech_to_text: `Transcribe this audio: ${args.audio_url}`,
    object_detection: `${args.prompt ?? "Detect all objects in"} this image: ${args.image_url}`,
    translate: `Translate to ${args.target_language}: ${args.text}`,
  };

  const res = await interfaze.chat.completions.create({
    model: "interfaze-beta",
    messages: [
      { role: "system", content: `<task>${toolName}</task>` },
      { role: "user", content: promptMap[toolName] },
    ],
    response_format: zodResponseFormat(z.any(), "empty_schema"),
  });

  return JSON.parse(res.choices[0].message.content!).result;
}

// Agent loop
const mainModel = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function runAgent(userMessage: string) {
  const messages: OpenAI.ChatCompletionMessageParam[] = [
    { role: "user", content: userMessage },
  ];

  while (true) {
    const response = await mainModel.chat.completions.create({
      model: "gpt-5.4",
      messages,
      tools: interfazeToolDefinitions,
      tool_choice: "auto",
    });

    const choice = response.choices[0];

    if (choice.finish_reason === "stop") {
      return choice.message.content;
    }

    messages.push(choice.message);

    for (const call of choice.message.tool_calls ?? []) {
      const args = JSON.parse(call.function.arguments);
      const result = await executeInterfazeTool(call.function.name, args);
      messages.push({
        role: "tool",
        tool_call_id: call.id,
        content: JSON.stringify(result),
      });
    }
  }
}

const result = await runAgent(
  "Find the latest changelog for Zod v4 and summarize what changed."
);
console.log(result);

tab-Vercel AI SDK
import { createOpenAI, openai } from "@ai-sdk/openai";
import { generateText, Output, tool, stepCountIs } from "ai";
import { z } from "zod";

const interfaze = createOpenAI({
  apiKey: process.env.INTERFAZE_API_KEY,
  baseURL: "https://api.interfaze.ai/v1",
});

async function runInterfazeTask(task: string, prompt: string) {
  const { output } = await generateText({
    model: interfaze.chat("interfaze-beta"),
    system: `<task>${task}</task>`,
    output: Output.object({ schema: z.any() }),
    prompt,
  });
  return output.result;
}

export const interfazeTools = {
  ocr: tool({
    description: "Extract text and structured data from images or documents.",
    inputSchema: z.object({ url: z.string() }),
      execute: async ({ url }) => runInterfazeTask("ocr", `Extract the title, authors, abstract, and key findings from: ${url}`),
  }),
  web_search: tool({
    description: "Search the web for real-time information, news, or documentation.",
    inputSchema: z.object({ query: z.string() }),
    execute: async ({ query }) => runInterfazeTask("web_search", query),
  }),
  scraper: tool({
    description: "Extract structured content from any public web page.",
    inputSchema: z.object({ url: z.string(), instruction: z.string().optional() }),
    execute: async ({ url, instruction }) =>
      runInterfazeTask("scraper", `${instruction ?? "Extract the main content from"} ${url}`),
  }),
  speech_to_text: tool({
    description: "Transcribe audio files to text.",
    inputSchema: z.object({ audio_url: z.string() }),
    execute: async ({ audio_url }) =>
      runInterfazeTask("speech_to_text", `Transcribe this audio: ${audio_url}`),
  }),
  object_detection: tool({
    description: "Detect and locate objects in images.",
    inputSchema: z.object({ image_url: z.string(), prompt: z.string().optional() }),
    execute: async ({ image_url, prompt }) =>
      runInterfazeTask(
        "object_detection",
        `${prompt ?? "Detect all objects in"} this image: ${image_url}`
      ),
  }),
  translate: tool({
    description: "Translate text between languages.",
    inputSchema: z.object({ text: z.string(), target_language: z.string() }),
    execute: async ({ text, target_language }) =>
      runInterfazeTask("translate", `Translate to ${target_language}: ${text}`),
  }),
};

const { text } = await generateText({
  model: openai("gpt-5.4"),
  tools: interfazeTools,
  stopWhen: stepCountIs(5),
  prompt: "Find the latest changelog for Zod v4 and summarize what changed.",
});

console.log(text);

tab-LangChain SDK
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { z } from "zod";

const interfaze = new ChatOpenAI({
  openAIApiKey: process.env.INTERFAZE_API_KEY,
  configuration: { baseURL: "https://api.interfaze.ai/v1" },
  modelName: "interfaze-beta",
});

async function runInterfazeTask(taskName: string, prompt: string) {
  const structured = interfaze.withStructuredOutput({});
  const res = await structured.invoke([
    new SystemMessage(`<task>${taskName}</task>`),
    new HumanMessage(prompt),
  ]);
  return res.result;
}

const ocrTool = tool(
  async ({ url }) => JSON.stringify(await runInterfazeTask("ocr", `Extract all text and data from: ${url}`)),
  { name: "ocr", description: "Extract text and structured data from images or documents.", schema: z.object({ url: z.string() }) }
);

const webSearchTool = tool(
  async ({ query }) => JSON.stringify(await runInterfazeTask("web_search", query)),
  { name: "web_search", description: "Search the web for real-time information, news, or documentation.", schema: z.object({ query: z.string() }) }
);

const scraperTool = tool(
  async ({ url, instruction }) =>
    JSON.stringify(await runInterfazeTask("scraper", `${instruction ?? "Extract the main content from"} ${url}`)),
  { name: "scraper", description: "Extract structured content from any public web page.", schema: z.object({ url: z.string(), instruction: z.string().optional() }) }
);

const sttTool = tool(
  async ({ audio_url }) => JSON.stringify(await runInterfazeTask("speech_to_text", `Transcribe this audio: ${audio_url}`)),
  { name: "speech_to_text", description: "Transcribe audio files to text.", schema: z.object({ audio_url: z.string() }) }
);

const translateTool = tool(
  async ({ text, target_language }) =>
    JSON.stringify(await runInterfazeTask("translate", `Translate to ${target_language}: ${text}`)),
  { name: "translate", description: "Translate text between languages.", schema: z.object({ text: z.string(), target_language: z.string() }) }
);

export const interfazeTools = [ocrTool, webSearchTool, scraperTool, sttTool, translateTool];

const mainModel = new ChatOpenAI({ model: "gpt-5.4" }).bindTools(interfazeTools);

const response = await mainModel.invoke(
  "Find the latest changelog for Zod v4 and summarize what changed."
);
console.log(response.content);

language-python

tab-OpenAI SDK
import json, os
from openai import OpenAI

interfaze = OpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
)

INTERFAZE_TOOL_DEFINITIONS = [
    {"type": "function", "function": {"name": "ocr", "description": "Extract text and structured data from images or documents.", "parameters": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}}},
    {"type": "function", "function": {"name": "web_search", "description": "Search the web for real-time information, news, or documentation.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
    {"type": "function", "function": {"name": "scraper", "description": "Extract structured content from any public web page.", "parameters": {"type": "object", "properties": {"url": {"type": "string"}, "instruction": {"type": "string"}}, "required": ["url"]}}},
    {"type": "function", "function": {"name": "speech_to_text", "description": "Transcribe audio files to text.", "parameters": {"type": "object", "properties": {"audio_url": {"type": "string"}}, "required": ["audio_url"]}}},
    {"type": "function", "function": {"name": "translate", "description": "Translate text between languages.", "parameters": {"type": "object", "properties": {"text": {"type": "string"}, "target_language": {"type": "string"}}, "required": ["text", "target_language"]}}},
]

def execute_interfaze_tool(tool_name: str, args: dict) -> dict:
    prompt_map = {
        "ocr": f"Extract the title, authors, abstract, and key findings from: {args.get('url')}",
        "web_search": args.get("query"),
        "scraper": f"{args.get('instruction', 'Extract the main content from')} {args.get('url')}",
        "speech_to_text": f"Transcribe this audio: {args.get('audio_url')}",
        "translate": f"Translate to {args.get('target_language')}: {args.get('text')}",
    }

    res = interfaze.chat.completions.create(
        model="interfaze-beta",
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "empty_schema",
                "schema": {"type": "object", "properties": {}, "additionalProperties": True},
            },
        },
        messages=[
            {"role": "system", "content": f"<task>{tool_name}</task>"},
            {"role": "user", "content": prompt_map[tool_name]},
        ],
    )

    return json.loads(res.choices[0].message.content)["result"]

main_model = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def run_agent(user_message: str) -> str:
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = main_model.chat.completions.create(
            model="gpt-5.4",
            messages=messages,
            tools=INTERFAZE_TOOL_DEFINITIONS,
            tool_choice="auto",
        )

        choice = response.choices[0]

        if choice.finish_reason == "stop":
            return choice.message.content

        messages.append(choice.message)

        for call in choice.message.tool_calls or []:
            args = json.loads(call.function.arguments)
            result = execute_interfaze_tool(call.function.name, args)
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

result = run_agent("Scrape https://interfaze.ai and summarize the key features and pricing.")
print(result)

tab-LangChain SDK
import json, os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import SystemMessage, HumanMessage

interfaze = ChatOpenAI(
    api_key=os.getenv("INTERFAZE_API_KEY"),
    base_url="https://api.interfaze.ai/v1",
    model="interfaze-beta",
)

def run_interfaze_task(task_name: str, prompt: str) -> dict:
    structured = interfaze.with_structured_output(
        {"name": "empty_schema", "schema": {"type": "object", "properties": {}, "additionalProperties": True}}
    )
    res = structured.invoke([SystemMessage(content=f"<task>{task_name}</task>"), HumanMessage(content=prompt)])
    return res.get("result", res)

@tool
def ocr(url: str) -> str:
    """Extract text and structured data from images or documents."""
    return json.dumps(run_interfaze_task("ocr", f"Extract the title, authors, abstract, and key findings from: {url}"))

@tool
def web_search(query: str) -> str:
    """Search the web for real-time information, news, or documentation."""
    return json.dumps(run_interfaze_task("web_search", query))

@tool
def scraper(url: str, instruction: str = "Extract the main content from") -> str:
    """Extract structured content from any public web page."""
    return json.dumps(run_interfaze_task("scraper", f"{instruction} {url}"))

@tool
def speech_to_text(audio_url: str) -> str:
    """Transcribe audio files to text."""
    return json.dumps(run_interfaze_task("speech_to_text", f"Transcribe this audio: {audio_url}"))

@tool
def translate(text: str, target_language: str) -> str:
    """Translate text between languages."""
    return json.dumps(run_interfaze_task("translate", f"Translate to {target_language}: {text}"))

interfaze_tools = [ocr, web_search, scraper, speech_to_text, translate]

main_model = ChatOpenAI(model="gpt-5.4").bind_tools(interfaze_tools)

response = main_model.invoke(
    "Scrape https://interfaze.ai and summarize the key features and pricing."
)
print(response.content)
```

## What to build next

Adding high quality context can solve 80% of your agent's accuracy problems from extracting the document in the right format or speeding up your agent workflow by delegating compute intensive tasks to Interfaze.

For that last 20%, adding Interfaze directly into your agent pipeline using any of the major SDKs and AI frameworks will push accuracy into the 99% range and speed up your workflow by offloading compute-intensive tasks from your main model.

- Get started: [interfaze.ai/dashboard](https://interfaze.ai/dashboard)
- For copy-paste ready code across all SDKs, see the [Interfaze as Tools](https://interfaze.ai/docs/interfaze-as-tools) docs.
- Docs on run-task mode: [interfaze.ai/docs/run-tasks](https://interfaze.ai/docs/run-tasks)
- Join the Discord: [interfaze.ai/discord](https://interfaze.ai/discord)
