id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
4e6754f2de47-6 | Examples:
.. code-block:: python
from langchain.prompts import ChatPromptTemplate
template = ChatPromptTemplate.from_messages([
("system", "You are a helpful AI bot. Your name is {name}."),
("human", "Hello, how are you doing?"),
("ai", "I'... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-7 | @root_validator(pre=True)
def validate_input_variables(cls, values: dict) -> dict:
"""Validate input variables.
If input_variables is not set, it will be set to the union of
all input variables in the messages.
Args:
values: values to validate.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-8 | return cls.from_messages([message])
[docs] @classmethod
@deprecated("0.0.260", alternative="from_messages classmethod", pending=True)
def from_role_strings(
cls, string_messages: List[Tuple[str, str]]
) -> ChatPromptTemplate:
"""Create a chat prompt template from a list of (role, template... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-9 | ("human", "That's good to hear."),
])
Instantiation from mixed message formats:
.. code-block:: python
template = ChatPromptTemplate.from_messages([
SystemMessage(content="hello"),
("human", "Hello, how are you?"),
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-10 | """Format the chat template into a list of finalized messages.
Args:
**kwargs: keyword arguments to use for filling in template variables
in all the template messages in this chat template.
Returns:
list of formatted messages
"""
kwargs = sel... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-11 | ("human", "{input}"),
]
)
template2 = template.partial(user="Lucy", name="R2D2")
template2.format_messages(input="hello")
"""
prompt_dict = self.__dict__.copy()
prompt_dict["input_variables"] = list(
set(self.input_v... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-12 | return len(self.messages)
@property
def _prompt_type(self) -> str:
"""Name of prompt type."""
return "chat"
[docs] def save(self, file_path: Union[Path, str]) -> None:
"""Save prompt to file.
Args:
file_path: path to file.
"""
raise NotImplementedEr... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4e6754f2de47-13 | - BaseMessagePromptTemplate
- BaseMessage
- 2-tuple of (role string, template); e.g., ("human", "{user_input}")
- 2-tuple of (message class, template)
- string: shorthand for ("human", template); e.g., "{user_input}"
Args:
message: a representation of a message in one of the supported format... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
2e7c7e13b2f6-0 | Source code for langchain.prompts.base
"""BasePrompt schema definition."""
from __future__ import annotations
import warnings
from abc import ABC
from typing import Any, Callable, Dict, List, Set
from langchain.schema.messages import BaseMessage, HumanMessage
from langchain.schema.prompt import PromptValue
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
2e7c7e13b2f6-1 | try:
from jinja2 import Environment, meta
except ImportError:
raise ImportError(
"jinja2 not installed, which is needed to use the jinja2_formatter. "
"Please install it with `pip install jinja2`."
)
env = Environment()
ast = env.parse(template)
variables ... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
2e7c7e13b2f6-2 | """Return prompt as string."""
return self.text
[docs] def to_messages(self) -> List[BaseMessage]:
"""Return prompt as messages."""
return [HumanMessage(content=self.text)]
[docs]class StringPromptTemplate(BasePromptTemplate, ABC):
"""String prompt that exposes the format method, returnin... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
30145d5878c2-0 | Source code for langchain.prompts.pipeline
from typing import Any, Dict, List, Tuple
from langchain.prompts.chat import BaseChatPromptTemplate
from langchain.pydantic_v1 import root_validator
from langchain.schema import BasePromptTemplate, PromptValue
def _get_inputs(inputs: dict, input_variables: List[str]) -> dict:
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html |
30145d5878c2-1 | for k, prompt in self.pipeline_prompts:
_inputs = _get_inputs(kwargs, prompt.input_variables)
if isinstance(prompt, BaseChatPromptTemplate):
kwargs[k] = prompt.format_messages(**_inputs)
else:
kwargs[k] = prompt.format(**_inputs)
_inputs = _get... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html |
67290c158102-0 | Source code for langchain.prompts.loading
"""Load prompts."""
import json
import logging
from pathlib import Path
from typing import Callable, Dict, Union
import yaml
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import BaseLLMOutp... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
67290c158102-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
67290c158102-2 | """Load the "few shot" prompt from the config."""
# Load the suffix and prefix templates.
config = _load_template("suffix", config)
config = _load_template("prefix", config)
# Load the example prompt.
if "example_prompt_path" in config:
if "example_prompt" in config:
raise ValueE... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
67290c158102-3 | file_path = Path(file)
else:
file_path = file
# Load from either json or yaml.
if file_path.suffix == ".json":
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)
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
ae5a34b4e7a5-0 | Source code for langchain.prompts.few_shot
"""Prompt template that contains few shot examples."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
)
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-1 | "One of 'examples' and 'example_selector' should be provided"
)
return values
def _get_examples(self, **kwargs: Any) -> List[dict]:
"""Get the examples to use for formatting the prompt.
Args:
**kwargs: Keyword arguments to be passed to the example selector.
Re... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-2 | @root_validator()
def template_is_valid(cls, values: Dict) -> Dict:
"""Check that prefix, suffix, and input variables are consistent."""
if values["validate_template"]:
check_valid_template(
values["prefix"] + values["suffix"],
values["template_format"],
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-3 | """Return the prompt type key."""
return "few_shot"
[docs] def dict(self, **kwargs: Any) -> Dict:
"""Return a dictionary of the prompt."""
if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs)
[doc... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-4 | few_shot_prompt = FewShotChatMessagePromptTemplate(
examples=examples,
# This is a prompt template used to format each individual example.
example_prompt=example_prompt,
)
final_prompt = ChatPromptTemplate.from_messages(
[
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-5 | example_selector=example_selector,
# Define how each example will be formatted.
# In this case, each example will become 2 messages:
# 1 human, and 1 AI
example_prompt=(
HumanMessagePromptTemplate.from_template("{input}")
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
ae5a34b4e7a5-6 | **kwargs: keyword arguments to use for filling in templates in messages.
Returns:
A list of formatted messages with all template variables filled in.
"""
# Get the examples to use.
examples = self._get_examples(**kwargs)
examples = [
{k: e[k] for k in self... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
16c7fc0d3307-0 | Source code for langchain.prompts.example_selector.ngram_overlap
"""Select and order examples based on ngram overlap score (sentence_bleu score).
https://www.nltk.org/_modules/nltk/translate/bleu_score.html
https://aclanthology.org/P02-1040.pdf
"""
from typing import Dict, List
import numpy as np
from langchain.prompts... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
16c7fc0d3307-1 | """
examples: List[dict]
"""A list of the examples that the prompt template expects."""
example_prompt: PromptTemplate
"""Prompt template used to format the examples."""
threshold: float = -1.0
"""Threshold at which algorithm stops. Set to -1.0 by default.
For negative threshold:
select_... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
16c7fc0d3307-2 | examples = []
k = len(self.examples)
score = [0.0] * k
first_prompt_template_key = self.example_prompt.input_variables[0]
for i in range(k):
score[i] = ngram_overlap_score(
inputs, [self.examples[i][first_prompt_template_key]]
)
while True:... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
cefe8e8114dd-0 | Source code for langchain.prompts.example_selector.base
"""Interface for selecting examples to include in prompts."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List
[docs]class BaseExampleSelector(ABC):
"""Interface for selecting examples to include in prompts."""
[docs] @abstractmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/base.html |
d4dcd2b10308-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
from langchain.pydantic_v1 import BaseModel... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
d4dcd2b10308-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
2d0652b80f6a-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 langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.py... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2d0652b80f6a-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2d0652b80f6a-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2d0652b80f6a-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://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2d0652b80f6a-4 | )
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
92824527b9ad-0 | Source code for langchain.graphs.arangodb_graph
import os
from math import ceil
from typing import Any, Dict, List, Optional
[docs]class ArangoGraph:
"""ArangoDB wrapper for graph operations."""
[docs] def __init__(self, db: Any) -> None:
"""Create a new ArangoDB graph wrapper instance."""
self.s... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
92824527b9ad-1 | """
if not 0 <= sample_ratio <= 1:
raise ValueError("**sample_ratio** value must be in between 0 to 1")
# Stores the Edge Relationships between each ArangoDB Document Collection
graph_schema: List[Dict[str, Any]] = [
{"graph_name": g["name"], "edge_definitions": g["edge_d... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
92824527b9ad-2 | f"example_{col_type}": doc,
}
)
return {"Graph Schema": graph_schema, "Collection Schema": collection_schema}
[docs] def query(
self, query: str, top_k: Optional[int] = None, **kwargs: Any
) -> List[Dict[str, Any]]:
"""Query the ArangoDB database."""
im... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
92824527b9ad-3 | )
return cls(db)
[docs]def get_arangodb_client(
url: Optional[str] = None,
dbname: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
) -> Any:
"""Get the Arango DB client from credentials.
Args:
url: Arango DB url. Can be passed in as named arg... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
92824527b9ad-4 | _password: str = password or os.environ.get("ARANGODB_PASSWORD", "") # type: ignore[assignment] # noqa: E501
return ArangoClient(_url).db(_dbname, _username, _password, verify=True) | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
c9ae73f829b5-0 | Source code for langchain.graphs.memgraph_graph
from langchain.graphs.neo4j_graph import Neo4jGraph
SCHEMA_QUERY = """
CALL llm_util.schema("prompt_ready")
YIELD *
RETURN *
"""
RAW_SCHEMA_QUERY = """
CALL llm_util.schema("raw")
YIELD *
RETURN *
"""
[docs]class MemgraphGraph(Neo4jGraph):
"""Memgraph wrapper for grap... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/memgraph_graph.html |
a39ccaacbb9f-0 | Source code for langchain.graphs.neo4j_graph
from typing import Any, Dict, List
from langchain.graphs.graph_document import GraphDocument
node_properties_query = """
CALL apoc.meta.data()
YIELD label, other, elementType, type, property
WHERE NOT type = "RELATIONSHIP" AND elementType = "node"
WITH label AS nodeLabels, c... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a39ccaacbb9f-1 | self._driver = neo4j.GraphDatabase.driver(url, auth=(username, password))
self._database = database
self.schema: str = ""
self.structured_schema: Dict[str, Any] = {}
# Verify connection
try:
self._driver.verify_connectivity()
except neo4j.exceptions.ServiceUna... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a39ccaacbb9f-2 | node_properties = [el["output"] for el in self.query(node_properties_query)]
rel_properties = [el["output"] for el in self.query(rel_properties_query)]
relationships = [el["output"] for el in self.query(rel_query)]
self.structured_schema = {
"node_props": {el["labels"]: el["propertie... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a39ccaacbb9f-3 | "RETURN distinct 'done' AS result"
),
{
"data": [el.__dict__ for el in document.nodes],
"document": document.source.__dict__,
},
)
# Import relationships
self.query(
"UNWIND $data ... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
76c26d5952ee-0 | Source code for langchain.graphs.hugegraph
from typing import Any, Dict, List
[docs]class HugeGraph:
"""HugeGraph wrapper for graph operations"""
[docs] def __init__(
self,
username: str = "default",
password: str = "default",
address: str = "127.0.0.1",
port: int = 8081,
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html |
76c26d5952ee-1 | self.schema = (
f"Node properties: {vertex_schema}\n"
f"Edge properties: {edge_schema}\n"
f"Relationships: {relationships}\n"
)
[docs] def query(self, query: str) -> List[Dict[str, Any]]:
g = self.client.gremlin()
res = g.exec(query)
return res["dat... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html |
a8b269081f3e-0 | Source code for langchain.graphs.graph_document
from __future__ import annotations
from typing import List, Union
from langchain.load.serializable import Serializable
from langchain.pydantic_v1 import Field
from langchain.schema import Document
[docs]class Node(Serializable):
"""Represents a node in a graph with as... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/graph_document.html |
eabc645509e2-0 | Source code for langchain.graphs.neptune_graph
from typing import Any, Dict, List, Optional, Tuple, Union
[docs]class NeptuneQueryException(Exception):
"""A class to handle queries that fail to execute"""
def __init__(self, exception: Union[str, Dict]):
if isinstance(exception, dict):
self.m... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
eabc645509e2-1 | service: str = "neptunedata",
) -> None:
"""Create a new Neptune graph wrapper instance."""
try:
if client is not None:
self.client = client
else:
import boto3
if credentials_profile_name is not None:
session... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
eabc645509e2-2 | }
)
@property
def get_schema(self) -> str:
"""Returns the schema of the Neptune database"""
return self.schema
[docs] def query(self, query: str, params: dict = {}) -> Dict[str, Any]:
"""Query Neptune database."""
return self.client.execute_open_cypher_query(openCy... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
eabc645509e2-3 | LIMIT 10
"""
triple_template = "(:`{a}`)-[:`{e}`]->(:`{b}`)"
triple_schema = []
for label in e_labels:
q = triple_query.format(e_label=label)
data = self.query(q)
for d in data["results"]:
triple = triple_template.format(
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
eabc645509e2-4 | for label in e_labels:
q = edge_properties_query.format(e_label=label)
data = {"label": label, "properties": self.query(q)["results"]}
s = set({})
for p in data["properties"]:
for k, v in p["props"].items():
s.add((k, types[type(v).__na... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
fabca055b61f-0 | Source code for langchain.graphs.kuzu_graph
from typing import Any, Dict, List
[docs]class KuzuGraph:
"""Kùzu wrapper for graph operations."""
[docs] def __init__(self, db: Any, database: str = "kuzu") -> None:
try:
import kuzu
except ImportError:
raise ImportError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html |
fabca055b61f-1 | for property_name in properties:
property_type = properties[property_name]["type"]
list_type_flag = ""
if properties[property_name]["dimension"] > 0:
if "shape" in properties[property_name]:
for s in properties[property_name]["s... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html |
238254bb7b6f-0 | Source code for langchain.graphs.nebula_graph
import logging
from string import Template
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
rel_query = Template(
"""
MATCH ()-[e:`$edge_type`]->()
WITH e limit 1
MATCH (m)-[:`$edge_type`]->(n) WHERE id(m) == src(e) AND id(n) == dst(e)
RETUR... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
238254bb7b6f-1 | self.session_pool = self._get_session_pool()
self.schema = ""
# Set schema
try:
self.refresh_schema()
except Exception as e:
raise ValueError(f"Could not refresh schema. Error: {e}")
def _get_session_pool(self) -> Any:
assert all(
[self.use... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
238254bb7b6f-2 | @property
def get_schema(self) -> str:
"""Returns the schema of the NebulaGraph database"""
return self.schema
[docs] def execute(self, query: str, params: Optional[dict] = None, retry: int = 0) -> Any:
"""Query NebulaGraph database."""
from nebula3.Exception import IOErrorExcepti... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
238254bb7b6f-3 | )
return self.execute(query, params, retry)
else:
raise ValueError(f"Error executing query to NebulaGraph. Error: {e}")
except (TTransportException, IOErrorException):
# connection issue, try to recreate session pool
if retry < RETRY_TIMES:
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
238254bb7b6f-4 | for i in range(r.row_size()):
edge_schema["properties"].append((props[i].cast(), types[i].cast()))
edge_types_schema.append(edge_schema)
# build relationships types
r = self.execute(
rel_query.substitute(edge_type=edge_type_name)
).column_v... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
9d0f9414b47b-0 | Source code for langchain.graphs.falkordb_graph
from typing import Any, Dict, List
from langchain.graphs.graph_document import GraphDocument
from langchain.graphs.neo4j_graph import Neo4jGraph
node_properties_query = """
MATCH (n)
WITH keys(n) as keys, labels(n) AS labels
WITH CASE WHEN keys = [] THEN [NULL] ELSE keys ... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
9d0f9414b47b-1 | raise ImportError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
driver = redis.Redis(host=host, port=port)
self._graph = Graph(driver, database)
self.schema: str = ""
self.structured_schema: Dict[str... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
9d0f9414b47b-2 | f"Relationships: {relationships}\n"
)
[docs] def query(self, query: str, params: dict = {}) -> List[Dict[str, Any]]:
"""Query FalkorDB database."""
try:
data = self._graph.query(query, params)
return data.result_set
except Exception as e:
raise Valu... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
231eb56d7530-0 | Source code for langchain.graphs.networkx_graph
"""Networkx wrapper for graph operations."""
from __future__ import annotations
from typing import Any, List, NamedTuple, Optional, Tuple
KG_TRIPLE_DELIMITER = "<|>"
[docs]class KnowledgeTriple(NamedTuple):
"""A triple in the graph."""
subject: str
predicate: ... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
231eb56d7530-1 | """Create a new graph."""
try:
import networkx as nx
except ImportError:
raise ImportError(
"Could not import networkx python package. "
"Please install it with `pip install networkx`."
)
if graph is not None:
if not... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
231eb56d7530-2 | if self._graph.has_edge(knowledge_triple.subject, knowledge_triple.object_):
self._graph.remove_edge(knowledge_triple.subject, knowledge_triple.object_)
[docs] def get_triples(self) -> List[Tuple[str, str, str]]:
"""Get all triples in the graph."""
return [(u, v, d["relation"]) for u, v, ... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
231eb56d7530-3 | Usage in a jupyter notebook:
>>> from IPython.display import SVG
>>> self.draw_graphviz_svg(layout="dot", filename="web.svg")
>>> SVG('web.svg')
"""
from networkx.drawing.nx_agraph import to_agraph
try:
import pygraphviz # noqa: F401
excep... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
5ce6068d8d7e-0 | Source code for langchain.graphs.rdf_graph
from __future__ import annotations
from typing import (
TYPE_CHECKING,
List,
Optional,
)
if TYPE_CHECKING:
import rdflib
prefixes = {
"owl": """PREFIX owl: <http://www.w3.org/2002/07/owl#>\n""",
"rdf": """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-sy... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-1 | """ FILTER (isIRI(?cls)) . \n"""
""" OPTIONAL { ?cls rdfs:comment ?com } \n"""
"""}"""
)
rel_query_rdf = prefixes["rdfs"] + (
"""SELECT DISTINCT ?rel ?com\n"""
"""WHERE { \n"""
""" ?subj ?rel ?obj . \n"""
""" OPTIONAL { ?cls rdfs:comment ?com } \n"""
"""}"""
)
rel_query_rdfs = (
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-2 | """}"""
)
)
[docs]class RdfGraph:
"""
RDFlib wrapper for graph operations.
Modes:
* local: Local file - can be queried and changed
* online: Online file - can only be queried, changes can be stored locally
* store: Triple store - can be queried and changed if update_endpoint available
To... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-3 | raise ValueError(
"Could not import rdflib python package. "
"Please install it with `pip install rdflib`."
)
if self.standard not in (supported_standards := ("rdf", "rdfs", "owl")):
raise ValueError(
f"Invalid standard. Supported standards... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-4 | @property
def get_schema(self) -> str:
"""
Returns the schema of the graph database.
"""
return self.schema
[docs] def query(
self,
query: str,
) -> List[rdflib.query.ResultRow]:
"""
Query the graph.
"""
from rdflib.exceptions im... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-5 | return (
"<"
+ str(res[var])
+ "> ("
+ self._get_local_name(res[var])
+ ", "
+ str(res["com"])
+ ")"
)
[docs] def load_schema(self) -> None:
"""
Load the graph schema information.
"""
def _rdf_... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
5ce6068d8d7e-6 | f"In the following, each IRI is followed by the local name and "
f"optionally its description in parentheses. \n"
f"The OWL graph supports the following node types:\n"
f'{", ".join([self._res_to_str(r, "cls") for r in clss])}\n'
f"The OWL graph supports th... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/rdf_graph.html |
8d026b39eccc-0 | Source code for langchain.load.dump
import json
from typing import Any, Dict
from langchain.load.serializable import Serializable, to_json_not_implemented
[docs]def default(obj: Any) -> Any:
"""Return a default value for a Serializable object or
a SerializedNotImplemented object."""
if isinstance(obj, Seria... | https://api.python.langchain.com/en/latest/_modules/langchain/load/dump.html |
7755b999bdc4-0 | Source code for langchain.load.serializable
from abc import ABC
from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
from langchain.pydantic_v1 import BaseModel, PrivateAttr
[docs]class BaseSerialized(TypedDict):
"""Base class for serialized objects."""
lc: int
id: List[str]
[docs]c... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
7755b999bdc4-1 | """List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
"""
return {}
[docs] @classmethod
def lc_id(cls) -> List[str]:
"""A unique identifier for this class for serialization purposes.
The unique id... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
7755b999bdc4-2 | if cls is Serializable:
break
if cls:
deprecated_attributes = [
"lc_namespace",
"lc_serializable",
]
for attr in deprecated_attributes:
if hasattr(cls, attr):
r... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
7755b999bdc4-3 | for part in parts:
if part not in current:
break
current[part] = current[part].copy()
current = current[part]
if last in current:
current[last] = {
"lc": 1,
"type": "secret",
"id": [secret_id],
... | https://api.python.langchain.com/en/latest/_modules/langchain/load/serializable.html |
0fbc0d92b28e-0 | Source code for langchain.load.load
import importlib
import json
import os
from typing import Any, Dict, List, Optional
from langchain.load.serializable import Serializable
[docs]class Reviver:
"""Reviver for JSON objects."""
[docs] def __init__(
self,
secrets_map: Optional[Dict[str, str]] = None... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
0fbc0d92b28e-1 | )
if (
value.get("lc", None) == 1
and value.get("type", None) == "constructor"
and value.get("id", None) is not None
):
[*namespace, name] = value["id"]
if namespace[0] not in self.valid_namespaces:
raise ValueError(f"Invalid na... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
0fbc0d92b28e-2 | [docs]def load(
obj: Any,
*,
secrets_map: Optional[Dict[str, str]] = None,
valid_namespaces: Optional[List[str]] = None,
) -> Any:
"""Revive a LangChain class from a JSON object. Use this if you already
have a parsed JSON object, eg. from `json.load` or `orjson.loads`.
Args:
obj: The... | https://api.python.langchain.com/en/latest/_modules/langchain/load/load.html |
4f627caec57f-0 | Source code for langchain.indexes.graph
"""Graph Index Creator."""
from typing import Optional, Type
from langchain.chains.llm import LLMChain
from langchain.graphs.networkx_graph import NetworkxEntityGraph, parse_triples
from langchain.indexes.prompts.knowledge_triplet_extraction import (
KNOWLEDGE_TRIPLE_EXTRACTI... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
4f627caec57f-1 | chain = LLMChain(llm=self.llm, prompt=prompt)
output = await chain.apredict(text=text)
knowledge = parse_triples(output)
for triple in knowledge:
graph.add_triple(triple)
return graph | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
c684f12c60d0-0 | Source code for langchain.indexes.vectorstore
from typing import Any, Dict, List, Optional, Type
from langchain.chains.qa_with_sources.retrieval import RetrievalQAWithSourcesChain
from langchain.chains.retrieval_qa.base import RetrievalQA
from langchain.document_loaders.base import BaseLoader
from langchain.embeddings.... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
c684f12c60d0-1 | )
return chain.run(question)
[docs] def query_with_sources(
self,
question: str,
llm: Optional[BaseLanguageModel] = None,
retriever_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Any
) -> dict:
"""Query the vectorstore and get back sources."""
l... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
c684f12c60d0-2 | vectorstore = self.vectorstore_cls.from_documents(
sub_docs, self.embedding, **self.vectorstore_kwargs
)
return VectorStoreIndexWrapper(vectorstore=vectorstore) | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
01a5c8d2eeb9-0 | Source code for langchain.indexes.base
from __future__ import annotations
import uuid
from abc import ABC, abstractmethod
from typing import List, Optional, Sequence
NAMESPACE_UUID = uuid.UUID(int=1984)
[docs]class RecordManager(ABC):
"""An abstract base class representing the interface for a record manager."""
[do... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
01a5c8d2eeb9-1 | """
[docs] @abstractmethod
def exists(self, keys: Sequence[str]) -> List[bool]:
"""Check if the provided keys exist in the database.
Args:
keys: A list of keys to check.
Returns:
A list of boolean values indicating the existence of each key.
"""
[docs] @... | https://api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
98a1629a750b-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 information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
@proper... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
92f8719656ec-0 | Source code for langchain.memory.utils
from typing import Any, Dict, List
[docs]def get_prompt_input_key(inputs: Dict[str, Any], memory_variables: List[str]) -> str:
"""
Get the prompt input key.
Args:
inputs: Dict[str, Any]
memory_variables: List[str]
Returns:
A prompt input key... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/utils.html |
3c0dbe077ed9-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get_entities, parse_triples
from langchain.memory.chat_memory import BaseChatMemory
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
3c0dbe077ed9-1 | 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)
context: Union[str, List]
if not summary_strings:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
3c0dbe077ed9-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://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
3c0dbe077ed9-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
dbb1d9b4771f-0 | Source code for langchain.memory.summary
from __future__ import annotations
from typing import Any, Dict, List, Type
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import SUMMARY_PROMPT
from langchain.pydantic_v1 import BaseModel, root_vali... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
dbb1d9b4771f-1 | *,
summarize_step: int = 2,
**kwargs: Any,
) -> ConversationSummaryMemory:
obj = cls(llm=llm, chat_memory=chat_memory, **kwargs)
for i in range(0, len(obj.chat_memory.messages), summarize_step):
obj.buffer = obj.predict_new_summary(
obj.chat_memory.message... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
dbb1d9b4771f-2 | self.chat_memory.messages[-2:], self.buffer
)
[docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
67267b0a9fbf-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List, Union
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema.messages import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
b8bbb36efad6-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Sequence, Union
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.pydantic_v1 import Field
from langchai... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.