1
1
"""Functionality for loading agents."""
2
2
import json
3
+ import os
4
+ import tempfile
3
5
from pathlib import Path
4
6
from typing import Any , Union
5
7
8
+ import requests
6
9
import yaml
7
10
8
11
from langchain .agents .agent import Agent
19
22
"conversational-react-description" : ConversationalAgent ,
20
23
}
21
24
25
+ URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/"
26
+
22
27
23
28
def load_agent_from_config (config : dict , ** kwargs : Any ) -> Agent :
24
29
"""Load agent from Config Dict."""
@@ -40,7 +45,32 @@ def load_agent_from_config(config: dict, **kwargs: Any) -> Agent:
40
45
return agent_cls (** combined_config ) # type: ignore
41
46
42
47
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 :
44
74
"""Load agent from file."""
45
75
# Convert file to Path object.
46
76
if isinstance (file , str ):
0 commit comments