id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
6a6d48ea842e-1 | " What is the nearest airport to {location}? Please respond with the "
" airport's International Air Transport Association (IATA) Location "
' Identifier in the following JSON format. JSON: "iataCode": "IATA '
' Location Identifier" '
)
llm = ChatOpenAI(temperature=0)... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/closest_airport.html |
9a26b9c99710-0 | Source code for langchain.tools.amadeus.utils
"""O365 tool utils."""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from amadeus import Client
logger = logging.getLogger(__name__)
[docs]def authenticate() -> Client:
"""Authenticate using the Amadeu... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/amadeus/utils.html |
f29f59d3783e-0 | Source code for langchain.tools.office365.events_search
"""Util that Searches calendar events in Office 365.
Free, but setup is required. See link below.
https://learn.microsoft.com/en-us/graph/auth/
"""
from datetime import datetime as dt
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseMode... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html |
f29f59d3783e-1 | " components, and the time zone offset is specified as ±hh:mm. "
' For example: "2023-06-09T10:30:00+03:00" represents June 9th, '
" 2023, at 10:30 AM in a time zone with a positive offset of 3 "
" hours from Coordinated Universal Time (UTC)."
)
)
max_results: int = F... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html |
f29f59d3783e-2 | extra = Extra.forbid
def _run(
self,
start_datetime: str,
end_datetime: str,
max_results: int = 10,
truncate: bool = True,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> List[Dict[str, Any]]:
TRUNCATE_LIMIT = 150
# Get calendar objec... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html |
f29f59d3783e-3 | "%Y-%m-%dT%H:%M:%S%z"
)
output_event["end_datetime"] = event.end.astimezone(time_zone).strftime(
"%Y-%m-%dT%H:%M:%S%z"
)
output_event["modified_date"] = event.modified.astimezone(
time_zone
).strftime("%Y-%m-%dT%H:%M:%S%z")
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html |
96f1531b3279-0 | Source code for langchain.tools.office365.base
"""Base class for Office 365 tools."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pydantic import Field
from langchain.tools.base import BaseTool
from langchain.tools.office365.utils import authenticate
if TYPE_CHECKING:
from O365 import A... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/base.html |
fc213c5eedb6-0 | Source code for langchain.tools.office365.send_message
from typing import List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.office365.base import O365BaseTool
[docs]class SendMessageSchema(BaseModel):
"""Input for SendMe... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html |
fc213c5eedb6-1 | message.body = body
message.subject = subject
message.to.add(to)
if cc is not None:
message.cc.add(cc)
if bcc is not None:
message.bcc.add(cc)
message.send()
output = "Message sent: " + str(message)
return output | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html |
ee3220847fbe-0 | Source code for langchain.tools.office365.messages_search
"""Util that Searches email messages in Office 365.
Free, but setup is required. See link below.
https://learn.microsoft.com/en-us/graph/auth/
"""
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra, Field
from langchain.call... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html |
ee3220847fbe-1 | "range example: received:2023-06-08..2023-06-09 matching example: "
"from:amy OR from:david."
)
)
max_results: int = Field(
default=10,
description="The maximum number of results to return.",
)
truncate: bool = Field(
default=True,
description=(
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html |
ee3220847fbe-2 | if folder != "":
mailbox = mailbox.get_folder(folder_name=folder)
# Retrieve messages based on query
query = mailbox.q().search(query)
messages = mailbox.get_messages(limit=max_results, query=query)
# Generate output dict
output_messages = []
for message in me... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html |
8dd5341eb80c-0 | Source code for langchain.tools.office365.create_draft_message
from typing import List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.office365.base import O365BaseTool
[docs]class CreateDraftMessageSchema(BaseModel):
"""I... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html |
8dd5341eb80c-1 | message = mailbox.new_message()
# Assign message values
message.body = body
message.subject = subject
message.to.add(to)
if cc is not None:
message.cc.add(cc)
if bcc is not None:
message.bcc.add(cc)
message.save_draft()
output = "Dr... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html |
7254177581f8-0 | Source code for langchain.tools.office365.send_event
"""Util that sends calendar events in Office 365.
Free, but setup is required. See link below.
https://learn.microsoft.com/en-us/graph/auth/
"""
from datetime import datetime as dt
from typing import List, Optional, Type
from pydantic import BaseModel, Field
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html |
7254177581f8-1 | " components, and the time zone offset is specified as ±hh:mm. "
' For example: "2023-06-09T10:30:00+03:00" represents June 9th, '
" 2023, at 10:30 AM in a time zone with a positive offset of 3 "
" hours from Coordinated Universal Time (UTC).",
)
[docs]class O365SendEvent(O365BaseTool):
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html |
68ac0df7d7bc-0 | Source code for langchain.tools.office365.utils
"""O365 tool utils."""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from O365 import Account
logger = logging.getLogger(__name__)
[docs]def clean_body(body: str) -> str:
"""Clean body of a message o... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html |
68ac0df7d7bc-1 | if account.is_authenticated is False:
if not account.authenticate(
scopes=[
"https://graph.microsoft.com/Mail.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/Calendars.ReadWrite",
"https://graph.microso... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html |
709f50f744ef-0 | Source code for langchain.tools.bing_search.tool
"""Tool for the Bing search API."""
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.base import BaseTool
from langchain.utilities.bing_search import BingSearchAPIWrapper
[docs]class BingSearchRun(BaseTool... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html |
c56883ef635e-0 | Source code for langchain.tools.nuclia.tool
"""Tool for the Nuclia Understanding API.
Installation:
```bash
pip install --upgrade protobuf
pip install nucliadb-protos
```
"""
import asyncio
import base64
import logging
import mimetypes
import os
from typing import Any, Dict, Optional, Type, Union
import request... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
c56883ef635e-1 | _config: Dict[str, Any] = {}
def __init__(self, enable_ml: bool = False) -> None:
zone = os.environ.get("NUCLIA_ZONE", "europe-1")
self._config["BACKEND"] = f"https://{zone}.nuclia.cloud/api/v1"
key = os.environ.get("NUCLIA_NUA_KEY")
if not key:
raise ValueError("NUCLIA_N... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
c56883ef635e-2 | if text:
self._pushText(id, text)
data = None
while True:
data = self._pull(id)
if data:
break
await asyncio.sleep(15)
return data
def _pushText(self, id: str, text: str) -> str:
field = {
"textfield": {"text... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
c56883ef635e-3 | response = requests.post(
self._config["BACKEND"] + "/processing/push",
headers={
"content-type": "application/json",
"x-stf-nuakey": "Bearer " + self._config["NUA_KEY"],
},
json=field,
)
if response.status_code != 200:
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
c56883ef635e-4 | "`pip install protobuf`."
) from e
res = requests.get(
self._config["BACKEND"] + "/processing/pull",
headers={
"x-stf-nuakey": "Bearer " + self._config["NUA_KEY"],
},
).json()
if res["status"] == "empty":
logger.info("Qu... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
899454e1e4af-0 | Source code for langchain.tools.google_places.tool
"""Tool for the Google search API."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.base import BaseTool
from langchain.utilities.google_places_api import G... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html |
8b0529e1af76-0 | Source code for langchain.tools.golden_query.tool
"""Tool for the Golden API."""
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.base import BaseTool
from langchain.utilities.golden_query import GoldenQueryAPIWrapper
[docs]class GoldenQueryRun(BaseTool)... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/golden_query/tool.html |
5319e164b73f-0 | Source code for langchain.tools.human.tool
"""Tool for asking human input."""
from typing import Callable, Optional
from pydantic import Field
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.base import BaseTool
def _print_func(text: str) -> None:
print("\n")
print(text)
[... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html |
b820cc1e143f-0 | Source code for langchain.tools.steamship_image_generation.tool
"""This tool allows agents to generate images using Steamship.
Steamship offers access to different third party image generation APIs
using a single API key.
Today the following models are supported:
- Dall-E
- Stable Diffusion
To use this tool, you must f... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
b820cc1e143f-1 | "Output: the UUID of a generated image"
)
@root_validator(pre=True)
def validate_size(cls, values: Dict) -> Dict:
if "size" in values:
size = values["size"]
model_name = values["model_name"]
if size not in SUPPORTED_IMAGE_SIZES[model_name]:
raise R... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
b820cc1e143f-2 | blocks = task.output.blocks
if len(blocks) > 0:
if self.return_urls:
return make_image_public(self.steamship, blocks[0])
else:
return blocks[0].id
raise RuntimeError(f"[{self.name}] Tool unable to generate image!") | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html |
2f61e129b892-0 | Source code for langchain.tools.steamship_image_generation.utils
"""Steamship Utils."""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from steamship import Block, Steamship
[docs]def make_image_public(client: Steamship, block: Block) -> str:
"""Upload a block ... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/utils.html |
a85f1d5d9cef-0 | Source code for langchain.graphs.nebula_graph
import logging
from string import Template
from typing import Any, Dict
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)
RETURN "(:" + tags(m)[0] + ")-[:$edge_type]->(:" + t... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
a85f1d5d9cef-1 | 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.username, self.password, self.address, self.port, self.s... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
a85f1d5d9cef-2 | @property
def get_schema(self) -> str:
"""Returns the schema of the NebulaGraph database"""
return self.schema
[docs] def execute(self, query: str, params: dict = {}, retry: int = 0) -> Any:
"""Query NebulaGraph database."""
from nebula3.Exception import IOErrorException, NoValidS... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
a85f1d5d9cef-3 | raise ValueError(f"Error executing query to NebulaGraph. Error: {e}")
except (TTransportException, IOErrorException):
# connection issue, try to recreate session pool
if retry < RETRY_TIMES:
retry += 1
logging.warning(
f"Connection issu... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
a85f1d5d9cef-4 | edge_types_schema.append(edge_schema)
# build relationships types
r = self.execute(
rel_query.substitute(edge_type=edge_type_name)
).column_values("rels")
if len(r) > 0:
relationships.append(r[0].cast())
self.schema = (
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
811334fadcec-0 | Source code for langchain.graphs.neptune_graph
import json
from typing import Any, Dict, List, Tuple, Union
import requests
[docs]class NeptuneQueryException(Exception):
"""A class to handle queries that fail to execute"""
def __init__(self, exception: Union[str, Dict]):
if isinstance(exception, dict):
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
811334fadcec-1 | try:
self._refresh_schema()
except NeptuneQueryException:
raise ValueError("Could not get schema for Neptune database")
@property
def get_schema(self) -> str:
"""Returns the schema of the Neptune database"""
return self.schema
[docs] def query(self, query: str,... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
811334fadcec-2 | n_labels = summary["nodeLabels"]
e_labels = summary["edgeLabels"]
return n_labels, e_labels
def _get_triples(self, e_labels: List[str]) -> List[str]:
triple_query = """
MATCH (a)-[e:{e_label}]->(b)
WITH a,e,b LIMIT 3000
RETURN DISTINCT labels(a) AS from, type(e) AS ed... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
811334fadcec-3 | "labels": label,
}
node_properties.append(np)
return node_properties
def _get_edge_properties(self, e_labels: List[str], types: Dict[str, Any]) -> List:
edge_properties_query = """
MATCH ()-[e:{e_label}]->()
RETURN properties(e) AS props
LIMIT 100
... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
811334fadcec-4 | The relationships are the following:
{triple_schema}
""" | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
ca3f570f726c-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 |
ca3f570f726c-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 |
ca3f570f726c-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 |
ca3f570f726c-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 |
ca3f570f726c-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 |
ca3f570f726c-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 |
ca3f570f726c-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 |
bdcc4038b00a-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 *
"""
[docs]class MemgraphGraph(Neo4jGraph):
"""Memgraph wrapper for graph operations."""
[docs] def __init__(
self, url: str, usernam... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/memgraph_graph.html |
0f0405ace6dd-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 |
0f0405ace6dd-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 |
0f0405ace6dd-2 | [docs] def query(
self, query: str, top_k: Optional[int] = None, **kwargs: Any
) -> List[Dict[str, Any]]:
"""Query the ArangoDB database."""
import itertools
cursor = self.__db.aql.execute(query, **kwargs)
return [doc for doc in itertools.islice(cursor, top_k)]
[docs] @... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
0f0405ace6dd-3 | 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 or set as environment
var ``ARANGODB_URL``. Defaults to "http://localhost:8529... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
0f0405ace6dd-4 | return ArangoClient(_url).db(_dbname, _username, _password, verify=True) | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
7df30e563a8a-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 |
7df30e563a8a-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 |
4c8d9235bb9b-0 | Source code for langchain.graphs.neo4j_graph
from typing import Any, Dict, List
node_properties_query = """
CALL apoc.meta.data()
YIELD label, other, elementType, type, property
WHERE NOT type = "RELATIONSHIP" AND elementType = "node"
WITH label AS nodeLabels, collect({property:property, type:type}) AS properties
RETUR... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
4c8d9235bb9b-1 | self._database = database
self.schema = ""
# Verify connection
try:
self._driver.verify_connectivity()
except neo4j.exceptions.ServiceUnavailable:
raise ValueError(
"Could not connect to Neo4j database. "
"Please ensure that the url... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
4c8d9235bb9b-2 | relationships_properties = self.query(rel_properties_query)
relationships = self.query(rel_query)
self.schema = f"""
Node properties are the following:
{[el['output'] for el in node_properties]}
Relationship properties are the following:
{[el['output'] for el in relations... | https://api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
00322734d04d-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 |
00322734d04d-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 |
fe158f4d019a-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 |
fe158f4d019a-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 |
fe158f4d019a-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 |
fe158f4d019a-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 |
988618d66ab1-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.formatting import formatter
from langchain.schema.messages import BaseMessage, HumanMessage
from langchain.sc... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
988618d66ab1-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 |
988618d66ab1-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 |
9e057ead08e3-0 | Source code for langchain.prompts.pipeline
from typing import Any, Dict, List, Tuple
from pydantic import root_validator
from langchain.prompts.chat import BaseChatPromptTemplate
from langchain.schema import BasePromptTemplate, PromptValue
def _get_inputs(inputs: dict, input_variables: List[str]) -> dict:
return {k... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/pipeline.html |
9e057ead08e3-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 |
22397d2ea558-0 | Source code for langchain.prompts.loading
"""Load prompts."""
import json
import logging
from pathlib import Path
from typing import Union
import yaml
from langchain.output_parsers.regex import RegexParser
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
f... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
22397d2ea558-1 | # Load the template.
if template_path.suffix == ".txt":
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_example... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
22397d2ea558-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 |
22397d2ea558-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 |
cc03e0eae319-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union
from pydantic import Field, root_validator
from langchain.load.serializable imp... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-1 | Combined prompt template.
"""
prompt = ChatPromptTemplate(messages=[self])
return prompt + other
[docs]class MessagesPlaceholder(BaseMessagePromptTemplate):
"""Prompt template that assumes variable is already list of messages."""
variable_name: str
"""Name of variable to use as messa... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-2 | """Additional keyword arguments to pass to the prompt template."""
[docs] @classmethod
def from_template(
cls: Type[MessagePromptTemplateT],
template: str,
template_format: str = "f-string",
**kwargs: Any,
) -> MessagePromptTemplateT:
"""Create a class from a string te... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-3 | """Format messages from kwargs.
Args:
**kwargs: Keyword arguments to use for formatting.
Returns:
List of BaseMessages.
"""
return [self.format(**kwargs)]
@property
def input_variables(self) -> List[str]:
"""
Input variables for this prompt... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-4 | """Format the prompt template.
Args:
**kwargs: Keyword arguments to use for formatting.
Returns:
Formatted message.
"""
text = self.prompt.format(**kwargs)
return AIMessage(content=text, additional_kwargs=self.additional_kwargs)
[docs]class SystemMessagePr... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-5 | formatted string
"""
return self.format_prompt(**kwargs).to_string()
[docs] def format_prompt(self, **kwargs: Any) -> PromptValue:
"""
Format prompt. Should return a PromptValue.
Args:
**kwargs: Keyword arguments to use for formatting.
Returns:
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-6 | """Combine two prompt templates.
Args:
other: Another prompt template.
Returns:
Combined prompt template.
"""
# Allow for easy combining
if isinstance(other, ChatPromptTemplate):
return ChatPromptTemplate(messages=self.messages + other.messages... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-7 | else:
values["input_variables"] = list(input_vars)
return values
[docs] @classmethod
def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
"""Create a chat prompt template from a template string.
Creates a chat template consisting of a single message assu... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-8 | [docs] @classmethod
def from_messages(
cls,
messages: Sequence[
Union[
BaseMessagePromptTemplate,
BaseChatPromptTemplate,
BaseMessage,
Tuple[str, str],
Tuple[Type, str],
str,
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-9 | _message, (BaseChatPromptTemplate, BaseMessagePromptTemplate)
):
input_vars.update(_message.input_variables)
return cls(input_variables=sorted(input_vars), messages=_messages)
[docs] def format(self, **kwargs: Any) -> str:
"""Format the chat template into a string.
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-10 | filled in.
Args:
**kwargs: keyword arguments to use for filling in template variables. Ought
to be a subset of the input variables.
Returns:
A new ChatPromptTemplate.
Example:
.. code-block:: python
from langchain.prompt... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-11 | template: str the template string.
Returns:
a message prompt template of the appropriate type.
"""
if message_type == "human":
message: BaseMessagePromptTemplate = HumanMessagePromptTemplate.from_template(
template
)
elif message_type == "ai":
message = AIMess... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
cc03e0eae319-12 | BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate
] = message
elif isinstance(message, BaseMessage):
_message = message
elif isinstance(message, str):
_message = _create_template_from_message_type("human", message)
elif isinstance(message, tuple):
if len(message)... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
4ad9a4dcdce9-0 | Source code for langchain.prompts.prompt
"""Prompt schema definition."""
from __future__ import annotations
from pathlib import Path
from string import Formatter
from typing import Any, Dict, List, Optional, Union
from pydantic import root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
4ad9a4dcdce9-1 | def __add__(self, other: Any) -> PromptTemplate:
"""Override the + operator to allow for combining prompt templates."""
# Allow for easy combining
if isinstance(other, PromptTemplate):
if self.template_format != "f-string":
raise ValueError(
"Addin... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
4ad9a4dcdce9-2 | Args:
kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
return DE... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
4ad9a4dcdce9-3 | Returns:
The final prompt generated.
"""
template = example_separator.join([prefix, *examples, suffix])
return cls(input_variables=input_variables, template=template, **kwargs)
[docs] @classmethod
def from_file(
cls, template_file: Union[str, Path], input_variables: Li... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
4ad9a4dcdce9-4 | `"foo {variable2}"`.
Returns:
The prompt template loaded from the template.
"""
if template_format == "jinja2":
# Get the variables for the template
input_variables = _get_jinja2_variables_from_template(template)
elif template_format == "f-string":
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
446f2fdfd839-0 | Source code for langchain.prompts.few_shot_with_templates
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate
from langchain.prompts.example_selec... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
446f2fdfd839-1 | examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_selector' should be provided"
)
if examples is None and example_selecto... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
446f2fdfd839-2 | Args:
kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
# Get the example... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
446f2fdfd839-3 | """Return a dictionary of the prompt."""
if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
074ec12427ee-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 pydantic import BaseModel, Extra, Field, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
St... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
074ec12427ee-1 | )
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.
Returns:
List of examples.
"""
if self.examples ... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
074ec12427ee-2 | 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"],
values[... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
074ec12427ee-3 | [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)
[docs]class FewShotChatMessagePromptTemplate(
BaseChatPrompt... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.