id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 115 |
|---|---|---|
88b26a3f51ee-0 | Source code for langchain.document_loaders.bigquery
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BigQueryLoader(BaseLoader):
"""Loads a query result from BigQuery into a list of documents.
Each document repr... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
88b26a3f51ee-1 | metadata_columns = []
for row in query_result:
page_content = "\n".join(
f"{k}: {v}" for k, v in row.items() if k in page_content_columns
)
metadata = {k: v for k, v in row.items() if k in metadata_columns}
doc = Document(page_content=page_content,... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
02f1cb9a817c-0 | Source code for langchain.document_loaders.gutenberg
"""Loader that loads .txt web files."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GutenbergLoader(BaseLoader):
"""Loader that uses urllib to load .txt web files."""
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html |
793ac5e7c4be-0 | Source code for langchain.document_loaders.evernote
"""Load documents from Evernote.
https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c
"""
import hashlib
from base64 import b64decode
from time import strptime
from typing import Any, Dict, List
from langchain.docstore.document import Document
from langcha... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
793ac5e7c4be-1 | else:
note_dict[elem.tag] = elem.text
note_dict["resource"] = resources
return note_dict
def _parse_note_xml(xml_file: str) -> str:
"""Parse Evernote xml."""
# Without huge_tree set to True, parser may complain about huge text node
# Try to recover, because there may be " ", which w... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
809910b46479-0 | Source code for langchain.document_loaders.s3_directory
"""Loading logic for loading documents from an s3 directory."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.s3_file import S3FileLoader
[docs]class ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html |
f88b2f145b9f-0 | Source code for langchain.document_loaders.gcs_file
"""Loading logic for loading documents from a GCS file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import Uns... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html |
5a158b7e3834-0 | Source code for langchain.document_loaders.notiondb
"""Notion DB loader for langchain"""
from typing import Any, Dict, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
NOTION_BASE_URL = "https://api.notion.com/v1"
DATABASE_URL = NOTION_BASE_URL... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
5a158b7e3834-1 | def _retrieve_page_ids(
self, query_dict: Dict[str, Any] = {"page_size": 100}
) -> List[str]:
"""Get all the pages from a Notion database."""
pages: List[Dict[str, Any]] = []
while True:
data = self._request(
DATABASE_URL.format(database_id=self.database_i... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
5a158b7e3834-2 | metadata[prop_name.lower()] = value
metadata["id"] = page_id
return Document(page_content=self._load_blocks(page_id), metadata=metadata)
def _load_blocks(self, block_id: str, num_tabs: int = 0) -> str:
"""Read a block and its children."""
result_lines_arr: List[str] = []
cur_... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
5a158b7e3834-3 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
ed4a8a5ec90c-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from pydantic.dataclasses import dataclass
from langchain.docstore.do... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-1 | if not values.get("credentials_path") and not values.get(
"service_account_path"
):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _load_credentials(self) -> Any:
"""Load credentials."""
# Adapted from https://developers.go... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-2 | """Loader that loads Youtube transcripts."""
def __init__(
self,
video_id: str,
add_video_info: bool = False,
language: str = "en",
continue_on_failure: bool = False,
):
"""Initialize with YouTube video ID."""
self.video_id = video_id
self.add_vide... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-3 | en_transcript = transcript_list.find_transcript(["en"])
transcript = en_transcript.translate(self.language)
transcript_pieces = transcript.fetch()
transcript = " ".join([t["text"].strip(" ") for t in transcript_pieces])
return [Document(page_content=transcript, metadata=metadata)]
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-4 | .. code-block:: python
from langchain.document_loaders import GoogleApiClient
from langchain.document_loaders import GoogleApiYoutubeLoader
google_api_client = GoogleApiClient(
service_account_path=Path("path_to_your_sec_file.json")
)
loader = ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-5 | if not values.get("channel_name") and not values.get("video_ids"):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _get_transcripe_for_video_id(self, video_id: str) -> str:
from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-6 | channel_id = response["items"][0]["id"]["channelId"]
return channel_id
def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]:
try:
from youtube_transcript_api import (
NoTranscriptFound,
TranscriptsDisabled,
)
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
ed4a8a5ec90c-7 | )
else:
raise e
pass
request = self.youtube_client.search().list_next(request, response)
return video_ids
[docs] def load(self) -> List[Document]:
"""Load documents."""
document_list = []
if self.channel_name:... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
6b34f1b6fae6-0 | Source code for langchain.document_loaders.image_captions
"""
Loader that loads image captions
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base
"""
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
6b34f1b6fae6-1 | model=model, processor=processor, path_image=path_image
)
doc = Document(page_content=caption, metadata=metadata)
results.append(doc)
return results
def _get_captions_and_metadata(
self, model: Any, processor: Any, path_image: str
) -> Tuple[str, dict]:
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
51513d089b9f-0 | Source code for langchain.document_loaders.sitemap
"""Loader that fetches a sitemap and loads those URLs."""
import itertools
import re
from typing import Any, Callable, Generator, Iterable, List, Optional
from langchain.document_loaders.web_base import WebBaseLoader
from langchain.schema import Document
def _default_p... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
51513d089b9f-1 | try:
import lxml # noqa:F401
except ImportError:
raise ValueError(
"lxml package not found, please install it with " "`pip install lxml`"
)
super().__init__(web_path)
self.filter_urls = filter_urls
self.parsing_function = parsing_funct... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
51513d089b9f-2 | if blockcount - 1 < self.blocknum:
raise ValueError(
"Selected sitemap does not contain enough blocks for given blocknum"
)
else:
els = elblocks[self.blocknum]
results = self.scrape_all([el["loc"].strip() for el in els if "loc" in e... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
2f2e8c5bbc03-0 | Source code for langchain.memory.combined
from typing import Any, Dict, List, Set
from pydantic import validator
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data together."""
memories: List[BaseMemory]
"""For tracking all the memo... | https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
2f2e8c5bbc03-1 | """Save context from this session for every memory."""
# Save context for all sub-memories
for memory in self.memories:
memory.save_context(inputs, outputs)
[docs] def clear(self) -> None:
"""Clear context from this session for every memory."""
for memory in self.memories:... | https://python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
e9213f94bb90-0 | Source code for langchain.memory.simple
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class SimpleMemory(BaseMemory):
"""Simple memory for storing context or other bits of information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
... | https://python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
84463034fe85-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
84463034fe85-1 | [docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self, key: str) -> None:
del self.store[key]
[docs] def exists(self, key: str) -> bool:
return key in self.store
[docs] def clear(self) -> None:
return self.store.clear()
[... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
84463034fe85-2 | except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
def full_key_prefix(self) -> str:
return f"{self.key_prefix}:{self.sess... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
84463034fe85-3 | yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class ConversationEntityMemory(BaseChatMemory):
"""Entity extractor & summarizer to memory."""
human_prefix: str = "Human"
a... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
84463034fe85-4 | history=buffer_string,
input=inputs[prompt_input_key],
)
if output.strip() == "NONE":
entities = []
else:
entities = [w.strip() for w in output.split(",")]
entity_summaries = {}
for entity in entities:
entity_summaries[entity] = sel... | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
84463034fe85-5 | """Clear memory contents."""
self.chat_memory.clear()
self.entity_cache.clear()
self.entity_store.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
2740914f6470-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.base_language import BaseLanguageModel
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buf... | https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
2740914f6470-1 | if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)
By Harrison Chase
© Copyright 2023, ... | https://python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
5abf290e6724-0 | Source code for langchain.memory.summary
from typing import Any, Dict, List, Type
from pydantic import BaseModel, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import SUM... | https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
5abf290e6724-1 | """Return history buffer."""
if self.return_messages:
buffer: Any = [self.summary_message_cls(content=self.buffer)]
else:
buffer = self.buffer
return {self.memory_key: buffer}
@root_validator()
def validate_prompt_input_variables(cls, values: Dict) -> Dict:
... | https://python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
5fe64ce4faa2-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
5fe64ce4faa2-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
2bfc5c0a9119-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory."""
human_pr... | https://python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
d97437525902-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d97437525902-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d97437525902-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
d97437525902-3 | """Clear memory contents."""
super().clear()
self.kg.clear()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
a15574d7d973-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import Documen... | https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
a15574d7d973-1 | docs = self.retriever.get_relevant_documents(query)
result: Union[List[Document], str]
if not self.return_docs:
result = "\n".join([doc.page_content for doc in docs])
else:
result = docs
return {self.memory_key: result}
def _form_documents(
self, input... | https://python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
71edcdeb2469-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import get_buffer_string
[docs]class ConversationBuff... | https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
71edcdeb2469-1 | @root_validator()
def validate_chains(cls, values: Dict) -> Dict:
"""Validate that return messages is not True."""
if values.get("return_messages", False):
raise ValueError(
"return_messages must be False for ConversationStringBufferMemory"
)
return va... | https://python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
6f2a64c961a7-0 | Source code for langchain.memory.readonly
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class ReadOnlySharedMemory(BaseMemory):
"""A memory wrapper that is read-only and cannot be changed."""
memory: BaseMemory
@property
def memory_variables(self) -> List[str]:
... | https://python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
13997cde14a5-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_CO... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
13997cde14a5-1 | messages = messages_from_dict(items)
return messages
[docs] def add_user_message(self, message: str) -> None:
self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(self, message: BaseMe... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
9f30b17823fd-0 | Source code for langchain.memory.chat_message_histories.cosmos_db
"""Azure CosmosDB Memory History."""
from __future__ import annotations
import logging
from types import TracebackType
from typing import TYPE_CHECKING, Any, List, Optional, Type
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
9f30b17823fd-1 | :param connection_string: The connection string to use to authenticate.
:param ttl: The time to live (in seconds) to use for documents in the container.
"""
self.cosmos_endpoint = cosmos_endpoint
self.cosmos_database = cosmos_database
self.cosmos_container = cosmos_container
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
9f30b17823fd-2 | self.cosmos_container,
partition_key=PartitionKey("/user_id"),
default_ttl=self.ttl,
)
self.load_messages()
def __enter__(self) -> "CosmosDBChatMessageHistory":
"""Context manager entry point."""
if self._client:
self._client.__enter__()
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
9f30b17823fd-3 | ):
self.messages = messages_from_dict(item["messages"])
[docs] def add_user_message(self, message: str) -> None:
"""Add a user message to the memory."""
self.upsert_messages(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
"""Add a AI messag... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
731eed8116fc-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
731eed8116fc-1 | items = []
messages = messages_from_dict(items)
return messages
[docs] def add_user_message(self, message: str) -> None:
self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(se... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
d79dfd27ada3-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
[do... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
d79dfd27ada3-1 | self.append(HumanMessage(content=message))
[docs] def add_ai_message(self, message: str) -> None:
self.append(AIMessage(content=message))
[docs] def append(self, message: BaseMessage) -> None:
"""Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_mes... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
fba1bdb0dd74-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
messages: List[Ba... | https://python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
35182ffa21d0-0 | Source code for langchain.chains.llm_requests
"""Chain that hits a URL and then uses an LLM to parse results."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
35182ffa21d0-1 | :meta private:
"""
return [self.output_key]
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
try:
from bs4 import BeautifulSoup # noqa: F401
except ImportError:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_requests.html |
754dd65727da-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import (... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-1 | def output_keys(self) -> List[str]:
"""Will always return text key.
:meta private:
"""
return [self.output_key]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = self.... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-2 | """Prepare prompts from inputs."""
stop = None
if "stop" in input_list[0]:
stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
selected_inputs = {k: inputs[k] for k in self.prompt.input_variables}
prompt = self.prompt.format_prompt(**se... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-3 | await run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
raise ValueError(
"If `stop` is present in any inputs, should be present in all."
)
prompts.append(prompt)
return prompts, ... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-4 | except (KeyboardInterrupt, Exception) as e:
await run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
await run_manager.on_chain_end({"outputs": outputs})
return outputs
[docs] def create_outputs(self, response: LLMResult) -> List[Dict[str, st... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-5 | Returns:
Completion from LLM.
Example:
.. code-block:: python
completion = llm.predict(adjective="funny")
"""
return (await self.acall(kwargs, callbacks=callbacks))[self.output_key]
[docs] def predict_and_parse(
self, callbacks: Callbacks = None... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
754dd65727da-6 | return [
self.prompt.output_parser.parse(res[self.output_key]) for res in result
]
else:
return result
[docs] async def aapply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
c20edf4b71ab-0 | Source code for langchain.chains.sequential
"""Chain pipeline where the outputs of one step feed directly into next."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForChainRun,
CallbackManagerForChainRun,
)... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c20edf4b71ab-1 | overlapping_keys = set(input_variables) & set(memory_keys)
raise ValueError(
f"The the input key(s) {''.join(overlapping_keys)} are found "
f"in the Memory keys ({memory_keys}) - please use input and "
f"memory keys that don't overlap."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c20edf4b71ab-2 | callbacks = _run_manager.get_child()
outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks)
known_values.update(outputs)
return {k: known_values[k] for k in self.output_variables}
async def _acall(
self,
inputs: Dict[str, Any],
run_manage... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c20edf4b71ab-3 | @root_validator()
def validate_chains(cls, values: Dict) -> Dict:
"""Validate that chains are all single input/output."""
for chain in values["chains"]:
if len(chain.input_keys) != 1:
raise ValueError(
"Chains used in SimplePipeline should all have one... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
c20edf4b71ab-4 | _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
_input = inputs[self.input_key]
color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))])
for i, chain in enumerate(self.chains):
_input = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/sequential.html |
e57fda41e63f-0 | Source code for langchain.chains.loading
"""Functionality for loading chains."""
import json
from pathlib import Path
from typing import Any, Union
import yaml
from langchain.chains.api.base import APIChain
from langchain.chains.base import Chain
from langchain.chains.combine_documents.map_reduce import MapReduceDocume... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-1 | """Load LLM chain from config dict."""
if "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm` or `llm_path` must be present.")
if "pro... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-2 | llm_chain=llm_chain, base_embeddings=embeddings, **config
)
def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain:
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_config)
elif "llm_chain_path" in ... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-3 | llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "combine_document_chain" in config:
combine_docu... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-4 | elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm` or `llm_path` must be present.")
if "prompt" in config:
prompt_config = config.pop("prompt")
prompt = load_prompt_from_config(prompt_config)
elif "prompt_path" in config:
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-5 | list_assertions_prompt = load_prompt(config.pop("list_assertions_prompt_path"))
if "check_assertions_prompt" in config:
check_assertions_prompt_config = config.pop("check_assertions_prompt")
check_assertions_prompt = load_prompt_from_config(
check_assertions_prompt_config
)
e... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-6 | prompt = load_prompt_from_config(prompt_config)
elif "prompt_path" in config:
prompt = load_prompt(config.pop("prompt_path"))
return LLMMathChain(llm=llm, prompt=prompt, **config)
def _load_map_rerank_documents_chain(
config: dict, **kwargs: Any
) -> MapRerankDocumentsChain:
if "llm_chain" in co... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-7 | return PALChain(llm=llm, prompt=prompt, **config)
def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocumentsChain:
if "initial_llm_chain" in config:
initial_llm_chain_config = config.pop("initial_llm_chain")
initial_llm_chain = load_chain_from_config(initial_llm_chain_config)
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-8 | if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(combine_documents_chain_config)
elif "combine_documents_chain_path" in config:
combine_documents_chain = load_chain(config.pop("comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-9 | if "combine_documents_chain" in config:
combine_documents_chain_config = config.pop("combine_documents_chain")
combine_documents_chain = load_chain_from_config(combine_documents_chain_config)
elif "combine_documents_chain_path" in config:
combine_documents_chain = load_chain(config.pop("comb... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-10 | api_request_chain = load_chain_from_config(api_request_chain_config)
elif "api_request_chain_path" in config:
api_request_chain = load_chain(config.pop("api_request_chain_path"))
else:
raise ValueError(
"One of `api_request_chain` or `api_request_chain_path` must be present."
... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-11 | if "requests_wrapper" in kwargs:
requests_wrapper = kwargs.pop("requests_wrapper")
return LLMRequestsChain(
llm_chain=llm_chain, requests_wrapper=requests_wrapper, **config
)
else:
return LLMRequestsChain(llm_chain=llm_chain, **config)
type_to_loader_dict = {
"api_cha... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-12 | if config_type not in type_to_loader_dict:
raise ValueError(f"Loading {config_type} chain not supported")
chain_loader = type_to_loader_dict[config_type]
return chain_loader(config, **kwargs)
[docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain:
"""Unified method for loading a chain ... | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
e57fda41e63f-13 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
77455961e9f4-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
77455961e9f4-1 | values,
"openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = ... | https://python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
1971c0377730-0 | Source code for langchain.chains.mapreduce
"""Map-reduce chain.
Splits up a document, sends the smaller parts to the LLM with one prompt,
then combines the results with another one.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.callbacks.ma... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
1971c0377730-1 | reduce_chain = StuffDocumentsChain(llm_chain=llm_chain, callbacks=callbacks)
combine_documents_chain = MapReduceDocumentsChain(
llm_chain=llm_chain,
combine_document_chain=reduce_chain,
callbacks=callbacks,
)
return cls(
combine_documents_chain=com... | https://python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html |
e1551dc33b5b-0 | Source code for langchain.chains.transform
"""Chain that runs an arbitrary python function."""
from typing import Callable, Dict, List, Optional
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
[docs]class TransformChain(Chain):
"""Chain transform chain outp... | https://python.langchain.com/en/latest/_modules/langchain/chains/transform.html |
069d6e2e7c57-0 | Source code for langchain.chains.llm_math.base
"""Chain that interprets a prompt and executes python code to do math."""
from __future__ import annotations
import math
import re
import warnings
from typing import Any, Dict, List, Optional
import numexpr
from pydantic import Extra, root_validator
from langchain.base_lan... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
069d6e2e7c57-1 | if "llm" in values:
warnings.warn(
"Directly instantiating an LLMMathChain with an llm is deprecated. "
"Please instantiate with llm_chain argument or using the from_llm "
"class method."
)
if "llm_chain" not in values and values["llm"]... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
069d6e2e7c57-2 | llm_output = llm_output.strip()
text_match = re.search(r"^```text(.*?)```", llm_output, re.DOTALL)
if text_match:
expression = text_match.group(1)
output = self._evaluate_expression(expression)
run_manager.on_text("\nAnswer: ", verbose=self.verbose)
run_ma... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
069d6e2e7c57-3 | else:
raise ValueError(f"unknown format from LLM: {llm_output}")
return {self.output_key: answer}
def _call(
self,
inputs: Dict[str, str],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run_manager = run_manager or CallbackMana... | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
069d6e2e7c57-4 | llm_chain = LLMChain(llm=llm, prompt=prompt)
return cls(llm_chain=llm_chain, **kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 02, 2023. | https://python.langchain.com/en/latest/_modules/langchain/chains/llm_math/base.html |
35a84bb02017-0 | Source code for langchain.chains.hyde.base
"""Hypothetical Document Embeddings.
https://arxiv.org/abs/2212.10496
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
import numpy as np
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForChainRun
from langc... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
35a84bb02017-1 | return list(np.array(embeddings).mean(axis=0))
[docs] def embed_query(self, text: str) -> List[float]:
"""Generate a hypothetical document and embedded it."""
var_name = self.llm_chain.input_keys[0]
result = self.llm_chain.generate([{var_name: text}])
documents = [generation.text for ... | https://python.langchain.com/en/latest/_modules/langchain/chains/hyde/base.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.