{"id":25431018,"url":"https://github.com/johannlai/openai-function-calling-tools","last_synced_at":"2025-04-05T09:08:43.169Z","repository":{"id":175780527,"uuid":"654452138","full_name":"JohannLai/openai-function-calling-tools","owner":"JohannLai","description":"🛠 openai function calling tools for JS/TS","archived":false,"fork":false,"pushed_at":"2024-01-30T14:06:52.000Z","size":436,"stargazers_count":293,"open_issues_count":4,"forks_count":28,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-03-29T08:05:26.073Z","etag":null,"topics":["function-calling","functions","javascript","openai","openai-api","tools"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohannLai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-16T06:54:27.000Z","updated_at":"2025-03-27T02:13:04.000Z","dependencies_parsed_at":"2025-02-24T04:01:28.745Z","dependency_job_id":"7f7b4a8b-10da-4456-9210-4a0eef2e8b0e","html_url":"https://github.com/JohannLai/openai-function-calling-tools","commit_stats":null,"previous_names":["johannlai/openai-function-calling-tools"],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohannLai%2Fopenai-function-calling-tools","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohannLai%2Fopenai-function-calling-tools/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohannLai%2Fopenai-function-calling-tools/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohannLai%2Fopenai-function-calling-tools/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohannLai","download_url":"https://codeload.github.com/JohannLai/openai-function-calling-tools/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247312080,"owners_count":20918344,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["function-calling","functions","javascript","openai","openai-api","tools"],"created_at":"2025-02-17T03:48:48.132Z","updated_at":"2025-04-05T09:08:43.120Z","avatar_url":"https://github.com/JohannLai.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg height=\"129\" align=\"left\" src=\"assets/logo.png\" alt=\"Logo\"\u003e\n\n# OpenAI Function calling tools\n\n\n\u003ca href=\"https://www.npmjs.com/package/openai-function-calling-tools\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/openai-function-calling-tools\" alt=\"Current version\"\u003e\u003c/a\u003e\n[![LICENSE](https://img.shields.io/github/license/JohannLai/openai-function-calling-tools)](https://github.com/JohannLai/openai-function-calling-tools/blob/main/LICENSE)\n[![codecov](https://codecov.io/github/JohannLai/openai-function-calling-tools/branch/main/graph/badge.svg?token=G85I4DWX8Q)](https://codecov.io/github/JohannLai/openai-function-calling-tools)\n\u003cimg src=\"https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg\" alt=\"semantic-release\"\u003e\n\u003cimg src=\"https://img.shields.io/badge/PRs-welcome-brightgreen.svg\" alt=\"PRs welcome\"\u003e\n---\n\nOpenAI Function calling tools\n\nOpenAI Function calling tools is a repository that offers a set of tools to help you easy to build a function calling model with OpenAI API.\n\n[More information about function calling](https://platform.openai.com/docs/guides/gpt/function-calling)\n\nSample: https://chatFn.io\n\n\u003cimg width=\"1387\" alt=\"image\" src=\"https://github.com/JohannLai/openai-function-calling-tools/assets/10769405/cc0f8565-d556-4325-afb6-bfefe912cc87\"\u003e\n\n\n## 🪓 Tools\nThe repo provides the following tools you can use out of the box:\n\n- 🗺️ ShowPoisOnMap: A tool that can show points of interest on a map.\n- 🌐 ReverseGeocode: A tool that can convert coordinates into a human-readable address.\n- ⏰ Clock: A clock that can tell you the time.\n- 🧮 Calculator: A simple calculator that can do basic arithmetic. Input should be a math expression.\n- 🔍 GoogleCustomSearch: A wrapper around the Google Custom Search API. Useful for when you need to answer questions about current events. Input should be a search query.\n- 🔍 BingCustomSearch: A wrapper around the Bing Custom Search API. Useful for when you need to answer questions about current events. Input should be a search query.\n- 🔍 SerperCustomSearch: A wrapper around the SerpAPI. Useful for when you need to answer questions about current events. Input should be a search query.\n- 🏞️ SerperImagesSearch: Use SerpAPI to search images. Input should be a search query.\n- 📁 fs: WriteFileTool abd ReadFileTool access to the file system. Input should be a file path and text written to the file.\n- 🪩 webbrowser: A web browser that can open a website. Input should be a URL.\n- 🚧 sql: Input to this tool is a detailed and correct SQL query, output is a result from the database.\n- 🚧 JavaScriptInterpreter: A JavaScript interpreter. Input should be a JavaScript program string.\n\n\u003e You can use `{ Tool }` factory function to create a tool instance. See `/tools` for more examples.\n\n\n## 📦 Quick Install\n\n  ```bash\n  npm install openai-function-calling-tools\n  ```\n\n## 📖 Usage\n\n### Example 1: Function Calls\n\nuse JavaScriptInterpreter to calculate 0.1 + 0.2\n\n```js\nimport { Configuration, OpenAIApi } from \"openai\";\nimport { createCalculator } from \"openai-function-calling-tools\"\n\nconst configuration = new Configuration({\n    apiKey: process.env.OPENAI_API_KEY,\n  });\nconst openai = new OpenAIApi(configuration);\n\nconst QUESTION = \"What is 100*2?\";\n\nconst messages = [\n  {\n    role: \"user\",\n    content: QUESTION,\n  },\n];\n\n# ✨ STEP 1: new the tools you want to use\nconst [calculator, calculatorSchema] = createCalculator();\n\n# ✨ STEP 2:  add the tools to the functions object\nconst functions = {\n  calculator,\n};\n\nconst getCompletion = async (messages) =\u003e {\n  const response = await openai.createChatCompletion({\n    model: \"gpt-3.5-turbo-0613\",\n    messages,\n    # ✨ STEP 3: add the tools to the schema\n    functions: [calculatorSchema],\n    temperature: 0,\n  });\n\n  return response;\n};\n\nconsole.log(\"Question: \" + QUESTION);\nlet response = await getCompletion(messages);\n\nif (response.data.choices[0].finish_reason === \"function_call\") {\n  const fnName = response.data.choices[0].message.function_call.name;\n  const args = response.data.choices[0].message.function_call.arguments;\n\n  console.log(\"Function call: \" + fnName);\n  console.log(\"Arguments: \" + args);\n\n  # ✨ STEP 4: call the function\n  const fn = functions[fnName];\n  const result = fn(JSON.parse(args));\n\n  console.log(\"Calling Function Result: \" + result);\n\n  messages.push({\n    role: \"assistant\",\n    content: null,\n    function_call: {\n      name: fnName,\n      arguments: args,\n    },\n  });\n\n  messages.push({\n    role: \"function\",\n    name: fnName,\n    content: JSON.stringify({ result: result }),\n  });\n\n  // call the completion again\n  response = await getCompletion(messages);\n\n  console.log(response.data.choices[0].message.content);\n}\n```\n\n### Example 2: Function Calls with Google Custom Search\n\n\u003e 📝 Note: You need to apply for a Google Custom Search API key and a Google Custom Search Engine ID to use this tool.\n\n#### The following is a sequence diagram of the example\n```mermaid\nsequenceDiagram\n  participant U as User\n  participant M as Main Function\n  participant O as OpenAI API\n  participant F as Functions Object\n  participant GC as Google Custom Search\n\n  U-\u003e\u003eM: Execute main function\n  M-\u003e\u003eM: Initialize configuration and API\n  M-\u003e\u003eM: Define QUESTION variable\n  M-\u003e\u003eM: Create Google Custom Search tool\n  M-\u003e\u003eF: Add tool to functions object\n  loop Chat Completion Loop\n      M-\u003e\u003eO: Request chat completion\n      O--\u003e\u003eM: Return response\n      alt If finish reason is \"stop\"\n          M-\u003e\u003eU: Display answer and exit loop\n      else If finish reason is \"function_call\"\n          M-\u003e\u003eM: Parse function call name and arguments\n          M-\u003e\u003eF: Invoke corresponding function\n          F-\u003e\u003eGC: Perform Google Custom Search\n          GC--\u003e\u003eF: Return search results\n          F-\u003e\u003eM: Receive function result\n          M-\u003e\u003eM: Add result to message queue\n          M-\u003e\u003eM: Output function call details\n      else Other cases\n          M-\u003e\u003eM: Continue loop\n      end\n  end\n```\n#### Code\n\n```js\nconst { Configuration, OpenAIApi } = require(\"openai\");\nconst { createGoogleCustomSearch } = require(\"openai-function-calling-tools\");\n\nconst main = async () =\u003e {\n  const configuration = new Configuration({\n    apiKey: process.env.OPENAI_API_KEY,\n  });\n  const openai = new OpenAIApi(configuration);\n\n  const QUESTION = \"How many tesla model 3 sale in 2022?\"\n\n  const messages = [\n    {\n      role: \"user\",\n      content: QUESTION,\n    },\n  ];\n\n  // ✨ STEP 1: new the tools you want to use\n  const [googleCustomSearch, googleCustomSearchSchema] =\n    createGoogleCustomSearch({\n      apiKey: process.env.GOOGLE_API_KEY,\n      googleCSEId: process.env.GOOGLE_CSE_ID,\n    });\n\n\n  // ✨ STEP 2:  add the tools to the functions object\n  const functions = {\n    googleCustomSearch,\n  };\n\n  const getCompletion = async (messages) =\u003e {\n    const response = await openai.createChatCompletion({\n      model: \"gpt-3.5-turbo-0613\",\n      messages,\n      // ✨ STEP 3: add the tools schema to the functions parameter\n      functions: [googleCustomSearchSchema],\n      temperature: 0,\n    });\n\n    return response;\n  };\n  let response;\n\n  console.log(\"Question: \" + QUESTION);\n\n  while (true) {\n    response = await getCompletion(messages);\n\n    if (response.data.choices[0].finish_reason === \"stop\") {\n      console.log(response.data.choices[0].message.content);\n      break;\n    } else if (response.data.choices[0].finish_reason === \"function_call\") {\n      const fnName = response.data.choices[0].message.function_call.name;\n      const args = response.data.choices[0].message.function_call.arguments;\n\n      const fn = functions[fnName];\n      const result = await fn(JSON.parse(args));\n\n      console.log(`Function call: ${fnName}, Arguments: ${args}`);\n      console.log(`Calling Function ${fnName} Result: ` + result);\n\n      messages.push({\n        role: \"assistant\",\n        content: \"\",\n        function_call: {\n          name: fnName,\n          arguments: args,\n        },\n      });\n\n      messages.push({\n        role: \"function\",\n        name: fnName,\n        content: JSON.stringify({ result: result }),\n      });\n    }\n  }\n};\n\nmain();\n```\n\n\n### Example 3: Schema Extraction\n\nExample to extract schema from a function call\n\nTree structure:\n\n```js\nimport { Configuration, OpenAIApi } from \"openai\";\n\nconst configuration = new Configuration({\n  apiKey: process.env.OPENAI_API_KEY,\n});\nconst openai = new OpenAIApi(configuration);\n\nconst getCompletion = async (messages) =\u003e {\n  const response = await openai.createChatCompletion({\n    model: \"gpt-3.5-turbo-0613\",\n    messages: [\n      {\n        role: \"user\",\n        content: `root\n              ├── folder1\n              │   ├── file1.txt\n              │   └── file2.txt\n              └── folder2\n                  ├── file3.txt\n                      └── subfolder1\n                              └── file4.txt`\n      },\n    ],\n    functions: [\n      {\n        \"name\": \"buildTree\",\n        \"description\": \"build a tree structure\",\n        \"parameters\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"name\": {\n              \"type\": \"string\",\n              \"description\": \"The name of the node\"\n            },\n            \"children\": {\n              \"type\": \"array\",\n              \"description\": \"The tree nodes\",\n              \"items\": {\n                \"$ref\": \"#\"\n              }\n            },\n            \"type\": {\n              \"type\": \"string\",\n              \"description\": \"The type of the node\",\n              \"enum\": [\n                \"file\",\n                \"folder\"\n              ]\n            }\n          },\n          \"required\": [\n            \"name\",\n            \"children\",\n            \"type\"\n          ]\n        }\n      }\n    ],\n    temperature: 0,\n  });\n\n  return response;\n};\n\nlet response = await getCompletion();\n\nif (response.data.choices[0].finish_reason === \"function_call\") {\n  const args = response.data.choices[0].message.function_call.arguments;\n  // 🌟 output the Tree structure data\n  console.log(args);\n}\n```\n\n## 💻 Supported Environments\n- Node.js v16 or higher\n- Cloudflare Workers\n- Vercel / Next.js (Backend, Serverless and Edge functions 🔥)\n- Supabase Edge Functions\n- 🚧 Browser\n\n## 🛡️ Safe for Production\n[![Security Status](https://www.murphysec.com/platform3/v31/badge/1671046841000607744.svg)](https://www.murphysec.com/console/report/1671046840954470400/1671046841000607744)\n\n## 🌟 Inspiration\n- LangChainAI\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohannlai%2Fopenai-function-calling-tools","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohannlai%2Fopenai-function-calling-tools","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohannlai%2Fopenai-function-calling-tools/lists"}