id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
9a18d086743f-0 | Source code for langchain.graphs.kuzu_graph
from typing import Any, Dict, List
[docs]class KuzuGraph:
"""Kùzu wrapper for graph operations.
*Security note*: Make sure that the database connection uses credentials
that are narrowly-scoped to only include necessary permissions.
Failure to do so ma... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html |
9a18d086743f-1 | column_names = result.get_column_names()
return_list = []
while result.has_next():
row = result.get_next()
return_list.append(dict(zip(column_names, row)))
return return_list
[docs] def refresh_schema(self) -> None:
"""Refreshes the Kùzu graph schema informatio... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html |
9a18d086743f-2 | table["name"]
).split("\n")
for i, line in enumerate(properties_text):
# The first 3 lines defines src, dst and name, so we skip them
if i < 3:
continue
if not line:
continue
property_name, pr... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/kuzu_graph.html |
a830323f4010-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
a830323f4010-1 | data is present in the database.
The best way to guard against such negative outcomes is to (as appropriate)
limit the permissions granted to the credentials used with this tool.
See https://python.langchain.com/docs/security for more information.
"""
[docs] def __init__(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
a830323f4010-2 | "Please install it with `pip install boto3`."
)
except Exception as e:
if type(e).__name__ == "UnknownServiceError":
raise ModuleNotFoundError(
"NeptuneGraph requires a boto3 version 1.28.38 or greater."
"Please install it with `pip... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
a830323f4010-3 | "ensure the engine version is >=1.2.1.0"
),
"details": str(e),
}
)
try:
summary = response["payload"]["graphSummary"]
except Exception:
raise NeptuneQueryException(
{
"message"... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
a830323f4010-4 | node_properties_query = """
MATCH (a:`{n_label}`)
RETURN properties(a) AS props
LIMIT 100
"""
node_properties = []
for label in n_labels:
q = node_properties_query.format(n_label=label)
data = {"label": label, "properties": self.query(q)["results"]... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
a830323f4010-5 | Refreshes the Neptune graph schema information.
"""
types = {
"str": "STRING",
"float": "DOUBLE",
"int": "INTEGER",
"list": "LIST",
"dict": "MAP",
"bool": "BOOLEAN",
}
n_labels, e_labels = self._get_labels()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neptune_graph.html |
e8d39e6beec3-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: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
e8d39e6beec3-1 | that are narrowly-scoped to only include necessary permissions.
Failure to do so may result in data corruption or loss, since the calling
code may attempt commands that would result in deletion, mutation
of data if appropriately prompted or reading sensitive data if such
data is present ... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
e8d39e6beec3-2 | # Creates nodes if they don't exist
# Overwrites existing edges
if not self._graph.has_node(knowledge_triple.subject):
self._graph.add_node(knowledge_triple.subject)
if not self._graph.has_node(knowledge_triple.object_):
self._graph.add_node(knowledge_triple.object_)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
e8d39e6beec3-3 | import networkx as nx
nx.write_gml(self._graph, path)
[docs] def clear(self) -> None:
"""Clear the graph."""
self._graph.clear()
[docs] def get_topological_sort(self) -> List[str]:
"""Get a list of entity names in the graph sorted by causal dependence."""
import networkx as... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
e8d39e6beec3-4 | graph.layout(prog=kwargs.get("prog", "dot"))
graph.draw(kwargs.get("path", "graph.svg")) | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/networkx_graph.html |
a7058a339ea3-0 | Source code for langchain.graphs.neo4j_graph
from typing import Any, Dict, List, Optional
from langchain.graphs.graph_document import GraphDocument
from langchain.graphs.graph_store import GraphStore
from langchain.utils import get_from_env
node_properties_query = """
CALL apoc.meta.data()
YIELD label, other, elementTy... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a7058a339ea3-1 | The best way to guard against such negative outcomes is to (as appropriate)
limit the permissions granted to the credentials used with this tool.
See https://python.langchain.com/docs/security for more information.
"""
[docs] def __init__(
self,
url: Optional[str] = None,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a7058a339ea3-2 | "Please ensure that the username and password are correct"
)
# Set schema
try:
self.refresh_schema()
except neo4j.exceptions.ClientError:
raise ValueError(
"Could not use APOC procedures. "
"Please ensure the APOC plugin is inst... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a7058a339ea3-3 | "rel_props": {el["type"]: el["properties"] for el in rel_properties},
"relationships": relationships,
}
self.schema = f"""
Node properties are the following:
{node_properties}
Relationship properties are the following:
{rel_properties}
The relationship... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
a7058a339ea3-4 | self.query(
"UNWIND $data AS row "
"CALL apoc.merge.node([row.source_label], {id: row.source},"
"{}, {}) YIELD node as source "
"CALL apoc.merge.node([row.target_label], {id: row.target},"
"{}, {}) YIELD node as target "
"CA... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/neo4j_graph.html |
8835e4fc83b3-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/graph_document.html |
b0c785826f45-0 | Source code for langchain.graphs.hugegraph
from typing import Any, Dict, List
[docs]class HugeGraph:
"""HugeGraph wrapper for graph operations.
*Security note*: Make sure that the database connection uses credentials
that are narrowly-scoped to only include necessary permissions.
Failure to do s... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html |
b0c785826f45-1 | try:
self.refresh_schema()
except Exception as e:
raise ValueError(f"Could not refresh schema. Error: {e}")
@property
def get_schema(self) -> str:
"""Returns the schema of the HugeGraph database"""
return self.schema
[docs] def refresh_schema(self) -> None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/hugegraph.html |
ade25e025f6a-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.
*Security note*: Make sure that the database connection uses credentials
that are narrowly-scoped to only includ... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
ade25e025f6a-1 | Auto-generates Schema if **schema** is None.
"""
self.__schema = self.generate_schema() if schema is None else schema
[docs] def generate_schema(
self, sample_ratio: float = 0
) -> Dict[str, List[Dict[str, Any]]]:
"""
Generates the schema of the ArangoDB Database and retur... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
ade25e025f6a-2 | LIMIT {limit_amount}
RETURN doc
"""
doc: Dict[str, Any]
properties: List[Dict[str, str]] = []
for doc in self.__db.aql.execute(aql):
for key, value in doc.items():
properties.append({"name": key, "type": type(value).... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
ade25e025f6a-3 | environment var ``ARANGODB_DBNAME``. Defaults to "_system".
username: Can be passed in as named arg or set as environment var
``ARANGODB_USERNAME``. Defaults to "root".
password: Can be passed ni as named arg or set as environment var
``ARANGODB_PASSWORD``. Defaul... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
ade25e025f6a-4 | ) from e
_url: str = url or os.environ.get("ARANGODB_URL", "http://localhost:8529") # type: ignore[assignment] # noqa: E501
_dbname: str = dbname or os.environ.get("ARANGODB_DBNAME", "_system") # type: ignore[assignment] # noqa: E501
_username: str = username or os.environ.get("ARANGODB_USERNAME", "root... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/arangodb_graph.html |
b23bed57542e-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
b23bed57542e-1 | ) -> None:
"""Create a new NebulaGraph wrapper instance."""
try:
import nebula3 # noqa: F401
import pandas # noqa: F401
except ImportError:
raise ValueError(
"Please install NebulaGraph Python client and pandas first: "
"`pip ... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
b23bed57542e-2 | )
try:
session_pool.init(config)
except AuthFailedException:
raise ValueError(
"Could not connect to NebulaGraph database. "
"Please ensure that the username and password are correct"
)
except RuntimeError as e:
rais... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
b23bed57542e-3 | )
raise ValueError(
f"No valid session found in session pool. "
f"Please consider increasing the session pool size. "
f"Current size: {self.session_pool_size}"
)
except RuntimeError as e:
if retry < RETRY_TIMES:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
b23bed57542e-4 | for i in range(r.row_size()):
tag_schema["properties"].append((props[i].cast(), types[i].cast()))
tags_schema.append(tag_schema)
for edge_type in self.execute("SHOW EDGES").column_values("Name"):
edge_type_name = edge_type.cast()
edge_schema = {"edge": edge_ty... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/nebula_graph.html |
702633c1c847-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/memgraph_graph.html |
447fc2513621-0 | Source code for langchain.graphs.falkordb_graph
from typing import Any, Dict, List, Optional
from langchain.graphs.graph_document import GraphDocument
from langchain.graphs.graph_store import GraphStore
node_properties_query = """
MATCH (n)
WITH keys(n) as keys, labels(n) AS labels
WITH CASE WHEN keys = [] THEN [NULL] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
447fc2513621-1 | data is present in the database.
The best way to guard against such negative outcomes is to (as appropriate)
limit the permissions granted to the credentials used with this tool.
See https://python.langchain.com/docs/security for more information.
"""
[docs] def __init__(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
447fc2513621-2 | """Refreshes the schema of the FalkorDB database"""
node_properties: List[Any] = self.query(node_properties_query)
rel_properties: List[Any] = self.query(rel_properties_query)
relationships: List[Any] = self.query(rel_query)
self.structured_schema = {
"node_props": {el[0]["la... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
447fc2513621-3 | "RETURN distinct 'done' AS result"
),
{"properties": node.properties},
)
# Import relationships
for rel in document.relationships:
self.query(
(
f"MATCH (a:{rel.source.type} {{id:'... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/falkordb_graph.html |
b76a57615593-0 | Source code for langchain.graphs.graph_store
from abc import abstractmethod
from typing import Any, Dict, List
from langchain.graphs.graph_document import GraphDocument
[docs]class GraphStore:
"""An abstract class wrapper for graph operations."""
@property
@abstractmethod
def get_schema(self) -> str:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/graphs/graph_store.html |
7107e9278fff-0 | Source code for langchain.llms.cerebriumai
import logging
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, Field, root_v... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
7107e9278fff-1 | extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_nam... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
7107e9278fff-2 | from cerebrium import model_api_request
except ImportError:
raise ValueError(
"Could not import cerebrium python package. "
"Please install it with `pip install cerebrium`."
)
params = self.model_kwargs or {}
response = model_api_request(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
d4ba7116d9a9-0 | Source code for langchain.llms.chatglm
import logging
from typing import Any, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
logger = logging.getLogger(__name__)
[docs]class... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html |
d4ba7116d9a9-1 | return {
**{"endpoint_url": self.endpoint_url},
**{"model_kwargs": _model_kwargs},
}
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
""... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html |
d4ba7116d9a9-2 | # Check if response content does exists
if isinstance(parsed_response, dict):
content_keys = "response"
if content_keys in parsed_response:
text = parsed_response[content_keys]
else:
raise ValueError(f"No content in resp... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/chatglm.html |
08d6223e104d-0 | Source code for langchain.llms.huggingface_hub
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra, root_validator
from lang... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
08d6223e104d-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
08d6223e104d-2 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html |
39a0014d469a-0 | Source code for langchain.llms.amazon_api_gateway
from typing import Any, Dict, List, Mapping, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.pydantic_v1 import Extra
[docs]... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html |
39a0014d469a-1 | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"api_url": self.api_url, "headers": self.headers},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/amazon_api_gateway.html |
81b97065f8fd-0 | Source code for langchain.llms.azureml_endpoint
import json
import urllib.request
import warnings
from abc import abstractmethod
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Ba... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-1 | result = response.read()
return result
[docs]class ContentFormatterBase:
"""Transform request and response of AzureML endpoint to match with
required schema.
"""
"""
Example:
.. code-block:: python
class ContentFormatter(ContentFormatterBase):
con... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-2 | prompt = prompt.replace(escape_sequence, escaped_sequence)
return prompt
[docs] @abstractmethod
def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:
"""Formats the request body according to the input schema of
the model. Returns bytes or seekable file like object in... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-3 | """
)
[docs]class HFContentFormatter(ContentFormatterBase):
"""Content handler for LLMs from the HuggingFace catalog."""
[docs] def format_request_payload(self, prompt: str, model_kwargs: Dict) -> bytes:
ContentFormatterBase.escape_special_characters(prompt)
request_payload = json.dumps(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-4 | "parameters": model_kwargs,
}
}
)
return str.encode(request_payload)
[docs] def format_response_payload(self, output: bytes) -> str:
"""Formats response"""
return json.loads(output)[0]["0"]
[docs]class AzureMLOnlineEndpoint(LLM, BaseModel):
"""Azure ML ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-5 | """Validate that api key and python package exists in environment."""
endpoint_key = get_from_dict_or_env(
values, "endpoint_api_key", "AZUREML_ENDPOINT_API_KEY"
)
endpoint_url = get_from_dict_or_env(
values, "endpoint_url", "AZUREML_ENDPOINT_URL"
)
deploy... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
81b97065f8fd-6 | request_payload = self.content_formatter.format_request_payload(
prompt, _model_kwargs
)
response_payload = self.http_client.call(request_payload, **kwargs)
generated_text = self.content_formatter.format_response_payload(
response_payload
)
return generate... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/azureml_endpoint.html |
961c0eb8f5f8-0 | Source code for langchain.llms.minimax
"""Wrapper around Minimax APIs."""
from __future__ import annotations
import logging
from typing import (
Any,
Dict,
List,
Optional,
)
import requests
from langchain.callbacks.manager import (
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
from... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
961c0eb8f5f8-1 | f"API {response.json()['base_resp']['status_code']}"
f" error: {response.json()['base_resp']['status_msg']}"
)
return response.json()["reply"]
[docs]class MinimaxCommon(BaseModel):
"""Common parameters for Minimax large language models."""
_client: Any = None
model: str =... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
961c0eb8f5f8-2 | "minimax_api_host",
"MINIMAX_API_HOST",
default="https://api.minimax.chat",
)
return values
@property
def _default_params(self) -> Dict[str, Any]:
"""Get the default parameters for calling OpenAI API."""
return {
"model": self.model,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
961c0eb8f5f8-3 | """
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
r"""Call out to Minimax's completion endpoint to chat
Args:
prompt: The prompt to pass into the... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/minimax.html |
8d42d338d2a0-0 | Source code for langchain.llms.xinference
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Mapping, Optional, Union
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
if TYPE_CHECKING:
from xinference.client import RESTfulChatModelHandle, RESTfulGenerat... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html |
8d42d338d2a0-1 | server_url="http://0.0.0.0:9997",
model_uid = {model_uid} # replace model_uid with the model UID return from launching the model
)
llm(
prompt="Q: where can we visit in the capital of France? A:",
generate_config={"max_tokens": 1024, "stream": True},
)
To ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html |
8d42d338d2a0-2 | self.client = RESTfulClient(server_url)
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "xinference"
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"server_url": self.serve... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html |
8d42d338d2a0-3 | else:
completion = model.generate(prompt=prompt, generate_config=generate_config)
return completion["choices"][0]["text"]
def _stream_generate(
self,
model: Union["RESTfulGenerateModelHandle", "RESTfulChatModelHandle"],
prompt: str,
run_manager: Optional[Callb... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/xinference.html |
b3a209a7cd08-0 | Source code for langchain.llms.together
"""Wrapper around Together AI's Completion API."""
import logging
from typing import Any, Dict, List, Optional
from aiohttp import ClientSession
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base i... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html |
b3a209a7cd08-1 | for question answering or summarization. A value greater than 1 introduces more
randomness in the output.
"""
top_k: Optional[int] = None
"""Used to limit the number of choices for the next predicted word or token. It
specifies the maximum number of tokens to consider at each step, based o... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html |
b3a209a7cd08-2 | [docs] @staticmethod
def get_user_agent() -> str:
from langchain import __version__
return f"langchain/{__version__}"
@property
def default_params(self) -> Dict[str, Any]:
return {
"model": self.model,
"temperature": self.temperature,
"top_p": s... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html |
b3a209a7cd08-3 | if response.status_code >= 500:
raise Exception(f"Together Server: Error {response.status_code}")
elif response.status_code >= 400:
raise ValueError(f"Together received an invalid payload: {response.text}")
elif response.status_code != 200:
raise Exception(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html |
b3a209a7cd08-4 | async with ClientSession() as session:
async with session.post(
self.base_url, json=payload, headers=headers
) as response:
if response.status >= 500:
raise Exception(f"Together Server: Error {response.status}")
elif response.st... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/together.html |
1e22e36802e2-0 | Source code for langchain.llms.bittensor
import http.client
import json
import ssl
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
[docs]class NIBittensorLLM(LLM):
"""NIBittensor LLMs
NIBittensorLLM is created b... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html |
1e22e36802e2-1 | system_prompt(str): A system prompt defining how your model should respond.
top_responses(int): Total top miner responses to retrieve from Bittensor
protocol.
Return:
The generated response(s).
Example:
.. code-block:: python
from langc... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html |
1e22e36802e2-2 | # Creating Header and getting top benchmark miner uids
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"Endpoint-Version": "2023-05-19",
}
conn.request("GET", "/top_miner_uids", headers=headers)
miner_response = co... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html |
1e22e36802e2-3 | "messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt},
],
}
)
conn.request("POST", "/chat", payload, headers)
response = conn.getresponse()
utf_st... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/bittensor.html |
b919950053b7-0 | Source code for langchain.llms.deepinfra
import json
from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional
import aiohttp
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM, GenerationChunk
from langch... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
b919950053b7-1 | return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_id": self.model_id},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
b919950053b7-2 | **kwargs: Any,
) -> str:
"""Call out to DeepInfra's inference API endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
b919950053b7-3 | )
self._handle_status(response.status_code, response.text)
for line in _parse_stream(response.iter_lines()):
chunk = _handle_sse_line(line)
if chunk:
yield chunk
if run_manager:
run_manager.on_llm_new_token(chunk.text)
async... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
b919950053b7-4 | # SSE event may be valid when it contain whitespace
line = line[len(b"data: ") :]
else:
line = line[len(b"data:") :]
if line.strip() == b"[DONE]":
# return here will cause GeneratorExit exception in urllib3
# and it will close http connection with TCP Rese... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepinfra.html |
9924e9867f8f-0 | Source code for langchain.llms.titan_takeoff_pro
from typing import Any, Iterator, List, Mapping, Optional
import requests
from requests.exceptions import ConnectionError
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_to... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html |
9924e9867f8f-1 | @property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling Titan Takeoff Server (Pro)."""
return {
**(
{"regex_string": self.regex_string}
if self.regex_string is not None
else {}
),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html |
9924e9867f8f-2 | **kwargs: Any,
) -> str:
"""Call out to Titan Takeoff (Pro) generate endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html |
9924e9867f8f-3 | **kwargs: Any,
) -> Iterator[GenerationChunk]:
"""Call out to Titan Takeoff (Pro) stream endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html |
9924e9867f8f-4 | chunk = GenerationChunk(text=buffer.replace("</s>", ""))
yield chunk
if run_manager:
run_manager.on_llm_new_token(token=chunk.text)
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {"base_url": self... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/titan_takeoff_pro.html |
e6b77633a886-0 | Source code for langchain.llms.yandex
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.load.serializab... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html |
e6b77633a886-1 | """Validate that iam token exists in environment."""
iam_token = get_from_dict_or_env(values, "iam_token", "YC_IAM_TOKEN", "")
values["iam_token"] = iam_token
api_key = get_from_dict_or_env(values, "api_key", "YC_API_KEY", "")
values["api_key"] = api_key
if api_key == "" and iam_... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html |
e6b77633a886-2 | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call the Yandex GPT model and return the output.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html |
e6b77633a886-3 | else:
metadata = (("authorization", f"Api-Key {self.api_key}"),)
res = stub.Instruct(request, metadata=metadata)
text = list(res)[0].alternatives[0].text
if stop is not None:
text = enforce_stop_tokens(text, stop)
return text
async def _acall(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html |
e6b77633a886-4 | operation_api_url = "operation.api.cloud.yandex.net:443"
channel_credentials = grpc.ssl_channel_credentials()
async with grpc.aio.secure_channel(self.url, channel_credentials) as channel:
request = InstructRequest(
model=self.model_name,
request_text=prompt,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/yandex.html |
c642eaca5eef-0 | Source code for langchain.llms.deepsparse
# flake8: noqa
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
from langchain.pydantic_v1 import root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain.llms.base imp... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
c642eaca5eef-1 | max_length, max_new_tokens, num_return_sequences, output_scores,
top_p, top_k, repetition_penalty."""
streaming: bool = False
"""Whether to stream the results, token by token."""
@property
def _identifying_params(self) -> Dict[str, Any]:
"""Get the identifying parameters."""
return {... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
c642eaca5eef-2 | Returns:
The generated text.
Example:
.. code-block:: python
from langchain.llms import DeepSparse
llm = DeepSparse(model="zoo:nlg/text_generation/codegen_mono-350m/pytorch/huggingface/bigpython_bigquery_thepile/base_quant-none")
llm("Tell ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
c642eaca5eef-3 | """
if self.streaming:
combined_output = ""
async for chunk in self._astream(
prompt=prompt, stop=stop, run_manager=run_manager, **kwargs
):
combined_output += chunk.text
text = combined_output
else:
text = (
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
c642eaca5eef-4 | stop=["'","\n"]):
print(chunk, end='', flush=True)
"""
inference = self.pipeline(
sequences=prompt, generation_config=self.generation_config, streaming=True
)
for token in inference:
chunk = GenerationChunk(text=token.generations[0].text)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
c642eaca5eef-5 | sequences=prompt, generation_config=self.generation_config, streaming=True
)
for token in inference:
chunk = GenerationChunk(text=token.generations[0].text)
yield chunk
if run_manager:
await run_manager.on_llm_new_token(token=chunk.text) | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/deepsparse.html |
319b845ed006-0 | Source code for langchain.llms.baseten
import logging
from typing import Any, Dict, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.pydantic_v1 import Field
logger = logging.getLogger(__name__)
[docs]class Baseten(LLM):
"""B... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
319b845ed006-1 | return "baseten"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Baseten deployed model endpoint."""
try:
import baseten
except ... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/baseten.html |
463f176f76a2-0 | Source code for langchain.llms.vertexai
from __future__ import annotations
from concurrent.futures import Executor, ThreadPoolExecutor
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Iterator,
List,
Optional,
Union,
)
from langchain.callbacks.manager import (
A... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
463f176f76a2-1 | Args:
model_name: The model name to check.
Returns: True if the model name is a Codey model.
"""
return "code" in model_name
def _create_retry_decorator(
llm: VertexAI,
*,
run_manager: Optional[
Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
] = None,
) -> Cal... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
463f176f76a2-2 | ) -> Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator(llm, run_manager=run_manager)
@retry_decorator
def _completion_with_retry(*args: Any, **kwargs: Any) -> Any:
return llm.client.predict_streaming(*args, **kwargs)
return _completion_with_retry... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
463f176f76a2-3 | "Optional list of stop words to use when generating."
model_name: Optional[str] = None
"Underlying model name."
@classmethod
def _get_task_executor(cls, request_parallelism: int = 5) -> Executor:
if cls.task_executor is None:
cls.task_executor = ThreadPoolExecutor(max_workers=request... | lang/api.python.langchain.com/en/latest/_modules/langchain/llms/vertexai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.