# Function / Tool Calling

URL: https://interfaze.ai/docs/function-calling

Function Calling (also known as Tool Calling) lets Interfaze invoke external tools and APIs giving access to new
functionality and data.

Interfaze supports [OpenAI-compatible function schemas](https://developers.openai.com/api/docs/guides/function-calling?api-mode=chat) so you can use all existing MCPs, tools the same way with any AI SDK.

## Examples

```tabs
language-typescript

tab-OpenAI SDK
// 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);
}

tab-LangChain SDK
// 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: tools,
		tool_choice: "auto",
	},
);

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

	// Execute the function
	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: tools,
			tool_choice: "auto",
		},
	);

	console.log("Final response:", finalResponse.content);
}
tab-Vercel AI SDK
import { generateText, tool, stepCountIs } from "ai";
import { z } from "zod";

const response = await generateText({
	model: interfaze.chat("interfaze-beta"),
	messages: [
		{
			role: "user",
			content:
				"Get the user info for user with user_id 123",
		},
	],
	tools: {
		get_user_info: tool({
			description: "Get the user info from the database",
			inputSchema: z.object({ user_id: z.string() }),
			outputSchema: z.string(),
			execute: async ({ user_id }) => {
				return `User info for user ${user_id}`;
			},
		}),
	},
	toolChoice: "auto",
	stopWhen: stepCountIs(5),
	maxRetries: 3,
});

console.log(response.text);
language-python

tab-OpenAI SDK
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")
tab-LangChain SDK
import json

# STEP 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"],
            },
        },
    },
]

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)
else:
    print("No tool calls were made")
```
