convert tools to openai (#6100)

This commit is contained in:
Harrison Chase 2023-06-13 10:40:49 -07:00 committed by GitHub
parent 292accde2b
commit 970b2f9d38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 0 deletions

View File

@ -9,6 +9,7 @@ from langchain.tools.azure_cognitive_services import (
from langchain.tools.base import BaseTool, StructuredTool, Tool, tool
from langchain.tools.bing_search.tool import BingSearchResults, BingSearchRun
from langchain.tools.brave_search.tool import BraveSearch
from langchain.tools.convert_to_openai import format_tool_to_openai_function
from langchain.tools.ddg_search.tool import DuckDuckGoSearchResults, DuckDuckGoSearchRun
from langchain.tools.file_management.copy import CopyFileTool
from langchain.tools.file_management.delete import DeleteFileTool
@ -122,4 +123,5 @@ __all__ = [
"YouTubeSearchTool",
"BraveSearch",
"PubmedQueryRun",
"format_tool_to_openai_function",
]

View File

@ -0,0 +1,53 @@
from typing import TypedDict
from langchain.tools import BaseTool, StructuredTool
class FunctionDescription(TypedDict):
"""Representation of a callable function to the OpenAI API."""
name: str
"""The name of the function."""
description: str
"""A description of the function."""
parameters: dict
"""The parameters of the function."""
def format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
"""Format tool into the open AI function API."""
if isinstance(tool, StructuredTool):
schema_ = tool.args_schema.schema()
# Bug with required missing for structured tools.
required = sorted(schema_["properties"]) # BUG WORKAROUND
return {
"name": tool.name,
"description": tool.description,
"parameters": {
"type": "object",
"properties": schema_["properties"],
"required": required,
},
}
else:
if tool.args_schema:
parameters = tool.args_schema.schema()
else:
parameters = {
# This is a hack to get around the fact that some tools
# do not expose an args_schema, and expect an argument
# which is a string.
# And Open AI does not support an array type for the
# parameters.
"properties": {
"__arg1": {"title": "__arg1", "type": "string"},
},
"required": ["__arg1"],
"type": "object",
}
return {
"name": tool.name,
"description": tool.description,
"parameters": parameters,
}

View File

@ -62,6 +62,7 @@ _EXPECTED = [
"YouTubeSearchTool",
"BraveSearch",
"PubmedQueryRun",
"format_tool_to_openai_function",
]