Skip to content

Commit

Permalink
core(patch): Fix encoding problem of load_prompt method (#21559)
Browse files Browse the repository at this point in the history
  • Loading branch information
liugddx authored Jun 20, 2024
1 parent 8711c61 commit 0bce28c
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions libs/core/langchain_core/prompts/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
from typing import Callable, Dict, Optional, Union

import yaml

Expand Down Expand Up @@ -125,18 +125,22 @@ def _load_prompt(config: dict) -> PromptTemplate:
return PromptTemplate(**config)


def load_prompt(path: Union[str, Path]) -> BasePromptTemplate:
def load_prompt(
path: Union[str, Path], encoding: Optional[str] = None
) -> BasePromptTemplate:
"""Unified method for loading a prompt from LangChainHub or local fs."""
if isinstance(path, str) and path.startswith("lc://"):
raise RuntimeError(
"Loading from the deprecated github-based Hub is no longer supported. "
"Please use the new LangChain Hub at https://smith.langchain.com/hub "
"instead."
)
return _load_prompt_from_file(path)
return _load_prompt_from_file(path, encoding)


def _load_prompt_from_file(file: Union[str, Path]) -> BasePromptTemplate:
def _load_prompt_from_file(
file: Union[str, Path], encoding: Optional[str] = None
) -> BasePromptTemplate:
"""Load prompt from file."""
# Convert file to a Path object.
if isinstance(file, str):
Expand All @@ -145,10 +149,10 @@ def _load_prompt_from_file(file: Union[str, Path]) -> BasePromptTemplate:
file_path = file
# Load from either json or yaml.
if file_path.suffix == ".json":
with open(file_path) as f:
with open(file_path, encoding=encoding) as f:
config = json.load(f)
elif file_path.suffix.endswith((".yaml", ".yml")):
with open(file_path, "r") as f:
with open(file_path, mode="r", encoding=encoding) as f:
config = yaml.safe_load(f)
else:
raise ValueError(f"Got unsupported file type {file_path.suffix}")
Expand Down

0 comments on commit 0bce28c

Please sign in to comment.