Skip to content

Commit 12dc7f2

Browse files
authored
load agents from hub (#759)
1 parent 7129f23 commit 12dc7f2

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

langchain/agents/loading.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"""Functionality for loading agents."""
22
import json
3+
import os
4+
import tempfile
35
from pathlib import Path
46
from typing import Any, Union
57

8+
import requests
69
import yaml
710

811
from langchain.agents.agent import Agent
@@ -19,6 +22,8 @@
1922
"conversational-react-description": ConversationalAgent,
2023
}
2124

25+
URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/"
26+
2227

2328
def load_agent_from_config(config: dict, **kwargs: Any) -> Agent:
2429
"""Load agent from Config Dict."""
@@ -40,7 +45,32 @@ def load_agent_from_config(config: dict, **kwargs: Any) -> Agent:
4045
return agent_cls(**combined_config) # type: ignore
4146

4247

43-
def load_agent(file: Union[str, Path], **kwargs: Any) -> Agent:
48+
def load_agent(path: Union[str, Path], **kwargs: Any) -> Agent:
49+
"""Unified method for loading a agent from LangChainHub or local fs."""
50+
if isinstance(path, str) and path.startswith("lc://agents"):
51+
path = os.path.relpath(path, "lc://agents/")
52+
return _load_from_hub(path, **kwargs)
53+
else:
54+
return _load_agent_from_file(path, **kwargs)
55+
56+
57+
def _load_from_hub(path: str, **kwargs: Any) -> Agent:
58+
"""Load agent from hub."""
59+
suffix = path.split(".")[-1]
60+
if suffix not in {"json", "yaml"}:
61+
raise ValueError("Unsupported file type.")
62+
full_url = URL_BASE + path
63+
r = requests.get(full_url)
64+
if r.status_code != 200:
65+
raise ValueError(f"Could not find file at {full_url}")
66+
with tempfile.TemporaryDirectory() as tmpdirname:
67+
file = tmpdirname + "/agent." + suffix
68+
with open(file, "wb") as f:
69+
f.write(r.content)
70+
return _load_agent_from_file(file)
71+
72+
73+
def _load_agent_from_file(file: Union[str, Path], **kwargs: Any) -> Agent:
4474
"""Load agent from file."""
4575
# Convert file to Path object.
4676
if isinstance(file, str):

0 commit comments

Comments
 (0)