Skip to content

Instantly share code, notes, and snippets.

@TahaSh
Created August 12, 2026 16:34
Show Gist options
  • Select an option

  • Save TahaSh/4f6e2d4f468c6558df1a35338109b466 to your computer and use it in GitHub Desktop.

Select an option

Save TahaSh/4f6e2d4f468c6558df1a35338109b466 to your computer and use it in GitHub Desktop.
Code for article "How LLMs Actually Call Functions (They Don't)"
import OpenAI from 'openai'
process.loadEnvFile('.env')
const client = new OpenAI({
baseURL: 'https://api.openai.com/v1',
apiKey: process.env.OPENAI_API_KEY,
})
const send_email = ({ email, message }) => {
// code to send email
// ...
return {
status: 'success',
content: `Email sent to ${email}`,
}
}
const toolSchemas = [
{
type: 'function',
function: {
name: 'send_email',
description: 'Send an email to a given email address.',
parameters: {
type: 'object',
properties: {
email: { type: 'string' },
message: { type: 'string' },
},
required: ['email', 'message'],
},
},
},
]
const messages = [
{
role: 'user',
content: 'Send an email to test@example.com and say Hi there!',
},
]
const response = await client.chat.completions.create({
model: 'gpt-5.4-mini',
messages,
tools: toolSchemas,
})
const output = response.choices[0].message
messages.push(output)
if (output.tool_calls?.length) {
for (const call of output.tool_calls) {
// LLM is asking you to call a tool for it
const functionName = call.function.name
const args = JSON.parse(call.function.arguments)
if (functionName === 'send_email') {
const result = send_email({
email: args.email,
message: args.message,
})
// Tell the LLM about the result
messages.push({
role: 'tool',
tool_call_id: call.id,
content: JSON.stringify(result),
})
const responseAfterToolCall = await client.chat.completions.create({
model: 'gpt-5.4-mini',
messages,
tools: toolSchemas,
})
console.log(responseAfterToolCall.choices[0].message.content)
} else {
console.log(`Tool with name ${functionName} does not exist!`)
}
}
} else {
// The LLM does not need tool call. It just responded.
console.log(output.content)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment