knowapi-langchain 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ """KnowAPI tools for LangChain: official records for AI agents, with the source on every answer.
2
+
3
+ The tool list is read live from the KnowAPI MCP server (stateless Streamable HTTP, no auth to connect), so it never drifts.
4
+ Only the standard library is used for HTTP; langchain-core is needed for get_tools().
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import urllib.request
10
+ from typing import Any, Callable, Dict, List, Optional
11
+
12
+ __all__ = ["KnowAPI", "KnowAPIToolkit"]
13
+ __version__ = "0.1.0"
14
+
15
+ DEFAULT_BASE = "https://api.knowapi.dev"
16
+
17
+
18
+ class KnowAPI:
19
+ """Minimal client: list and call KnowAPI tools over MCP JSON-RPC."""
20
+
21
+ def __init__(self, base_url: str = DEFAULT_BASE, profile: str = "core", timeout: float = 60.0,
22
+ transport: Optional[Callable[[str, bytes, Dict[str, str]], bytes]] = None):
23
+ self.url = base_url.rstrip("/") + "/mcp" + ("?tools=all" if profile == "all" else "")
24
+ self.timeout = timeout
25
+ self._transport = transport
26
+ self._id = 0
27
+ self._tools: Optional[List[Dict[str, Any]]] = None
28
+
29
+ def _post(self, body: bytes) -> bytes:
30
+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "User-Agent": "knowapi-langchain/" + __version__}
31
+ if self._transport is not None:
32
+ return self._transport(self.url, body, headers)
33
+ req = urllib.request.Request(self.url, data=body, headers=headers, method="POST")
34
+ with urllib.request.urlopen(req, timeout=self.timeout) as r: # noqa: S310 (fixed https endpoint)
35
+ return r.read()
36
+
37
+ def _rpc(self, method: str, params: Optional[Dict[str, Any]] = None) -> Any:
38
+ self._id += 1
39
+ msg = {"jsonrpc": "2.0", "id": self._id, "method": method}
40
+ if params is not None:
41
+ msg["params"] = params
42
+ raw = self._post(json.dumps(msg).encode()).decode()
43
+ reply = json.loads(raw[raw.index("{"):])
44
+ if "error" in reply:
45
+ raise RuntimeError("knowapi: " + str(reply["error"].get("message")))
46
+ return reply["result"]
47
+
48
+ def list_tools(self) -> List[Dict[str, Any]]:
49
+ if self._tools is None:
50
+ self._tools = self._rpc("tools/list")["tools"]
51
+ return self._tools
52
+
53
+ def call(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> Any:
54
+ res = self._rpc("tools/call", {"name": name, "arguments": arguments or {}})
55
+ text = "\n".join(c.get("text", "") for c in res.get("content", []))
56
+ if res.get("isError"):
57
+ raise RuntimeError(text or ("knowapi: " + name + " failed"))
58
+ return res.get("structuredContent", text)
59
+
60
+ def ask(self, question: str) -> Any:
61
+ """One call answers a factual question from verified official datasets."""
62
+ return self.call("ask", {"question": question})
63
+
64
+ def request_data(self, description: str) -> Any:
65
+ """Ask KnowAPI to build a new API from public data (you become its creator)."""
66
+ return self.call("request_data", {"description": description})
67
+
68
+
69
+ class KnowAPIToolkit:
70
+ """LangChain toolkit: KnowAPIToolkit().get_tools() -> list of StructuredTool."""
71
+
72
+ def __init__(self, client: Optional[KnowAPI] = None, **kwargs: Any):
73
+ self.client = client or KnowAPI(**kwargs)
74
+
75
+ def get_tools(self) -> list:
76
+ from langchain_core.tools import StructuredTool # imported here so the client works without LangChain
77
+
78
+ tools = []
79
+ for t in self.client.list_tools():
80
+ name = t["name"]
81
+
82
+ def run(_name: str = name, **kwargs: Any) -> str:
83
+ try:
84
+ return json.dumps(self.client.call(_name, kwargs), default=str)
85
+ except Exception as e: # the model sees the error and can recover
86
+ return json.dumps({"error": str(e)})
87
+
88
+ tools.append(StructuredTool.from_function(
89
+ func=run, name=name, description=t.get("description", "")[:1024],
90
+ args_schema=t.get("inputSchema") or {"type": "object", "properties": {}},
91
+ ))
92
+ return tools
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: knowapi-langchain
3
+ Version: 0.1.0
4
+ Summary: Official records for AI agents, with the source on every answer. KnowAPI tools for LangChain and LangGraph.
5
+ License: MIT
6
+ Project-URL: Homepage, https://knowapi.dev/agents
7
+ Project-URL: Documentation, https://api.knowapi.dev/llms.txt
8
+ Keywords: langchain,langgraph,agents,mcp,public-data,official-records,knowapi
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ Requires-Dist: langchain-core>=0.3
12
+
13
+ # knowapi-langchain
14
+
15
+ Official records for AI agents, with the source on every answer: KnowAPI tools for LangChain and LangGraph.
16
+
17
+ ```python
18
+ from knowapi_langchain import KnowAPIToolkit
19
+
20
+ tools = KnowAPIToolkit().get_tools() # core tools; KnowAPIToolkit(profile="all") for every tool
21
+ # from langgraph.prebuilt import create_react_agent
22
+ # agent = create_react_agent(model, tools)
23
+ ```
24
+
25
+ Without LangChain:
26
+
27
+ ```python
28
+ from knowapi_langchain import KnowAPI
29
+ kn = KnowAPI()
30
+ kn.ask("Which medicines are currently in shortage?")
31
+ kn.request_data("Daily FDA drug recalls for pet food with brand and reason") # build it; earn when others use it
32
+ ```
33
+
34
+ **Free to start:** a starter credit shared across every API, then pay per call. A call that returns no records is not charged. The current terms are at <https://api.knowapi.dev/v2/free-allowance>.
35
+
36
+ The tool list is read live from `https://api.knowapi.dev/mcp`. Docs for agents: <https://api.knowapi.dev/llms.txt>.
@@ -0,0 +1,5 @@
1
+ knowapi_langchain/__init__.py,sha256=xqun2dZLwP4VQkVzJG0y-CJw9oiQmVI4BXcM32SXGfg,4077
2
+ knowapi_langchain-0.1.0.dist-info/METADATA,sha256=6yNcKunNxHQl3-qKAVyIQlGSoUuGkg-gVghQuVka3Yg,1436
3
+ knowapi_langchain-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ knowapi_langchain-0.1.0.dist-info/top_level.txt,sha256=28HYV5UdB7iBUR_rd2n8JBiwRr2b5wdSMCYUxJ1HfAY,18
5
+ knowapi_langchain-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ knowapi_langchain