Source code for langchain_community.agent_toolkits.openapi.spec
"""Quick and dirty representation for OpenAPI specs."""fromdataclassesimportdataclassfromtypingimportList,Tuplefromlangchain_core.utils.json_schemaimportdereference_refs
[docs]@dataclass(frozen=True)classReducedOpenAPISpec:"""A reduced OpenAPI spec. This is a quick and dirty representation for OpenAPI specs. Parameters: servers: The servers in the spec. description: The description of the spec. endpoints: The endpoints in the spec. """servers:List[dict]description:strendpoints:List[Tuple[str,str,dict]]
[docs]defreduce_openapi_spec(spec:dict,dereference:bool=True)->ReducedOpenAPISpec:"""Simplify/distill/minify a spec somehow. I want a smaller target for retrieval and (more importantly) I want smaller results from retrieval. I was hoping https://openapi.tools/ would have some useful bits to this end, but doesn't seem so. Args: spec: The OpenAPI spec. dereference: Whether to dereference the spec. Default is True. Returns: ReducedOpenAPISpec: The reduced OpenAPI spec. """# 1. Consider only get, post, patch, put, delete endpoints.endpoints=[(f"{operation_name.upper()}{route}",docs.get("description"),docs)forroute,operationinspec["paths"].items()foroperation_name,docsinoperation.items()ifoperation_namein["get","post","patch","put","delete"]]# 2. Replace any refs so that complete docs are retrieved.# Note: probably want to do this post-retrieval, it blows up the size of the spec.ifdereference:endpoints=[(name,description,dereference_refs(docs,full_schema=spec))forname,description,docsinendpoints]# 3. Strip docs down to required request args + happy path response.defreduce_endpoint_docs(docs:dict)->dict:out={}ifdocs.get("description"):out["description"]=docs.get("description")ifdocs.get("parameters"):out["parameters"]=[parameterforparameterindocs.get("parameters",[])ifparameter.get("required")]if"200"indocs["responses"]:out["responses"]=docs["responses"]["200"]ifdocs.get("requestBody"):out["requestBody"]=docs.get("requestBody")returnoutendpoints=[(name,description,reduce_endpoint_docs(docs))forname,description,docsinendpoints]returnReducedOpenAPISpec(servers=spec["servers"],description=spec["info"].get("description",""),endpoints=endpoints,)