|
1 | 1 | """Load prompts from disk."""
|
| 2 | +import importlib |
2 | 3 | import json
|
| 4 | +import tempfile |
3 | 5 | from pathlib import Path
|
4 | 6 | from typing import Union
|
5 | 7 |
|
| 8 | +import requests |
6 | 9 | import yaml
|
7 | 10 |
|
8 | 11 | from langchain.prompts.base import BasePromptTemplate
|
@@ -97,7 +100,38 @@ def load_prompt(file: Union[str, Path]) -> BasePromptTemplate:
|
97 | 100 | elif file_path.suffix == ".yaml":
|
98 | 101 | with open(file_path, "r") as f:
|
99 | 102 | config = yaml.safe_load(f)
|
| 103 | + elif file_path.suffix == ".py": |
| 104 | + spec = importlib.util.spec_from_loader( |
| 105 | + "prompt", loader=None, origin=str(file_path) |
| 106 | + ) |
| 107 | + if spec is None: |
| 108 | + raise ValueError("could not load spec") |
| 109 | + helper = importlib.util.module_from_spec(spec) |
| 110 | + with open(file_path, "rb") as f: |
| 111 | + exec(f.read(), helper.__dict__) |
| 112 | + if not isinstance(helper.PROMPT, BasePromptTemplate): |
| 113 | + raise ValueError("Did not get object of type BasePromptTemplate.") |
| 114 | + return helper.PROMPT |
100 | 115 | else:
|
101 |
| - raise ValueError |
| 116 | + raise ValueError(f"Got unsupported file type {file_path.suffix}") |
102 | 117 | # Load the prompt from the config now.
|
103 | 118 | return load_prompt_from_config(config)
|
| 119 | + |
| 120 | + |
| 121 | +URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/prompts/" |
| 122 | + |
| 123 | + |
| 124 | +def load_from_hub(path: str) -> BasePromptTemplate: |
| 125 | + """Load prompt from hub.""" |
| 126 | + suffix = path.split(".")[-1] |
| 127 | + if suffix not in {"py", "json", "yaml"}: |
| 128 | + raise ValueError("Unsupported file type.") |
| 129 | + full_url = URL_BASE + path |
| 130 | + r = requests.get(full_url) |
| 131 | + if r.status_code != 200: |
| 132 | + raise ValueError(f"Could not find file at {full_url}") |
| 133 | + with tempfile.TemporaryDirectory() as tmpdirname: |
| 134 | + file = tmpdirname + "/prompt." + suffix |
| 135 | + with open(file, "wb") as f: |
| 136 | + f.write(r.content) |
| 137 | + return load_prompt(file) |
0 commit comments