id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
b61218194d0e-1
"""Total probability mass of tokens to consider at each step.""" top_k: int = 50 """The number of highest probability tokens to keep for top-k filtering.""" repetition_penalty: float = 1.0 """Penalizes repeated tokens. 1.0 means no penalty.""" length_penalty: float = 1.0 """Exponential penalty t...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
b61218194d0e-2
@property def _default_params(self) -> Mapping[str, Any]: """Get the default parameters for calling NLPCloud API.""" return { "temperature": self.temperature, "min_length": self.min_length, "max_length": self.max_length, "length_no_input": self.length_...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
b61218194d0e-3
The string generated by the model. Example: .. code-block:: python response = nlpcloud("Tell me a joke.") """ if stop and len(stop) > 1: raise ValueError( "NLPCloud only supports a single stop sequence per generation." "Pass...
https://python.langchain.com/en/latest/_modules/langchain/llms/nlpcloud.html
0c3a20467387-0
Source code for langchain.llms.ctransformers """Wrapper around the C Transformers library.""" from typing import Any, Dict, Optional, Sequence from pydantic import root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM [docs]class CTransformers(LLM): """W...
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
0c3a20467387-1
"config": self.config, } @property def _llm_type(self) -> str: """Return type of llm.""" return "ctransformers" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that ``ctransformers`` package is installed.""" try: from...
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
0c3a20467387-2
text.append(chunk) _run_manager.on_llm_new_token(chunk, verbose=self.verbose) return "".join(text) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/ctransformers.html
6cbaabe87e86-0
Source code for langchain.llms.huggingface_endpoint """Wrapper around HuggingFace APIs.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import Extra, root_validator from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.llms.base import LLM from langchain....
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
6cbaabe87e86-1
huggingfacehub_api_token: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" hugging...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
6cbaabe87e86-2
return "huggingface_endpoint" def _call( self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, ) -> str: """Call out to HuggingFace Hub's inference endpoint. Args: prompt: The prompt to pass into t...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
6cbaabe87e86-3
elif self.task == "summarization": text = generated_text[0]["summary_text"] else: raise ValueError( f"Got invalid task {self.task}, " f"currently only {VALID_TASKS} are supported" ) if stop is not None: # This is a bit hacky...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html
ec486957182e-0
Source code for langchain.llms.anthropic """Wrapper around Anthropic APIs.""" import re import warnings from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union from pydantic import BaseModel, Extra, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMR...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ec486957182e-1
anthropic_api_key = get_from_dict_or_env( values, "anthropic_api_key", "ANTHROPIC_API_KEY" ) try: import anthropic values["client"] = anthropic.Client( api_key=anthropic_api_key, default_request_timeout=values["default_request_timeout"]...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ec486957182e-2
if stop is None: stop = [] # Never want model to invent new turns of Human / Assistant dialog. stop.extend([self.HUMAN_PROMPT]) return stop [docs]class Anthropic(LLM, _AnthropicCommon): r"""Wrapper around Anthropic's large language models. To use, you should have the ``anthro...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ec486957182e-3
extra = Extra.forbid @property def _llm_type(self) -> str: """Return type of llm.""" return "anthropic-llm" def _wrap_prompt(self, prompt: str) -> str: if not self.HUMAN_PROMPT or not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") ...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ec486957182e-4
if self.streaming: stream_resp = self.client.completion_stream( prompt=self._wrap_prompt(prompt), stop_sequences=stop, **self._default_params, ) current_completion = "" for data in stream_resp: delta = data["...
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
ec486957182e-5
**self._default_params, ) return response["completion"] [docs] def stream(self, prompt: str, stop: Optional[List[str]] = None) -> Generator: r"""Call Anthropic completion_stream and return the resulting generator. BETA: this is a beta feature while we figure out the right abstraction....
https://python.langchain.com/en/latest/_modules/langchain/llms/anthropic.html
3f9b725500cf-0
Source code for langchain.llms.rwkv """Wrapper for the RWKV model. Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py """ from typing import Any, Dict, List, Mapping, Optional, Set from pydantic import BaseModel, Extra, roo...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
3f9b725500cf-1
"""Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim..""" penalty_alpha_presence: float = 0.4 """Positive values penalize new tokens based on whether they appear in the text so far, increasing ...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
3f9b725500cf-2
"""Validate that the python package exists in the environment.""" try: import tokenizers except ImportError: raise ImportError( "Could not import tokenizers python package. " "Please install it with `pip install tokenizers`." ) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
3f9b725500cf-3
AVOID_REPEAT_TOKENS = [] AVOID_REPEAT = ",:?!" for i in AVOID_REPEAT: dd = self.pipeline.encode(i) assert len(dd) == 1 AVOID_REPEAT_TOKENS += dd tokens = [int(x) for x in _tokens] self.model_tokens += tokens out: Any = None while len(to...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
3f9b725500cf-4
occurrence[token] += 1 logits = self.run_rnn([token]) xxx = self.tokenizer.decode(self.model_tokens[out_last:]) if "\ufffd" not in xxx: # avoid utf-8 display issues decoded += xxx out_last = begin + i + 1 if i >= self.max_tokens_per_ge...
https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html
9a5feace4e4c-0
Source code for langchain.chat_models.azure_openai """Azure OpenAI chat wrapper.""" from __future__ import annotations import logging from typing import Any, Dict, Mapping from pydantic import root_validator from langchain.chat_models.openai import ChatOpenAI from langchain.schema import ChatResult from langchain.utils...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
9a5feace4e4c-1
openai_api_base: str = "" openai_api_version: str = "" openai_api_key: str = "" openai_organization: str = "" openai_proxy: str = "" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
9a5feace4e4c-2
except AttributeError: raise ValueError( "`openai` has no `ChatCompletion` attribute, this is likely " "due to an old version of the openai package. Try upgrading it " "with `pip install --upgrade openai`." ) if values["n"] < 1: ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
9a5feace4e4c-3
) return super()._create_chat_result(response) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
ee32f1594022-0
Source code for langchain.chat_models.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.chat_models import ChatOpenAI from langchain.sch...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
ee32f1594022-1
) -> ChatResult: """Call ChatOpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(messages, stop, run_manage...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
ee32f1594022-2
generated_responses = await super()._agenerate(messages, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() message_dicts, params = super()._create_message_dicts(messages, stop) for i, generation in enumerate(generated_responses.generations): response_dict, par...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
0c1e4b78ffca-0
Source code for langchain.chat_models.vertexai """Wrapper around Google VertexAI chat-based models.""" from dataclasses import dataclass, field from typing import Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForL...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
0c1e4b78ffca-1
""" if not history: return _ChatHistory() first_message = history[0] system_message = first_message if isinstance(first_message, SystemMessage) else None chat_history = _ChatHistory(system_message=system_message) messages_left = history[1:] if system_message else history if len(messages_...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
0c1e4b78ffca-2
) -> ChatResult: """Generate next turn in the conversation. Args: messages: The history of the conversation as a list of messages. stop: The list of stop words (optional). run_manager: The Callbackmanager for LLM run, it's not used at the moment. Returns: ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
0c1e4b78ffca-3
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
ef05ca6fd5bd-0
Source code for langchain.chat_models.openai """OpenAI chat wrapper.""" from __future__ import annotations import logging import sys from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union, ) from pydantic import Extra, Field, root_validator fro...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-1
return retry( reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=( retry_if_exception_type(openai.error.Timeout) | retry_if_exception_type(openai.error.APIError) | retry_...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-2
elif isinstance(message, HumanMessage): message_dict = {"role": "user", "content": message.content} elif isinstance(message, AIMessage): message_dict = {"role": "assistant", "content": message.content} elif isinstance(message, SystemMessage): message_dict = {"role": "system", "content": ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-3
leave blank if not using a proxy or service emulator.""" openai_api_base: Optional[str] = None openai_organization: Optional[str] = None # to support explicit proxy for OpenAI openai_proxy: Optional[str] = None request_timeout: Optional[Union[float, Tuple[float, float]]] = None """Timeout for re...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-4
if invalid_model_kwargs: raise ValueError( f"Parameters {invalid_model_kwargs} should be specified explicitly. " f"Instead they were passed in as part of `model_kwargs` parameter." ) values["model_kwargs"] = extra return values @root_validator(...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-5
) if values["n"] < 1: raise ValueError("n must be at least 1.") if values["n"] > 1 and values["streaming"]: raise ValueError("n must be 1 when streaming.") return values @property def _default_params(self) -> Dict[str, Any]: """Get the default parameters f...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-6
"""Use tenacity to retry the completion call.""" retry_decorator = self._create_retry_decorator() @retry_decorator def _completion_with_retry(**kwargs: Any) -> Any: return self.client.create(**kwargs) return _completion_with_retry(**kwargs) def _combine_llm_outputs(self, ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-7
{"content": inner_completion, "role": role} ) return ChatResult(generations=[ChatGeneration(message=message)]) response = self.completion_with_retry(messages=message_dicts, **params) return self._create_chat_result(response) def _create_message_dicts( self, messages: ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-8
async for stream_resp in await acompletion_with_retry( self, messages=message_dicts, **params ): role = stream_resp["choices"][0]["delta"].get("role", role) token = stream_resp["choices"][0]["delta"].get("content", "") inner_completion += token...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-9
"""Return type of chat model.""" return "openai-chat" def _get_encoding_model(self) -> Tuple[str, tiktoken.Encoding]: tiktoken_ = _import_tiktoken() model = self.model_name if model == "gpt-3.5-turbo": # gpt-3.5-turbo may change over time. # Returning num toke...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
ef05ca6fd5bd-10
Official documentation: https://github.com/openai/openai-cookbook/blob/ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb""" if sys.version_info[1] <= 7: return super().get_num_tokens_from_messages(messages) model, encoding = self._get_encoding_model() if model == "g...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
9c94f72abc3f-0
Source code for langchain.chat_models.google_palm """Wrapper around Google's PaLM Chat API.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-1
raise ChatGooglePalmError("ChatResponse must have at least one candidate.") generations: List[ChatGeneration] = [] for candidate in response.candidates: author = candidate.get("author") if author is None: raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}") ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-2
raise ChatGooglePalmError("System message must be first input message.") context = input_message.content elif isinstance(input_message, HumanMessage) and input_message.example: if messages: raise ChatGooglePalmError( "Message examples must come before ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-3
context=context, examples=examples, messages=messages, ) def _create_retry_decorator() -> Callable[[Any], Any]: """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions""" import google.api_core.exceptions multiplier = 2 min_seconds = 1 max_seconds = 60 ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-4
return await _achat_with_retry(**kwargs) [docs]class ChatGooglePalm(BaseChatModel, BaseModel): """Wrapper around Google's PaLM Chat API. To use you must have the google.generativeai Python package installed and either: 1. The ``GOOGLE_API_KEY``` environment varaible set with your API key, or ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-5
"""Validate api key, python package exists, temperature, top_p, and top_k.""" google_api_key = get_from_dict_or_env( values, "google_api_key", "GOOGLE_API_KEY" ) try: import google.generativeai as genai genai.configure(api_key=google_api_key) except Im...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
9c94f72abc3f-6
) return _response_to_result(response, stop) async def _agenerate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, ) -> ChatResult: prompt = _messages_to_prompt_dict(messages) ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
e92bf4bdc192-0
Source code for langchain.chat_models.anthropic from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.chat_models.base import BaseChatModel from langchain.llms.anthropic import _...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
e92bf4bdc192-1
elif isinstance(message, AIMessage): message_text = f"{self.AI_PROMPT} {message.content}" elif isinstance(message, SystemMessage): message_text = f"{self.HUMAN_PROMPT} <admin>{message.content}</admin>" else: raise ValueError(f"Got unknown type {message}") retu...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
e92bf4bdc192-2
) -> ChatResult: prompt = self._convert_messages_to_prompt(messages) params: Dict[str, Any] = {"prompt": prompt, **self._default_params} if stop: params["stop_sequences"] = stop if self.streaming: completion = "" stream_resp = self.client.completion_st...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
e92bf4bdc192-3
completion = response["completion"] message = AIMessage(content=completion) return ChatResult(generations=[ChatGeneration(message=message)]) [docs] def get_num_tokens(self, text: str) -> int: """Calculate number of tokens.""" if not self.count_tokens: raise NameError("Plea...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
fc6046c4dbfd-0
Source code for langchain.prompts.few_shot """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPromptTemplate, check_valid_template, ) from langcha...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
fc6046c4dbfd-1
"""Check that one and only one of examples/example_selector are provided.""" examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_select...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
fc6046c4dbfd-2
# Get the examples to use. examples = self._get_examples(**kwargs) examples = [ {k: e[k] for k in self.example_prompt.input_variables} for e in examples ] # Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examp...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
96fca020a6dd-0
Source code for langchain.prompts.chat """Chat prompt template.""" from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union from pydantic import BaseModel, Field from langchain.memory.buffer import get_b...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
96fca020a6dd-1
"""Input variables for this prompt template.""" return [self.variable_name] MessagePromptTemplateT = TypeVar( "MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate" ) class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): prompt: StringPromptTemplate additional_kwargs: dic...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
96fca020a6dd-2
) class HumanMessagePromptTemplate(BaseStringMessagePromptTemplate): def format(self, **kwargs: Any) -> BaseMessage: text = self.prompt.format(**kwargs) return HumanMessage(content=text, additional_kwargs=self.additional_kwargs) class AIMessagePromptTemplate(BaseStringMessagePromptTemplate): def...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
96fca020a6dd-3
messages: List[Union[BaseMessagePromptTemplate, BaseMessage]] @classmethod def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate: prompt_template = PromptTemplate.from_template(template, **kwargs) message = HumanMessagePromptTemplate(prompt=prompt_template) return cl...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
96fca020a6dd-4
result = [] for message_template in self.messages: if isinstance(message_template, BaseMessage): result.extend([message_template]) elif isinstance(message_template, BaseMessagePromptTemplate): rel_params = { k: v for...
https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
9d63fb169c0b-0
Source code for langchain.prompts.base """BasePrompt schema definition.""" from __future__ import annotations import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union import yaml from pydantic import BaseModel, Extra, Field, roo...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
9d63fb169c0b-1
"Please install it with `pip install jinja2`." ) env = Environment() ast = env.parse(template) variables = meta.find_undeclared_variables(ast) return variables DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = { "f-string": formatter.format, "jinja2": jinja2_formatter, } DEFAULT_VALIDATOR...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
9d63fb169c0b-2
"""A list of the names of the variables the prompt template expects.""" output_parser: Optional[BaseOutputParser] = None """How to parse the output of calling an LLM on this formatted prompt.""" partial_variables: Mapping[str, Union[str, Callable[[], str]]] = Field( default_factory=dict ) cl...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
9d63fb169c0b-3
prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs} return type(self)(**prompt_dict) def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]: # Get partial params: partial_kwargs = { k: v if isinstance(v, str) else v() for k, v...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
9d63fb169c0b-4
save_path = Path(file_path) else: save_path = file_path directory_path = save_path.parent directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save prompt_dict = self.dict() if save_path.suffix == ".json": with open(file_path, "w...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
b8ee990c8f3f-0
Source code for langchain.prompts.prompt """Prompt schema definition.""" from __future__ import annotations from pathlib import Path from string import Formatter from typing import Any, Dict, List, Union from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, S...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
b8ee990c8f3f-1
""" kwargs = self._merge_partial_and_user_variables(**kwargs) return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs) @root_validator() def template_is_valid(cls, values: Dict) -> Dict: """Check that template and input variables are consistent.""" if value...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
b8ee990c8f3f-2
[docs] @classmethod def from_file( cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any ) -> PromptTemplate: """Load a prompt from a file. Args: template_file: The path to the file containing the prompt template. input_variables: A li...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
8eccc9cc9134-0
Source code for langchain.prompts.few_shot_with_templates """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate from langchain.prompts.example_selec...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
8eccc9cc9134-1
examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_selector' should be provided" ) if examples is None and example_selecto...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
8eccc9cc9134-2
Args: kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the example...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
8eccc9cc9134-3
"""Return a dictionary of the prompt.""" if self.example_selector: raise ValueError("Saving an example selector is not currently supported") return super().dict(**kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
3f574573f4a2-0
Source code for langchain.prompts.loading """Load prompts from disk.""" import importlib import json import logging from pathlib import Path from typing import Union import yaml from langchain.output_parsers.regex import RegexParser from langchain.prompts.base import BasePromptTemplate from langchain.prompts.few_shot i...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
3f574573f4a2-1
with open(template_path) as f: template = f.read() else: raise ValueError # Set the template variable to the extracted variable. config[var_name] = template return config def _load_examples(config: dict) -> dict: """Load examples if necessary.""" if isinst...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
3f574573f4a2-2
config = _load_template("prefix", config) # Load the example prompt. if "example_prompt_path" in config: if "example_prompt" in config: raise ValueError( "Only one of example_prompt and example_prompt_path should " "be specified." ) config[...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
3f574573f4a2-3
with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) elif file_path.suffix == ".py": spec = importlib.util.spec_from_loader( "prompt", loader=None, origin=str(file_path) ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
aed627abb0c0-0
Source code for langchain.prompts.example_selector.length_based """Select examples based on length.""" import re from typing import Callable, Dict, List from pydantic import BaseModel, validator from langchain.prompts.example_selector.base import BaseExampleSelector from langchain.prompts.prompt import PromptTemplate d...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
aed627abb0c0-1
get_text_length = values["get_text_length"] string_examples = [example_prompt.format(**eg) for eg in values["examples"]] return [get_text_length(eg) for eg in string_examples] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use base...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
68742d912109-0
Source code for langchain.prompts.example_selector.semantic_similarity """Example selector that selects examples based on SemanticSimilarity.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings fr...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
68742d912109-1
return ids[0] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on semantic similarity.""" # Get the docs with the highest similarity. if self.input_keys: input_variables = {key: input_variables[key] for key in s...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
68742d912109-2
instead of all variables. vectorstore_cls_kwargs: optional kwargs containing url for vector store Returns: The ExampleSelector instantiated, backed by a vector store. """ if input_keys: string_examples = [ " ".join(sorted_values({k: eg[k] for k...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
68742d912109-3
examples = [dict(e.metadata) for e in example_docs] # If example keys are provided, filter examples to those keys. if self.example_keys: examples = [{k: eg[k] for k in self.example_keys} for eg in examples] return examples [docs] @classmethod def from_examples( cls, ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
68742d912109-4
) return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
b1c978110697-0
Source code for langchain.agents.initialize """Load agent.""" from typing import Any, Optional, Sequence from langchain.agents.agent import AgentExecutor from langchain.agents.agent_types import AgentType from langchain.agents.loading import AGENT_TO_CLASS, load_agent from langchain.base_language import BaseLanguageMod...
https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
b1c978110697-1
"but at most only one should be." ) if agent is not None: if agent not in AGENT_TO_CLASS: raise ValueError( f"Got unknown agent type: {agent}. " f"Valid types are: {AGENT_TO_CLASS.keys()}." ) agent_cls = AGENT_TO_CLASS[agent] ag...
https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html
c9638ff90a75-0
Source code for langchain.agents.agent """Chain that takes in an input and produces an action and action input.""" from __future__ import annotations import asyncio import json import logging import time from abc import abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-1
return None [docs] @abstractmethod def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Ste...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-2
# `force` just returns a constant string return AgentFinish( {"output": "Agent stopped due to iteration limit or time limit."}, "" ) else: raise ValueError( f"Got unsupported early_stopping_method `{early_stopping_method}`" ) [docs]...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-3
directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save agent_dict = self.dict() if save_path.suffix == ".json": with open(file_path, "w") as f: json.dump(agent_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(fil...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-4
**kwargs: Any, ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations callbacks: Callbacks to run. **kwargs: User inputs. Returns: ...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-5
Example: .. code-block:: python # If working with agent executor agent.agent.save(file_path="path/agent.yaml") """ # Convert file to Path object. if isinstance(file_path, str): save_path = Path(file_path) else: save_path = file_path...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-6
return _dict [docs] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has take...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-7
} [docs]class Agent(BaseSingleActionAgent): """Class responsible for calling the language model and deciding the action. This is driven by an LLMChain. The prompt in the LLMChain MUST include a variable called "agent_scratchpad" where the agent can put its intermediary work. """ llm_chain: LLMCh...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-8
return thoughts [docs] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Callbacks = None, **kwargs: Any, ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has t...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-9
"""Create the full inputs for the LLMChain from intermediate steps.""" thoughts = self._construct_scratchpad(intermediate_steps) new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop} full_inputs = {**kwargs, **new_inputs} return full_inputs @property def input_keys(self...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-10
"""Create a prompt for this class.""" @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: """Validate that appropriate tools are passed in.""" pass @classmethod @abstractmethod def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser: """G...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-11
# `force` just returns a constant string return AgentFinish( {"output": "Agent stopped due to iteration limit or time limit."}, "" ) elif early_stopping_method == "generate": # Generate does one final forward pass thoughts = "" for acti...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html
c9638ff90a75-12
} class ExceptionTool(BaseTool): name = "_Exception" description = "Exception tool" def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: return query async def _arun( self, query: str, run_manager: Opti...
https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html