> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stophy.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI

> Give an OpenAI model live web search with Stophy: define a tool, run the call when the model asks for it, and return the results as JSON.

## Setup

```bash theme={null}
npm install openai
```

Set `OPENAI_API_KEY` in your environment. `STOPHY_API_KEY` is optional for this example.

## The Stophy tool

This function calls Google search and returns the results as JSON, limited to 5 so the model's context stays small. It reads your key from `STOPHY_API_KEY`, and works without one.

```ts stophy.ts theme={null}
export async function stophySearch(query: string): Promise<string> {
  const headers: Record<string, string> = { "content-type": "application/json" };
  if (process.env.STOPHY_API_KEY) headers.authorization = `Bearer ${process.env.STOPHY_API_KEY}`;
  const response = await fetch("https://api.stophy.dev/v1/google/search", {
    method: "POST",
    headers,
    body: JSON.stringify({ query }),
  });
  const body = await response.json();
  if (!body.success) throw new Error(body.error.message);
  return JSON.stringify(body.data.results);
}
```

## Use it as a tool

Pass the function as a tool to the Responses API. When the model calls it, run the search and send the result back.

```ts theme={null}
import OpenAI from "openai";
import { stophySearch } from "./stophy";

const openai = new OpenAI();

const tools: OpenAI.Responses.Tool[] = [
  {
    type: "function",
    name: "web_search",
    description: "Search the web. Returns the top results as JSON.",
    parameters: {
      type: "object",
      properties: { query: { type: "string", description: "What to search for" } },
      required: ["query"],
      additionalProperties: false,
    },
    strict: true,
  },
];

let response = await openai.responses.create({
  model: "gpt-5-mini",
  input: "What changed in the latest Bun release?",
  tools,
});

while (true) {
  const calls = response.output.filter((item) => item.type === "function_call");
  if (calls.length === 0) break;
  const outputs: OpenAI.Responses.ResponseInputItem[] = [];
  for (const call of calls) {
    const { query } = JSON.parse(call.arguments) as { query: string };
    outputs.push({ type: "function_call_output", call_id: call.call_id, output: await stophySearch(query) });
  }
  response = await openai.responses.create({
    model: "gpt-5-mini",
    previous_response_id: response.id,
    input: outputs,
    tools,
  });
}

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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.