id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
aba36ae210b9-2 | raise ValueError(f"unknown format from LLM: {llm_output}")
return {self.output_key: answer}
async def _aprocess_llm_result(
self,
llm_output: str,
run_manager: AsyncCallbackManagerForChainRun,
) -> Dict[str, str]:
await run_manager.on_text(llm_output, color="green", verbo... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html |
aba36ae210b9-3 | stop=["```output"],
callbacks=_run_manager.get_child(),
)
return self._process_llm_result(llm_output, _run_manager)
async def _acall(
self,
inputs: Dict[str, str],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
_run... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html |
b0afdb1229ac-0 | Source code for langchain_experimental.llms.anthropic_functions
import json
from collections import defaultdict
from html.parser import HTMLParser
from typing import Any, DefaultDict, Dict, List, Optional
from langchain.callbacks.manager import (
CallbackManagerForLLMRun,
)
from langchain.chat_models.anthropic impo... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
b0afdb1229ac-1 | """A heavy-handed solution, but it's fast for prototyping.
Might be re-implemented later to restrict scope to the limited grammar, and
more efficiency.
Uses an HTML parser to parse a limited grammar that allows
for syntax of the form:
INPUT -> JUNK? VALUE*
JUNK ->... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
b0afdb1229ac-2 | value = self.data if is_leaf else top_of_stack
# Difficult to type this correctly with mypy (maybe impossible?)
# Can be nested indefinitely, so requires self referencing type
self.stack[-1][tag].append(value) # type: ignore
# Reset the data so we if we encounter a sequence of end tags,... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
b0afdb1229ac-3 | return values
@property
def model(self) -> BaseChatModel:
"""For backwards compatibility."""
return self.llm
def _generate(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**k... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
b0afdb1229ac-4 | }
}
message = AIMessage(content="", additional_kwargs=kwargs)
return ChatResult(generations=[ChatGeneration(message=message)])
elif "<tool>" in completion:
tag_parser = TagParser()
tag_parser.feed(completion.strip() + "</tool_input>")
msg =... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/anthropic_functions.html |
ef52f97a636f-0 | Source code for langchain_experimental.llms.lmformatenforcer_decoder
"""Experimental implementation of lm-format-enforcer wrapped LLM."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.huggingf... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/lmformatenforcer_decoder.html |
ef52f97a636f-1 | import lmformatenforcer.integrations.transformers as hf_integration
# We integrate lmformatenforcer by adding a prefix_allowed_tokens_fn.
# It has to be done on each call, because the prefix function is stateful.
if "prefix_allowed_tokens_fn" in self.pipeline._forward_params:
raise V... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/lmformatenforcer_decoder.html |
7587352bafe9-0 | Source code for langchain_experimental.llms.jsonformer_decoder
"""Experimental implementation of jsonformer wrapped LLM."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.hugg... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
7587352bafe9-1 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
jsonformer = import_jsonformer()
from transformers import Text2TextGenerationPipeline
pipeline = cast(Text2TextGenerationPipeline, self.pipe... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/jsonformer_decoder.html |
0f484fbe579d-0 | Source code for langchain_experimental.llms.rellm_decoder
"""Experimental implementation of RELLM wrapped LLM."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Optional, cast
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.huggingface_pipeline impor... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
0f484fbe579d-1 | import_rellm()
return values
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
rellm = import_rellm()
from transformers import Text2TextGenerationPipelin... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/rellm_decoder.html |
d11c4beaca92-0 | Source code for langchain_experimental.llms.llamaapi
import json
import logging
from typing import (
Any,
Dict,
List,
Mapping,
Optional,
Tuple,
)
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.chat_models.base import BaseChatModel
from langchain.schema import (
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
d11c4beaca92-1 | if isinstance(message, ChatMessage):
message_dict = {"role": message.role, "content": message.content}
elif isinstance(message, HumanMessage):
message_dict = {"role": "user", "content": message.content}
elif isinstance(message, AIMessage):
message_dict = {"role": "assistant", "content": ... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
d11c4beaca92-2 | self, messages: List[BaseMessage], stop: Optional[List[str]]
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
params = dict(self._client_params)
if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
p... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llms/llamaapi.html |
829b89b373a0-0 | Source code for langchain_experimental.graph_transformers.diffbot
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import requests
from langchain.graphs.graph_document import GraphDocument, Node, Relationship
from langchain.schema import Document
from langchain.utils import get_from_env
[docs]def fo... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-1 | self.nodes[node] = properties
else:
self.nodes[node].update(properties)
[docs] def return_node_list(self) -> List[Node]:
"""
Returns the nodes as a list of Node objects.
Each Node object will have its ID, type, and properties populated.
Returns:
List[No... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-2 | [docs] def get_type(self, type: str) -> str:
"""
Retrieves the simplified schema type for a given original type.
Args:
type (str): The original schema type to find the simplified type for.
Returns:
str: The simplified schema type if it exists;
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-3 | Args:
diffbot_api_key (str):
The API key for Diffbot's NLP services.
fact_confidence_threshold (float):
Minimum confidence level for facts to be included.
include_qualifiers (bool):
Whether to include qualifiers in the relationships.
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-4 | self, payload: Dict[str, Any], document: Document
) -> GraphDocument:
"""
Transform the Diffbot NLP response into a GraphDocument.
Args:
payload (Dict[str, Any]): The JSON response from Diffbot's NLP API.
document (Document): The original document.
Returns:
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-5 | if record["value"]["allUris"]
else record["value"]["name"]
)
target_label = record["value"]["allTypes"][0]["name"].capitalize()
target_name = record["value"]["name"]
# Some facts are better suited as node properties
if target_label in FACT_TO_P... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
829b89b373a0-6 | relationships=relationships,
source=document,
)
[docs] def convert_to_graph_documents(
self, documents: Sequence[Document]
) -> List[GraphDocument]:
"""Convert a sequence of documents into graph documents.
Args:
documents (Sequence[Document]): The original ... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/graph_transformers/diffbot.html |
a9cb8bf0c879-0 | Source code for langchain_experimental.generative_agents.generative_agent
import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.schema.language_model import BaseLanguageModel
from lang... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-1 | """Configuration for this pydantic object."""
arbitrary_types_allowed = True
# LLM-related methods
@staticmethod
def _parse_list(text: str) -> List[str]:
"""Parse a newline-separated string into a list of strings."""
lines = re.split(r"\n", text.strip())
return [re.sub(r"^\s*... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-2 | """
)
entity_name = self._get_entity_from_observation(observation)
entity_action = self._get_entity_action(observation, entity_name)
q1 = f"What is the relationship between {self.name} and {entity_name}"
q2 = f"{entity_name} is {entity_action}"
return self.chain(prompt=pr... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-3 | agent_name=self.name,
observation=observation,
agent_status=self.status,
)
consumed_tokens = self.llm.get_num_tokens(
prompt.format(most_recent_memories="", **kwargs)
)
kwargs[self.memory.most_recent_memories_token_key] = consumed_tokens
return... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-4 | reaction = self._clean_response(result.split("REACT:")[-1])
return False, f"{self.name} {reaction}"
if "SAY:" in result:
said_value = self._clean_response(result.split("SAY:")[-1])
return True, f"{self.name} said {said_value}"
else:
return False, result
[d... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-5 | f"{observation} and said {response_text}",
self.memory.now_key: now,
},
)
return True, f"{self.name} said {response_text}"
else:
return False, result
######################################################
# Agent stateful' summary m... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
a9cb8bf0c879-6 | f"Name: {self.name} (age: {age})"
+ f"\nInnate traits: {self.traits}"
+ f"\n{self.summary}"
)
[docs] def get_full_header(
self, force_refresh: bool = False, now: Optional[datetime] = None
) -> str:
"""Return a full header of the agent's status, summary, and current... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/generative_agent.html |
8574bf689f71-0 | Source code for langchain_experimental.generative_agents.memory
import logging
import re
from datetime import datetime
from typing import Any, Dict, List, Optional
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers import TimeWeightedVectorStoreRetriever
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-1 | # output keys
relevant_memories_key: str = "relevant_memories"
relevant_memories_simple_key: str = "relevant_memories_simple"
most_recent_memories_key: str = "most_recent_memories"
now_key: str = "now"
reflecting: bool = False
[docs] def chain(self, prompt: PromptTemplate) -> LLMChain:
re... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-2 | self, topic: str, now: Optional[datetime] = None
) -> List[str]:
"""Generate 'insights' on a topic of reflection, based on pertinent memories."""
prompt = PromptTemplate.from_template(
"Statements relevant to: '{topic}'\n"
"---\n"
"{related_statements}\n"
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-3 | insights = self._get_insights_on_topic(topic, now=now)
for insight in insights:
self.add_memory(insight, now=now)
new_insights.extend(insights)
return new_insights
def _score_memory_importance(self, memory_content: str) -> float:
"""Score the absolute importan... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-4 | + " acceptance), rate the likely poignancy of the"
+ " following piece of memory. Always answer with only a list of numbers."
+ " If just given one memory still respond in a list."
+ " Memories are separated by semi colans (;)"
+ "\Memories: {memory_content}"
... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-5 | and not self.reflecting
):
self.reflecting = True
self.pause_to_reflect(now=now)
# Hack to clear the importance from reflection
self.aggregate_importance = 0.0
self.reflecting = False
return result
[docs] def add_memory(
self, memory... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-6 | else:
return self.memory_retriever.get_relevant_documents(observation)
[docs] def format_memories_detail(self, relevant_memories: List[Document]) -> str:
content = []
for mem in relevant_memories:
content.append(self._format_memory_detail(mem, prefix="- "))
return "\n"... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
8574bf689f71-7 | now = inputs.get(self.now_key)
if queries is not None:
relevant_memories = [
mem for query in queries for mem in self.fetch_memories(query, now=now)
]
return {
self.relevant_memories_key: self.format_memories_detail(
relevan... | lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/generative_agents/memory.html |
f0e22500afd4-0 | Source code for langchain.cache
"""
.. warning::
Beta Feature!
**Cache** provides an optional caching layer for LLMs.
Cache is useful for two reasons:
- It can save you money by reducing the number of API calls you make to the LLM
provider if you're often requesting the same completion multiple times.
- It can spee... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-1 | logger = logging.getLogger(__file__)
if TYPE_CHECKING:
import momento
from cassandra.cluster import Session as CassandraSession
def _hash(_input: str) -> str:
"""Use a deterministic hashing approach."""
return hashlib.md5(_input.encode()).hexdigest()
def _dump_generations_to_json(generations: RETURN_VAL... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-2 | Returns:
str: a single string representing a list of generations.
This function (+ its counterpart `_loads_generations`) rely on
the dumps/loads pair with Reviver, so are able to deal
with all subclasses of Generation.
Each item in the list can be `dumps`ed to a string,
then we make the whol... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-3 | )
return generations
except (json.JSONDecodeError, TypeError):
logger.warning(
f"Malformed/unparsable cached blob encountered: '{generations_str}'"
)
return None
[docs]class InMemoryCache(BaseCache):
"""Cache that stores things in memory."""
[docs] def __init__(sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-4 | """Initialize by creating all tables."""
self.engine = engine
self.cache_schema = cache_schema
self.cache_schema.metadata.create_all(self.engine)
[docs] def lookup(self, prompt: str, llm_string: str) -> Optional[RETURN_VAL_TYPE]:
"""Look up based on prompt and llm_string."""
s... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-5 | for item in items:
session.merge(item)
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear cache."""
with Session(self.engine) as session:
session.query(self.cache_schema).delete()
session.commit()
[docs]class SQLiteCache(SQLAlchemyCache):
"""Cache that... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-6 | raise ValueError(
"Could not import upstash_redis python package. "
"Please install it with `pip install upstash_redis`."
)
if not isinstance(redis_, Redis):
raise ValueError("Please pass in Upstash Redis object.")
self.redis = redis_
self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-7 | str(idx): generation.text for idx, generation in enumerate(return_val)
}
self.redis.hset(key=key, values=mapping)
if self.ttl is not None:
self.redis.expire(key, self.ttl)
[docs] def clear(self, **kwargs: Any) -> None:
"""
Clear cache. If `asynchronous` is True, fl... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-8 | try:
from redis import Redis
except ImportError:
raise ValueError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
if not isinstance(redis_, Redis):
raise ValueError("Please pass in ... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-9 | if not isinstance(gen, Generation):
raise ValueError(
"RedisCache only supports caching of normal LLM generations, "
f"got {type(gen)}"
)
# Write to a Redis HASH
key = self._key(prompt, llm_string)
with self.redis.pipeline()... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-10 | Example:
.. code-block:: python
from langchain.globals import set_llm_cache
from langchain.cache import RedisSemanticCache
from langchain.embeddings import OpenAIEmbeddings
set_llm_cache(RedisSemanticCache(
redis_url="redis://localhost:6379",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-11 | return self._cache_dict[index_name]
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear semantic cache for a given llm_string."""
index_name = self._index_name(kwargs["llm_string"])
if index_name in self._cache_dict:
self._cache_dict[index_name].drop_index(
ind... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-12 | """Update cache based on prompt and llm_string."""
for gen in return_val:
if not isinstance(gen, Generation):
raise ValueError(
"RedisSemanticCache only supports caching of "
f"normal LLM generations, got {type(gen)}"
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-13 | data_manager=manager_factory(
manager="map",
data_dir=f"map_cache_{llm}"
),
)
set_llm_cache(GPTCache(init_gptcache))
"""
try:
import gptcache # noqa: F401
except ImportError:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-14 | def _get_gptcache(self, llm_string: str) -> Any:
"""Get a cache object.
When the corresponding llm model cache does not exist, it will be created."""
_gptcache = self.gptcache_dict.get(llm_string, None)
if not _gptcache:
_gptcache = self._new_gptcache(llm_string)
retu... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-15 | _gptcache = self._get_gptcache(llm_string)
handled_data = json.dumps([generation.dict() for generation in return_val])
put(prompt, handled_data, cache_obj=_gptcache)
return None
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear cache."""
from gptcache import Cache
... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-16 | cache_client: momento.CacheClient,
cache_name: str,
*,
ttl: Optional[timedelta] = None,
ensure_cache_exists: bool = True,
):
"""Instantiate a prompt cache using Momento as a backend.
Note: to instantiate the cache client passed to MomentoCache,
you must have a... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-17 | cls,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
api_key: Optional[str] = None,
auth_token: Optional[str] = None, # for backwards compatibility
**kwargs: Any,
) -> MomentoCache:
"""Construct cache ... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-18 | """Lookup llm generations in cache by prompt and associated model and settings.
Args:
prompt (str): The prompt run through the language model.
llm_string (str): The language model version and settings.
Raises:
SdkException: Momento service or network error
Ret... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-19 | value = _dump_generations_to_json(return_val)
set_response = self.cache_client.set(self.cache_name, key, value, self.ttl)
from momento.responses import CacheSet
if isinstance(set_response, CacheSet.Success):
pass
elif isinstance(set_response, CacheSet.Error):
rais... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-20 | skip_provisioning: bool = False,
):
"""
Initialize with a ready session and a keyspace name.
Args:
session (cassandra.cluster.Session): an open Cassandra session
keyspace (str): the keyspace to use for storing the cache
table_name (str): name of the Cassan... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-21 | if generations is not None:
return generations
else:
return None
else:
return None
[docs] def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE) -> None:
"""Update cache based on prompt and llm_string."""
blob = _dum... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-22 | CASSANDRA_SEMANTIC_CACHE_DEFAULT_SCORE_THRESHOLD = 0.85
CASSANDRA_SEMANTIC_CACHE_DEFAULT_TABLE_NAME = "langchain_llm_semantic_cache"
CASSANDRA_SEMANTIC_CACHE_DEFAULT_TTL_SECONDS = None
CASSANDRA_SEMANTIC_CACHE_EMBEDDING_CACHE_SIZE = 16
[docs]class CassandraSemanticCache(BaseCache):
"""
Cache that uses Cassandra... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-23 | embedding (Embedding): Embedding provider for semantic
encoding and search.
table_name (str): name of the Cassandra (vector) table
to use as cache
distance_metric (str, 'dot'): which measure to adopt for
similarity searches
score_thresh... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-24 | self.table = MetadataVectorCassandraTable(
session=self.session,
keyspace=self.keyspace,
table=self.table_name,
primary_key_type=["TEXT"],
vector_dimension=self.embedding_dimension,
ttl_seconds=self.ttl_seconds,
metadata_indexing=("allo... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-25 | ) -> Optional[Tuple[str, RETURN_VAL_TYPE]]:
"""
Look up based on prompt and llm_string.
If there are hits, return (document_id, cached_entry)
"""
prompt_embedding: List[float] = self._get_embedding(text=prompt)
hits = list(
self.table.metric_ann_search(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-26 | """
self.table.delete(row_id=document_id)
[docs] def clear(self, **kwargs: Any) -> None:
"""Clear the *whole* semantic cache."""
self.table.clear()
[docs]class FullMd5LLMCache(Base): # type: ignore
"""SQLite table for full LLM Cache (all generations)."""
__tablename__ = "full_md5_llm... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-27 | prompt_md5 = self.get_md5(prompt)
items = [
self.cache_schema(
id=str(uuid.uuid1()),
prompt=prompt,
prompt_md5=prompt_md5,
llm=llm_string,
response=dumps(gen),
idx=i,
)
for i, gen ... | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
f0e22500afd4-28 | """Clear cache."""
with Session(self.engine) as session:
session.execute(self.cache_schema.delete())
[docs] @staticmethod
def get_md5(input_string: str) -> str:
return hashlib.md5(input_string.encode()).hexdigest() | lang/api.python.langchain.com/en/latest/_modules/langchain/cache.html |
23faabef47de-0 | Source code for langchain.text_splitter
"""**Text Splitters** are classes for splitting text.
**Class hierarchy:**
.. code-block::
BaseDocumentTransformer --> TextSplitter --> <name>TextSplitter # Example: CharacterTextSplitter
RecursiveCharacterTextSplitter --> <n... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-1 | from spacy.lang.en import English
sentencizer = English()
sentencizer.add_pipe("sentencizer")
else:
sentencizer = spacy.load(pipeline, exclude=["ner", "tagger"])
return sentencizer
def _split_text_with_regex(
text: str, separator: str, keep_separator: bool
) -> List[str]:
# Now t... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-2 | chunk_overlap: Overlap in characters between chunks
length_function: Function that measures the length of given chunks
keep_separator: Whether to keep the separator in the chunks
add_start_index: If `True`, includes chunk's start index in metadata
strip_whitespace: If `Tr... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-3 | """Split documents."""
texts, metadatas = [], []
for doc in documents:
texts.append(doc.page_content)
metadatas.append(doc.metadata)
return self.create_documents(texts, metadatas=metadatas)
def _join_docs(self, docs: List[str], separator: str) -> Optional[str]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-4 | while total > self._chunk_overlap or (
total + _len + (separator_len if len(current_doc) > 0 else 0)
> self._chunk_size
and total > 0
):
total -= self._length_function(current_doc[0]) + (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-5 | allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
**kwargs: Any,
) -> TS:
"""Text splitter that uses tiktoken encoder to count length."""
try:
import tiktoken
except ImportError:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-6 | ) -> Sequence[Document]:
"""Asynchronously transform a sequence of documents by splitting them."""
return await asyncio.get_running_loop().run_in_executor(
None, partial(self.transform_documents, **kwargs), documents
)
[docs]class CharacterTextSplitter(TextSplitter):
"""Splitting... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-7 | ):
"""Create a new MarkdownHeaderTextSplitter.
Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
"""
# Output line-by-line or aggregated into chunks w/ common headers
self.return_each_line = return... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-8 | lines = text.split("\n")
# Final output
lines_with_metadata: List[LineType] = []
# Content and metadata of the chunk currently being processed
current_content: List[str] = []
current_metadata: Dict[str, str] = {}
# Keep track of the nested header structure
# heade... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-9 | and header_stack[-1]["level"] >= current_header_level
):
# We have encountered a new header
# at the same or higher level
popped_header = header_stack.pop()
# Clear the metadata for th... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-10 | return self.aggregate_lines_to_chunks(lines_with_metadata)
else:
return [
Document(page_content=chunk["content"], metadata=chunk["metadata"])
for chunk in lines_with_metadata
]
[docs]class ElementType(TypedDict):
"""Element type as typed dict."""
u... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-11 | for element in elements:
if (
aggregated_chunks
and aggregated_chunks[-1]["metadata"] == element["metadata"]
):
# If the last element in the aggregated list
# has the same metadata as the current element,
# append th... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-12 | # document transformation for "structure-aware" chunking is handled with xsl.
# see comments in html_chunks_with_headers.xslt for more detailed information.
xslt_path = (
pathlib.Path(__file__).parent
/ "document_transformers/xsl/html_chunks_with_headers.xslt"
)
x... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-13 | )
},
)
)
if not self.return_each_element:
return self.aggregate_elements_to_chunks(elements)
else:
return [
Document(page_content=chunk["content"], metadata=chunk["metadata"])
for chunk in... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-14 | [docs] def __init__(
self,
encoding_name: str = "gpt2",
model_name: Optional[str] = None,
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
**kwargs: Any,
) -> None:
"""Crea... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-15 | [docs] def __init__(
self,
chunk_overlap: int = 50,
model_name: str = "sentence-transformers/all-mpnet-base-v2",
tokens_per_chunk: Optional[int] = None,
**kwargs: Any,
) -> None:
"""Create a new TextSplitter."""
super().__init__(**kwargs, chunk_overlap=chun... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-16 | def encode_strip_start_and_stop_token_ids(text: str) -> List[int]:
return self._encode(text)[1:-1]
tokenizer = Tokenizer(
chunk_overlap=self._chunk_overlap,
tokens_per_chunk=self.tokens_per_chunk,
decode=self.tokenizer.decode,
encode=encode_strip_start... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-17 | CSHARP = "csharp"
COBOL = "cobol"
[docs]class RecursiveCharacterTextSplitter(TextSplitter):
"""Splitting text by recursively look at characters.
Recursively tries to split by different characters to find one
that works.
"""
[docs] def __init__(
self,
separators: Optional[List[str]... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-18 | _separator = "" if self._keep_separator else separator
for s in splits:
if self._length_function(s) < self._chunk_size:
_good_splits.append(s)
else:
if _good_splits:
merged_text = self._merge_splits(_good_splits, _separator)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-19 | "\ncase ",
# Split by the normal type of lines
"\n\n",
"\n",
" ",
"",
]
elif language == Language.GO:
return [
# Split along function definitions
"\nfunc ",
"\n... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-20 | "\nwhen ",
"\ncase ",
"\nelse ",
# Split by the normal type of lines
"\n\n",
"\n",
" ",
"",
]
elif language == Language.JS:
return [
# Split along function defi... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-21 | "\nforeach ",
"\nwhile ",
"\ndo ",
"\nswitch ",
"\ncase ",
# Split by the normal type of lines
"\n\n",
"\n",
" ",
"",
]
elif language == Language.PROTO:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-22 | "\nclass ",
# Split along control flow statements
"\nif ",
"\nunless ",
"\nwhile ",
"\nfor ",
"\ndo ",
"\nbegin ",
"\nrescue ",
# Split by the normal type of lines
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-23 | # Split along control flow statements
"\nif ",
"\nfor ",
"\nwhile ",
"\ndo ",
"\nswitch ",
"\ncase ",
# Split by the normal type of lines
"\n\n",
"\n",
" ",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-24 | "\n\\\\begin{verbatim}",
# Now split by math environments
"\n\\\begin{align}",
"$$",
"$",
# Now split by the normal type of lines
" ",
"",
]
elif language == Language.HTML:
ret... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-25 | "\nelse ",
# Split by exceptions
"\ntry ",
"\nthrow ",
"\nfinally ",
"\ncatch ",
# Split by the normal type of lines
"\n\n",
"\n",
" ",
"",
]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-26 | "\nREAD ",
"\nWRITE ",
"\nIF ",
"\nELSE ",
"\nMOVE ",
"\nPERFORM ",
"\nUNTIL ",
"\nVARYING ",
"\nACCEPT ",
"\nDISPLAY ",
"\nSTOP RUN.",
# Split ... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-27 | """Splitting text using Spacy package.
Per default, Spacy's `en_core_web_sm` model is used. For a faster, but
potentially less accurate splitting, you can use `pipeline='sentencizer'`.
"""
[docs] def __init__(
self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any
) ->... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
23faabef47de-28 | super().__init__(separators=separators, **kwargs)
[docs]class LatexTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Latex-formatted layout elements."""
[docs] def __init__(self, **kwargs: Any) -> None:
"""Initialize a LatexTextSplitter."""
separators = self.get_se... | lang/api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
c37ade5e7a8b-0 | Source code for langchain.model_laboratory
"""Experiment with different models."""
from __future__ import annotations
from typing import List, Optional, Sequence
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.llms.base import BaseLLM
from langchain.prompts.prompt import... | lang/api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html |
c37ade5e7a8b-1 | self.chain_colors = get_color_mapping(chain_range)
self.names = names
[docs] @classmethod
def from_llms(
cls, llms: List[BaseLLM], prompt: Optional[PromptTemplate] = None
) -> ModelLaboratory:
"""Initialize with LLMs to experiment with and optional prompt.
Args:
ll... | lang/api.python.langchain.com/en/latest/_modules/langchain/model_laboratory.html |
baad2192616a-0 | Source code for langchain.hub
"""Interface with the LangChain Hub."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from langchain.load.dump import dumps
from langchain.load.load import loads
if TYPE_CHECKING:
from langchainhub import Client
def _get_client(api_url: Optional[str... | lang/api.python.langchain.com/en/latest/_modules/langchain/hub.html |
baad2192616a-1 | :param parent_commit_hash: The commit hash of the parent commit to push to. Defaults
to the latest commit automatically.
:param new_repo_is_public: Whether the repo should be public. Defaults to
True (Public by default).
:param new_repo_description: The description of the repo. Defaults to an em... | lang/api.python.langchain.com/en/latest/_modules/langchain/hub.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.