# Function / Tool Calling

URL: https://interfaze-landing-1am6r0242-jigsaw-stack.vercel.app/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

**Interfaze SDK · typescript**

```typescript
import type { ChatCompletionMessageParam, ChatCompletionTool } from "interfaze";

// STEP 1. Define a list of callable tools for the model
const tools: ChatCompletionTool[] = [
	{
		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"],
			},
		},
	},
];

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

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

// Step 3: Extract tool call and execute function
const assistantMessage = response.choices[0]?.message;
if (assistantMessage) messages.push(assistantMessage); // the assistant turn, carrying any tool_calls

for (const toolCall of assistantMessage?.tool_calls ?? []) {
	if (toolCall.type !== "function") continue;
	const args = JSON.parse(toolCall.function.arguments);

	messages.push({
		role: "tool",
		tool_call_id: toolCall.id,
		content: `Today's horoscope for ${args.sign}: You will have a great day!`,
	});
}

// Step 4: Send the tool results back for the final answer
const finalResponse = await interfaze.chat.completions.create({
	messages,
	tools,
	tool_choice: "auto",
});

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

**LangChain SDK · typescript**

```typescript
import { HumanMessage, ToolMessage } from "@langchain/core/messages";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

// STEP 1. Define tools
const getHoroscope = tool(
	async ({ sign }) => `Today's horoscope for ${sign}: You will have a great day!`,
	{
		name: "get_horoscope",
		description: "Get today's horoscope for an astrological sign.",
		schema: z.object({
			sign: z.string().describe("An astrological sign like Taurus or Aquarius"),
		}),
	}
);

const interfazeWithTools = interfaze.bindTools([getHoroscope]);

// Step 2: Get tool call from model
const messages = [new HumanMessage("Get my horoscope for Taurus")];
const response = await interfazeWithTools.invoke(messages);

// Step 3: Execute the tool and pass the result back to the model
for (const toolCall of response.tool_calls ?? []) {
	const result = await getHoroscope.invoke(toolCall);
	messages.push(response, result as ToolMessage);
}

// Step 4: Send the tool results back for the final answer
const finalResponse = await interfazeWithTools.invoke(messages);

console.log("Final response:", finalResponse.content);
```

**Vercel AI SDK · typescript**

```typescript
import { generateText, tool, stepCountIs } from "ai";
import { z } from "zod";

const response = await generateText({
	model: interfaze("interfaze-1"),
	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);
```

**Interfaze 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(
    messages=input_list,
    tools=tools,
    tool_choice="auto",
)

message = response.choices[0].message

# Save the assistant turn, carrying any tool_calls, for subsequent requests
input_list.append(message.model_dump())

if message.tool_calls:
    function_call = 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(
        messages=input_list,
        tools=tools,
        tool_choice="auto",
    )

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

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool

# STEP 1. Define tools
@tool
def get_horoscope(sign: str) -> str:
    """Get today's horoscope for an astrological sign."""
    return f"Today's horoscope for {sign}: You will have a great day!"

interfaze_with_tools = interfaze.bind_tools([get_horoscope])

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

# Step 3: Execute the tool and pass the result back to the model
for tool_call in response.tool_calls:
    messages.append(get_horoscope.invoke(tool_call))

# Step 4: Get the final response from the model
final_response = interfaze_with_tools.invoke(messages)

print(final_response.content)
```
