id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
28,630
from __future__ import annotations from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Iterator, List, Optional, Union from langchain_core.chat_sessions import ChatSession from langchain_core.messages import HumanMessage from langchain_community.chat_loaders.base import BaseChatLoad...
null
28,631
from __future__ import annotations import importlib from typing import ( Any, AsyncIterator, Dict, Iterable, List, Mapping, Sequence, Union, overload, ) from langchain_core.chat_sessions import ChatSession from langchain_core.messages import ( AIMessage, AIMessageChunk, B...
Async version of enumerate function.
28,632
from __future__ import annotations import importlib from typing import ( Any, AsyncIterator, Dict, Iterable, List, Mapping, Sequence, Union, overload, ) from langchain_core.chat_sessions import ChatSession from langchain_core.messages import ( AIMessage, AIMessageChunk, B...
Convert dictionaries representing OpenAI messages to LangChain format. Args: messages: List of dictionaries representing OpenAI messages Returns: List of LangChain BaseMessage objects.
28,633
from __future__ import annotations import importlib from typing import ( Any, AsyncIterator, Dict, Iterable, List, Mapping, Sequence, Union, overload, ) from langchain_core.chat_sessions import ChatSession from langchain_core.messages import ( AIMessage, AIMessageChunk, B...
null
28,634
from __future__ import annotations import importlib from typing import ( Any, AsyncIterator, Dict, Iterable, List, Mapping, Sequence, Union, overload, ) from langchain_core.chat_sessions import ChatSession from langchain_core.messages import ( AIMessage, AIMessageChunk, B...
Convert messages to a list of lists of dictionaries for fine-tuning. Args: sessions: The chat sessions. Returns: The list of lists of dictionaries.
28,635
import os from math import ceil from typing import Any, Dict, List, Optional The provided code snippet includes necessary dependencies for implementing the `get_arangodb_client` function. Write a Python function `def get_arangodb_client( url: Optional[str] = None, dbname: Optional[str] = None, username: Op...
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". dbname: Arango DB name. Can be passed in as named arg or set as environment var ``ARANGODB_DBNAME``. Defaults to "_system". username: Can be...
28,636
from __future__ import annotations from typing import Any, List, NamedTuple, Optional, Tuple KG_TRIPLE_DELIMITER = "<|>" class KnowledgeTriple(NamedTuple): """A triple in the graph.""" subject: str predicate: str object_: str def from_string(cls, triple_string: str) -> "KnowledgeTriple": """...
Parse knowledge triples from the knowledge string.
28,637
from __future__ import annotations from typing import Any, List, NamedTuple, Optional, Tuple The provided code snippet includes necessary dependencies for implementing the `get_entities` function. Write a Python function `def get_entities(entity_str: str) -> List[str]` to solve the following problem: Extract entities ...
Extract entities from entity string.
28,638
from hashlib import md5 from typing import Any, Dict, List, Optional from langchain_core.utils import get_from_dict_or_env from langchain_community.graphs.graph_document import GraphDocument from langchain_community.graphs.graph_store import GraphStore The provided code snippet includes necessary dependencies for impl...
Sanitize the input dictionary or list. Sanitizes the input by removing embedding-like values, lists with more than 128 elements, that are mostly irrelevant for generating answers in a LLM context. These properties, if left in results, can occupy significant context space and detract from the LLM's performance by introd...
28,639
from hashlib import md5 from typing import Any, Dict, List, Optional from langchain_core.utils import get_from_dict_or_env from langchain_community.graphs.graph_document import GraphDocument from langchain_community.graphs.graph_store import GraphStore BASE_ENTITY_LABEL = "__Entity__" include_docs_query = ( "MERGE ...
null
28,640
from hashlib import md5 from typing import Any, Dict, List, Optional from langchain_core.utils import get_from_dict_or_env from langchain_community.graphs.graph_document import GraphDocument from langchain_community.graphs.graph_store import GraphStore BASE_ENTITY_LABEL = "__Entity__" def _get_rel_import_query(baseEnt...
null
28,641
import os import tempfile from urllib.parse import urlparse import requests The provided code snippet includes necessary dependencies for implementing the `detect_file_src_type` function. Write a Python function `def detect_file_src_type(file_path: str) -> str` to solve the following problem: Detect if the file is loc...
Detect if the file is local or remote.
28,642
import os import tempfile from urllib.parse import urlparse import requests The provided code snippet includes necessary dependencies for implementing the `download_audio_from_url` function. Write a Python function `def download_audio_from_url(audio_url: str) -> str` to solve the following problem: Download audio from...
Download audio from url to local.
28,643
from __future__ import annotations import logging import os from typing import TYPE_CHECKING logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `authenticate` function. Write a Python function `def authenticate() -> Client` to solve the following problem...
Authenticate using the Amadeus API
28,644
import json from typing import Any, Dict, Optional, Union from langchain_core.pydantic_v1 import BaseModel from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_community.utilities.requests import GenericRequestsWrapper from langchain_core.tools impor...
Parse the json string into a dict.
28,645
import json from typing import Any, Dict, Optional, Union from langchain_core.pydantic_v1 import BaseModel from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_community.utilities.requests import GenericRequestsWrapper from langchain_core.tools impor...
Strips quotes from the url.
28,646
from __future__ import annotations import json from typing import Optional, Type import requests import yaml from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.pydantic_v1 import BaseModel from langchain_core.tools import BaseTool The provide...
Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict.
28,647
import ast import io import sys import tokenize The provided code snippet includes necessary dependencies for implementing the `interleave` function. Write a Python function `def interleave(inter, f, seq)` to solve the following problem: Call f on each item in seq, calling inter() in between. Here is the function: d...
Call f on each item in seq, calling inter() in between.
28,648
import ast import io import sys import tokenize class Unparser: """Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarded.""" def __init__(self, tree, file=sys.stdout): """Unparser(tree, file=sys.stdout) -> None. ...
Parse a file and pretty-print it to output. The output is formatted as valid Python source code. Args: filename: The name of the file to parse. output: The output stream to write to.
28,649
from __future__ import annotations import ast import json import os from io import StringIO from sys import version_info from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, Type, Union from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManager, CallbackManagerFor...
Add print statement to the last line if it's missing. Sometimes, the LLM-generated code doesn't have `print(variable_name)`, instead the LLM tries to print the variable only by writing `variable_name` (as you would in REPL, for example). This methods checks the AST of the generated Python code and adds the print statem...
28,650
from __future__ import annotations import tempfile from typing import TYPE_CHECKING, Any, Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.tools import BaseTool from langchain_community.utilities.vertexai import get_client_info def _import_google_cloud_texttospeech() -> Any: ...
null
28,651
import json from typing import Any, Dict, Optional from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.language_models import BaseLanguageModel from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.tools import BaseTool fr...
null
28,652
from __future__ import annotations import logging import os from typing import TYPE_CHECKING, List, Optional, Tuple def import_googleapiclient_resource_builder() -> build_resource: """Import googleapiclient.discovery.build function. Returns: build_resource: googleapiclient.discovery.build function. ...
Build a Gmail service.
28,653
from __future__ import annotations import logging import os from typing import TYPE_CHECKING, List, Optional, Tuple logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `clean_email_body` function. Write a Python function `def clean_email_body(body: str) -...
Clean email body.
28,654
from __future__ import annotations import uuid from typing import TYPE_CHECKING The provided code snippet includes necessary dependencies for implementing the `make_image_public` function. Write a Python function `def make_image_public(client: Steamship, block: Block) -> str` to solve the following problem: Upload a b...
Upload a block to a signed URL and return the public URL.
28,655
from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Coroutine, List, Optional, TypeVar The provided code snippet includes necessary dependencies for implementing the `aget_current_page` function. Write a Python function `async def aget_current_page(browser: AsyncBrowser) -> AsyncPa...
Asynchronously get the current page of the browser. Args: browser: The browser (AsyncBrowser) to get the current page from. Returns: AsyncPage: The current page.
28,656
from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Coroutine, List, Optional, TypeVar The provided code snippet includes necessary dependencies for implementing the `get_current_page` function. Write a Python function `def get_current_page(browser: SyncBrowser) -> SyncPage` to sol...
Get the current page of the browser. Args: browser: The browser to get the current page from. Returns: SyncPage: The current page.
28,657
from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Coroutine, List, Optional, TypeVar def run_async(coro: Coroutine[Any, Any, T]) -> T: """Run an async coroutine. Args: coro: The coroutine to run. Coroutine[Any, Any, T] Returns: T: The result of the coro...
Create an async playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: AsyncBrowser: The playwright browser.
28,658
from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Coroutine, List, Optional, TypeVar The provided code snippet includes necessary dependencies for implementing the `create_sync_playwright_browser` function. Write a Python function `def create_sync_playwright_browser( headless...
Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. args: arguments to pass to browser.chromium.launch Returns: SyncBrowser: The playwright browser.
28,659
from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.tools.playwright.ba...
Get elements matching the given CSS selector.
28,660
from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.tools.playwright.ba...
Get elements matching the given CSS selector.
28,661
from __future__ import annotations from typing import TYPE_CHECKING, Optional, Tuple, Type from langchain_core.pydantic_v1 import root_validator from langchain_core.tools import BaseTool The provided code snippet includes necessary dependencies for implementing the `lazy_import_playwright_browsers` function. Write a P...
Lazy import playwright browsers. Returns: Tuple[Type[AsyncBrowser], Type[SyncBrowser]]: AsyncBrowser and SyncBrowser classes.
28,662
from typing import Callable, Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.pydantic_v1 import Field from langchain_core.tools import BaseTool def _print_func(text: str) -> None: print("\n") # noqa: T201 print(text) # noqa: T201
null
28,663
import logging import platform import warnings from typing import Any, List, Optional, Type, Union from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.pydantic_v1 import BaseModel, Field, root_validator from langchain_core.tools import BaseTool class BashProcess: """Wrapper ...
Get default bash process.
28,664
import logging import platform import warnings from typing import Any, List, Optional, Type, Union from langchain_core.callbacks import ( CallbackManagerForToolRun, ) from langchain_core.pydantic_v1 import BaseModel, Field, root_validator from langchain_core.tools import BaseTool The provided code snippet includes...
Get platform.
28,665
import warnings from typing import Any from langchain_community.tools.human.tool import HumanInputRun class HumanInputRun(BaseTool): """Tool that asks user for input.""" name: str = "human" description: str = ( "You can ask a human for guidance when you think you " "got stuck or you are no...
Tool for asking the user for input.
28,666
from __future__ import annotations import json import re from pathlib import Path from typing import Dict, List, Optional, Union from langchain_core.pydantic_v1 import BaseModel from langchain_core.callbacks import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain_core.tools import B...
Parse input of the form data["key1"][0]["key2"] into a list of keys.
28,667
import tempfile from enum import Enum from typing import Any, Dict, Optional, Union from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.pydantic_v1 import root_validator from langchain_core.tools import BaseTool from langchain_core.utils import get_from_dict_or_env def _import_elevenlabs...
null
28,668
from __future__ import annotations import logging import os from typing import TYPE_CHECKING The provided code snippet includes necessary dependencies for implementing the `clean_body` function. Write a Python function `def clean_body(body: str) -> str` to solve the following problem: Clean body of a message or event....
Clean body of a message or event.
28,669
from __future__ import annotations import logging import os from typing import TYPE_CHECKING logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `authenticate` function. Write a Python function `def authenticate() -> Account` to solve the following proble...
Authenticate using the Microsoft Grah API
28,670
from __future__ import annotations import logging import os from typing import TYPE_CHECKING logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `login` function. Write a Python function `def login() -> WebClient` to solve the following problem: Authentic...
Authenticate using the Slack API.
28,671
import warnings from typing import Any, Optional, Type from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.pydantic_v1 import BaseModel, Field from langchain_core.tools import BaseTool from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper class DuckDuckGoS...
Deprecated. Use DuckDuckGoSearchRun instead. Args: *args: **kwargs: Returns: DuckDuckGoSearchRun
28,672
import sys from pathlib import Path from typing import Optional from langchain_core.pydantic_v1 import BaseModel def is_relative_to(path: Path, root: Path) -> bool: """Check if path is relative to root.""" if sys.version_info >= (3, 9): # No need for a try/except block in Python 3.8+. return pat...
Resolve a relative path, raising an error if not within the root directory.
28,673
from __future__ import annotations import os from typing import TYPE_CHECKING, Literal, Optional The provided code snippet includes necessary dependencies for implementing the `authenticate` function. Write a Python function `def authenticate(network: Optional[Literal["mainnet", "testnet"]] = "testnet") -> Ain` to sol...
Authenticate using the AIN Blockchain
28,674
import base64 import itertools import json import re from pathlib import Path from typing import Dict, List, Type import requests from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.tools import Tool The provided code snippet includes necessary dependencies for implementing the `strip_mark...
Strip markdown code from a string.
28,675
import base64 import itertools import json import re from pathlib import Path from typing import Dict, List, Type import requests from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.tools import Tool The provided code snippet includes necessary dependencies for implementing the `head_file`...
Get the first n lines of a file.
28,676
import base64 import itertools import json import re from pathlib import Path from typing import Dict, List, Type import requests from langchain_core.pydantic_v1 import BaseModel, Field from langchain_community.tools import Tool The provided code snippet includes necessary dependencies for implementing the `file_to_ba...
Convert a file to base64.
28,677
import logging from typing import List, Optional, Tuple, Union import numpy as np Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray] def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray: """Row-wise cosine similarity between two equal-width matrices.""" if len(X) == 0 or len(Y) == 0: r...
Row-wise cosine similarity with optional top-k and score threshold filtering. Args: X: Matrix. Y: Matrix, same width as X. top_k: Max number of results to return. score_threshold: Minimum cosine similarity of results. Returns: Tuple of two lists. First contains two-tuples of indices (X_idx, Y_idx), second contains corr...
28,678
from importlib import metadata from typing import Any, Optional The provided code snippet includes necessary dependencies for implementing the `get_client_info` function. Write a Python function `def get_client_info(module: Optional[str] = None) -> Any` to solve the following problem: r"""Returns a custom user agent h...
r"""Returns a custom user agent header. Args: module (Optional[str]): Optional. The module for a custom user agent header. Returns: google.api_core.gapic_v1.client_info.ClientInfo
28,679
from typing import Literal, Optional, Type, TypedDict from langchain_core.pydantic_v1 import BaseModel from langchain_core.utils.json_schema import dereference_refs class ToolDescription(TypedDict): """Representation of a callable function to the Ernie API.""" type: Literal["function"] function: FunctionDes...
Converts a Pydantic model to a function description for the Ernie API.
28,680
import os from pathlib import Path import pypdfium2 as pdfium from langchain_community.vectorstores import Chroma from langchain_experimental.open_clip import OpenCLIPEmbeddings The provided code snippet includes necessary dependencies for implementing the `get_images_from_pdf` function. Write a Python function `def g...
Extract images from each page of a PDF document and save as JPEG files. :param pdf_path: A string representing the path to the PDF file. :param img_dump_path: A string representing the path to dummp images.
28,681
import base64 import io from pathlib import Path from langchain_community.chat_models import ChatOpenAI from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_core.messages import HumanMessage from langchain_core.output_parsers import StrOutputParser from langch...
Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process.
28,682
import json from langchain_core.pydantic_v1 import BaseModel, Field, conint class LLMPlateResponse(BaseModel): row_start: conint(ge=0) = Field( ..., description="The starting row of the plate (0-indexed)" ) row_end: conint(ge=0) = Field( ..., description="The ending row of the plate (0-index...
Based on the prompt we expect the result to be a string that looks like: '[{"row_start": 12, "row_end": 19, "col_start": 1, \ "col_end": 12, "contents": "Entity ID"}]' We'll load that JSON and turn it into a Pydantic model
28,683
import base64 import json from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate from langchain_core.pydantic_v1 import Field from langserve import CustomUserType from .prompts im...
null
28,684
import base64 import json from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate from langchain_core.pydantic_v1 import Field from langserve import CustomUserType from .prompts im...
null
28,685
import base64 import json from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate from langchain_core.pydantic_v1 import Field from langserve import CustomUserType from .prompts im...
null
28,686
import base64 import json from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate from langchain_core.pydantic_v1 import Field from langserve import CustomUserType from .prompts im...
null
28,687
from langchain.utilities import DuckDuckGoSearchAPIWrapper from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import Runnable...
null
28,688
from langchain.utilities import DuckDuckGoSearchAPIWrapper from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import Runnable...
null
28,689
from langchain_core.agents import AgentAction, AgentFinish from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder class AgentAction(Serializable): """A full description of an action for an ActionAgent to execute.""" tool: str """The name of the Tool to execute.""" tool_input: Union...
null
28,690
from typing import List, Tuple from langchain.agents import AgentExecutor from langchain.agents.format_scratchpad import format_xml from langchain.tools import DuckDuckGoSearchRun from langchain.tools.render import render_text_description from langchain_community.chat_models import ChatAnthropic from langchain_core.mes...
null
28,691
import os from langchain_community.chat_models import ChatOpenAI from langchain_community.embeddings import OpenAIEmbeddings from langchain_community.vectorstores import MongoDBAtlasVectorSearch from langchain_core.documents import Document from langchain_core.output_parsers import StrOutputParser from langchain_core.p...
null
28,692
import os import uuid from langchain_community.document_loaders import PyPDFLoader from langchain_community.embeddings import OpenAIEmbeddings from langchain_community.vectorstores import MongoDBAtlasVectorSearch from langchain_text_splitters import RecursiveCharacterTextSplitter from pymongo import MongoClient PARENT_...
null
28,693
import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) def populate(vector_store): # is the store empty? find out with a probe search hits = vector_store.similarity_search_by_vector( embedding=[0.001] * 1536, k=1, ) # if len(hits) == 0: # this seems a first run: ...
null
28,694
import os from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster def get_cassandra_connection(): contact_points = [ cp.strip() for cp in os.environ.get("CASSANDRA_CONTACT_POINTS", "").split(",") if cp.strip() ] CASSANDRA_KEYSPACE = os.environ["CASSAND...
null
28,695
from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import RunnablePassthrough def parse_numbered_list(input_str): """Pars...
null
28,696
from langchain_community.chat_models import ChatOpenAI from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import RunnablePassthrough def get_final_answer(expanded_list): final...
null
28,698
import os def get_boolean_env_var(var_name, default_value=False): """Retrieve the boolean value of an environment variable. Args: var_name (str): The name of the environment variable to retrieve. default_value (bool): The default value to return if the variable is not found. Returns: bool: T...
null
28,699
import os from langchain_community.document_loaders import UnstructuredFileLoader from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import Redis from langchain_text_splitters import RecursiveCharacterTextSplitter from rag_redis.config import EMBED_MODEL, INDEX_NAME, ...
Ingest PDF to Redis from the data/ directory that contains Edgar 10k filings data for Nike.
28,700
from langchain import hub from langchain_community.chat_models import ChatAnthropic from langchain_community.utilities import WikipediaAPIWrapper from langchain_core.output_parsers import StrOutputParser from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import RunnableLambda, RunnablePassth...
null
28,701
from typing import Optional, Type from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.pydantic_v1 import BaseModel, Field from langchain.tools import BaseTool from neo4j_semantic_ollama.utils import get_candidates, get_user_id, graph recommendati...
Recommends movies based on user's history and preference for a specific movie and/or genre. Returns: str: A string containing a list of recommended movies, or an error message.
28,702
from typing import Optional, Type from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.pydantic_v1 import BaseModel, Field from langchain.tools import BaseTool from neo4j_semantic_ollama.utils import get_candidates, graph description_query = """ M...
null
28,703
import os from typing import List, Tuple from langchain.agents import AgentExecutor from langchain.agents.format_scratchpad import format_log_to_messages from langchain.agents.output_parsers import ( ReActJsonSingleInputOutputParser, ) from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder from langc...
null
28,704
from typing import Optional, Type from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.pydantic_v1 import BaseModel, Field from langchain.tools import BaseTool from neo4j_semantic_ollama.utils import get_candidates, get_user_id, graph store_rating...
null
28,705
import getpass import os from langchain_community.document_loaders import PyPDFLoader from langchain_community.vectorstores import Milvus from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.r...
Load and ingest the PDF file from the URL
28,706
import os from langchain_community.chat_models import ChatOpenAI from langchain_community.document_loaders import PyPDFLoader from langchain_community.embeddings import OpenAIEmbeddings from langchain_community.vectorstores import MongoDBAtlasVectorSearch from langchain_core.output_parsers import StrOutputParser from l...
null
28,707
import os from operator import itemgetter from typing import List, Tuple from langchain_community.chat_models import ChatOpenAI from langchain_community.vectorstores.zep import CollectionConfig, ZepVectorStore from langchain_core.documents import Document from langchain_core.messages import AIMessage, BaseMessage, Huma...
null
28,708
import os from operator import itemgetter from typing import List, Tuple from langchain_community.chat_models import ChatOpenAI from langchain_community.vectorstores.zep import CollectionConfig, ZepVectorStore from langchain_core.documents import Document from langchain_core.messages import AIMessage, BaseMessage, Huma...
null
28,709
from typing import List, Tuple from langchain.agents import AgentExecutor from langchain.agents.format_scratchpad import format_to_openai_function_messages from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.utilities.tavily_search import TavilySearchAPIWrapper from langchain_com...
null
28,710
from langchain_core.agents import AgentAction, AgentFinish class AgentAction(Serializable): """A full description of an action for an ActionAgent to execute.""" tool: str """The name of the Tool to execute.""" tool_input: Union[str, dict] """The input to pass in to the Tool.""" log: str ""...
null
28,711
import base64 import io from pathlib import Path from langchain_community.chat_models import ChatOllama from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_core.messages import HumanMessage from langchain_core.output_parsers import StrOutputParser from langch...
Resize an image encoded as a Base64 string. :param base64_string: A Base64 encoded string of the image to be resized. :param size: A tuple representing the new size (width, height) for the image. :return: A Base64 encoded string of the resized image.
28,712
import base64 import io from pathlib import Path from langchain_community.chat_models import ChatOllama from langchain_community.vectorstores import Chroma from langchain_core.documents import Document from langchain_core.messages import HumanMessage from langchain_core.output_parsers import StrOutputParser from langch...
Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process.
28,713
from operator import itemgetter import numpy as np from langchain.retrievers import ( ArxivRetriever, KayAiRetriever, PubMedRetriever, WikipediaRetriever, ) from langchain.utils.math import cosine_similarity from langchain_community.chat_models import ChatOpenAI from langchain_community.embeddings impor...
null
28,714
from operator import itemgetter import numpy as np from langchain.retrievers import ( ArxivRetriever, KayAiRetriever, PubMedRetriever, WikipediaRetriever, ) from langchain.utils.math import cosine_similarity from langchain_community.chat_models import ChatOpenAI from langchain_community.embeddings impor...
null
28,715
from typing import List, Optional from langchain_community.graphs import Neo4jGraph from langchain_core.documents import Document from langchain_experimental.graph_transformers import LLMGraphTransformer from langchain_openai import ChatOpenAI graph = Neo4jGraph() llm = ChatOpenAI(model="gpt-3.5-turbo-16k", temperature...
Process the given text to extract graph data and constructs a graph document from the extracted information. The constructed graph document is then added to the graph. Parameters: - text (str): The input text from which the information will be extracted to construct the graph. - allowed_nodes (Optional[List[str]]): A l...
28,716
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
null
28,717
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
Format a file with black.
28,718
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
Run ruff format on a file.
28,719
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
Run ruff check on a file.
28,720
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
Run mypy on a file.
28,721
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
null
28,722
import os import re import subprocess import tempfile from langchain.agents import AgentType, initialize_agent from langchain.agents.tools import Tool from langchain.pydantic_v1 import BaseModel, Field, ValidationError, validator from langchain_community.chat_models import ChatOpenAI from langchain_core.language_model...
null
28,723
import logging import uuid from typing import Sequence from bs4 import BeautifulSoup as Soup from langchain_core.documents import Document from langchain_core.runnables import Runnable from propositional_retrieval.constants import DOCSTORE_ID_KEY from propositional_retrieval.proposal_chain import proposition_chain from...
Create retriever that indexes docs and their propositions :param docs: Documents to index :param indexer: Runnable creates additional propositions per doc :param docstore_id_key: Key to use to store the docstore id :return: Retriever
28,724
from langchain_community.chat_models import ChatOpenAI from langchain_core.load import load from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel from langchain_core.runnables import RunnablePassthrough from propo...
The RAG chain :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process.
28,725
import logging from langchain.output_parsers.openai_tools import JsonOutputToolsParser from langchain_community.chat_models import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnableLambda def get_propositions(tool_calls: list) -> list: if not tool_calls: ...
null
28,726
import logging from langchain.output_parsers.openai_tools import JsonOutputToolsParser from langchain_community.chat_models import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnableLambda def empty_proposals(x): # Model couldn't generate proposals ret...
null
28,728
import os from operator import itemgetter from typing import List, Tuple from langchain_community.chat_models import ChatOpenAI from langchain_community.embeddings import OpenAIEmbeddings from langchain_core.messages import AIMessage, HumanMessage from langchain_core.output_parsers import StrOutputParser from langchain...
null
28,729
import os from operator import itemgetter from typing import List, Tuple from langchain_community.chat_models import ChatOpenAI from langchain_community.embeddings import OpenAIEmbeddings from langchain_core.messages import AIMessage, HumanMessage from langchain_core.output_parsers import StrOutputParser from langchain...
null
28,730
import os from typing import List, Tuple from langchain.agents import AgentExecutor from langchain.agents.format_scratchpad import format_to_openai_function_messages from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain_community.chat_models import ChatOpenAI from langchain_communi...
A search engine optimized for comprehensive, accurate, \ and trusted results. Useful for when you need to answer questions \ about current events or about recent information. \ Input should be a search query. \ If the user is asking about something that you don't know about, \ you should probably use this tool to see i...
28,731
import os from typing import List, Tuple from langchain.agents import AgentExecutor from langchain.agents.format_scratchpad import format_to_openai_function_messages from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain_community.chat_models import ChatOpenAI from langchain_communi...
null