# OpenAI SDK Integration

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

Interfaze supports the Chat Completion API standard, so you can use it out of the box by easily adding Interfaze's base URL and API key to your code.

## Installation

**npm / yarn · typescript**

```typescript
npm install openai
# or
yarn add openai
```

**pip · python**

```python
pip install openai
```

## Official Documentation

- [OpenAI API Reference](https://platform.openai.com/docs/api-reference)
- [OpenAI Node.js SDK](https://github.com/openai/openai-node)
- [OpenAI Python SDK](https://github.com/openai/openai-python)

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

## Basic Setup

**OpenAI SDK · typescript**

```typescript
import OpenAI from "openai";

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

**OpenAI SDK · python**

```python
from openai import OpenAI

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

## Examples

### Text Generation

**OpenAI SDK · typescript**

```typescript
const completion = await interfaze.chat.completions.create({
  model: "interfaze-beta",
  messages: [
    { role: "user", content: "Write a short story about a robot learning to paint" }
  ]
});

console.log(completion.choices[0].message.content);
```

**OpenAI SDK · python**

```python
completion = interfaze.chat.completions.create(
    model="interfaze-beta",
    messages=[
        {"role": "user", "content": "Write a short story about a robot learning to paint"}
    ]
)

print(completion.choices[0].message.content)
```

### Structured Output

Learn more about [structured output](https://interfaze.ai/docs/structured-output).

**OpenAI SDK · typescript**

```typescript
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/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 response = await interfaze.chat.completions.create({
  model: "interfaze-beta",
  messages: [
    {
      role: "user",
      content: "What is the current weather in Tokyo?",
    },
  ],
  response_format: zodResponseFormat(weatherSchema, "weather_schema"),
});

console.log(response.choices[0].message.content);
```

**OpenAI 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")

response = interfaze.chat.completions.create(
    model="interfaze-beta",
    messages=[
        {
            "role": "user",
            "content": "What is the current weather in Tokyo?",
        }
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "weather_schema",
            "schema": WeatherSchema.model_json_schema(),
        }
    },
)

print(response.choices[0].message.content)
```

### Image / File Input

**OpenAI SDK · typescript**

```typescript
const response = await interfaze.chat.completions.create({
  model: "interfaze-beta",
  messages: [
    {
      role: "user",
      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.choices[0].message.content);
```

**OpenAI SDK · python**

```python
response = interfaze.chat.completions.create(
    model="interfaze-beta",
    messages=[
        {
            "role": "user",
            "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.choices[0].message.content)
```

### Streaming

Learn more about [streaming](https://interfaze.ai/docs/streaming).

**OpenAI SDK · typescript**

```typescript
const stream = await interfaze.chat.completions.create({
  model: "interfaze-beta",
  messages: [
    { role: "user", content: "Write a short story about a robot learning to paint" }
  ],
  stream: true
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) {
    process.stdout.write(content);
  }
}
```

**OpenAI SDK · python**

```python
stream = interfaze.chat.completions.create(
    model="interfaze-beta",
    messages=[
        {"role": "user", "content": "Write a short story about a robot learning to paint"}
    ],
    stream=True
)

for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if delta and delta.content is not None:
        print(delta.content, end="", flush=True)
```

### Function Calling

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

**OpenAI SDK · typescript**

```typescript
// STEP 1. Define a list of callable tools for the model
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"],
			},
		},
	},
];

let messages: any[] = [
	{
		role: "user" as const,
		content: "Get my horoscope for Taurus",
	},
];

// Step 2: Get tool call from model
const response = await interfaze.chat.completions.create({
	model: "interfaze-beta",
	messages,
	tools,
	tool_choice: "auto",
});

// Step 3: Extract tool call and execute function
const assistantMessage = response.choices[0].message;

messages.push({
	role: "assistant",
	content: "",
	tool_calls: response.choices[0].message.tool_calls,
});

if (assistantMessage.tool_calls && assistantMessage.tool_calls.length > 0) {
	const toolCall = assistantMessage.tool_calls[0] as any;
	const args = JSON.parse(toolCall.function.arguments);

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

	messages.push({
		role: "tool" as const,
		tool_call_id: toolCall.id,
		content: result,
	});

	const finalResponse = await interfaze.chat.completions.create({
		model: "interfaze-beta",
		messages,
		tools,
		tool_choice: "auto",
	});

	console.log(finalResponse.choices[0].message.content);
}
```

**OpenAI SDK · python**

```python
import json

# 1. Define a list of callable tools for the model
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"],
            },
        },
    },
]

# Create a running input list we will add to over time
input_list = [
    {"role": "user", "content": "Get my horoscope for Taurus"}
]

# 2. Prompt the model with tools defined
response = interfaze.chat.completions.create(
    model="interfaze-beta",
    messages=input_list,
    tools=tools,
    tool_choice="auto",
)

# Save function call outputs for subsequent requests
input_list.append(response.choices[0].message)

if response.choices[0].message.tool_calls:
    function_call = response.choices[0].message.tool_calls[0]
    function_call_arguments = json.loads(function_call.function.arguments)

    # 3. Execute the function logic
    result = f"Today's horoscope for {function_call_arguments['sign']}: You will have a great day!"

    # 4. Provide function call results to the model
    input_list.append({
        "role": "tool",
        "tool_call_id": function_call.id,
        "content": result,
    })

    # 5. Get final response from the model
    response = interfaze.chat.completions.create(
        model="interfaze-beta",
        messages=input_list,
        tools=tools,
        tool_choice="auto",
    )

    print(response.choices[0].message.content)
else:
    print("No tool calls were made")
```
