text
stringlengths
79
3.72M
<vulnerable_code>Make sure that you only use the comparators and logical operators listed above and \ no others. Make sure that filters only refer to attributes that exist in the data source. Make sure that filters take into account the descriptions of attributes and only make \ comparisons that are feasible given the ...
<vulnerable_code> from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.chains.query_constructor.base import load_query_constructor_chain from langchain.chains.query_constructor.ir import StructuredQuery, Visitor from langchain.chains.query_constructor.schema import Attribu...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> import datetime import re from typing import Any, Callable, Dict, Tuple from langchain.chains.query_constructor.ir import ( Comparator, Comparison, ...
<vulnerable_code> # Instantiate as constant instead of pytest fixture to prevent needing to make multiple # connections. TEST_CLIENT = MongoClient(CONNECTION_STRING) collection = TEST_CLIENT[DB_NAME][COLLECTION_NAME] <commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my ...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Any, Tuple import pytest from langchain.chains.query_constructor.ir import ( Comparator, Comparison, Operation, Operator...
<vulnerable_code> self, query: str, num_results: int, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> Union[List[Dict], str]: """Use the tool.""" try: return self.api_wrapper.results(query, num_results) except Exception as e: ...
<vulnerable_code>In order to set this up, follow instructions at: """ import json from typing import Dict, List import aiohttp import requests extra = Extra.forbid def _metaphor_search_results(self, query: str, num_results: int) -> List[dict]: headers = {"X-Api-Key": self.metaphor_api_key} ...
<vulnerable_code>) from langchain.agents.loading import load_agent from langchain.agents.mrkl.base import MRKLChain, ZeroShotAgent from langchain.agents.react.base import ReActChain, ReActTextWorldAgent from langchain.agents.self_ask_with_search.base import SelfAskWithSearchChain from langchain.agents.structured_chat.b...
<vulnerable_code>from langchain.tools.sql_database.tool import ( InfoSQLDatabaseTool, ListSQLDatabaseTool, QueryCheckerTool, QuerySQLDataBaseTool, ) db=self.db, description=info_sql_database_tool_description ), ListSQLDatabaseTool(db=self.db), QueryCh...
<vulnerable_code> from langchain.callbacks.aim_callback import AimCallbackHandler from langchain.callbacks.argilla_callback import ArgillaCallbackHandler from langchain.callbacks.clearml_callback import ClearMLCallbackHandler from langchain.callbacks.comet_ml_callback import CometCallbackHandler from langchain.callback...
<vulnerable_code>from langchain.chains.loading import load_chain from langchain.chains.mapreduce import MapReduceChain from langchain.chains.moderation import OpenAIModerationChain from langchain.chains.openai_functions import ( create_extraction_chain, create_extraction_chain_pydantic, from langchain.chains.qa...
<vulnerable_code>"""Wrappers on top of docstores.""" from langchain.docstore.in_memory import InMemoryDocstore from langchain.docstore.wikipedia import Wikipedia __all__ = ["InMemoryDocstore", "Wikipedia"]<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix ...
<vulnerable_code>from langchain.document_loaders.bigquery import BigQueryLoader from langchain.document_loaders.bilibili import BiliBiliLoader from langchain.document_loaders.blackboard import BlackboardLoader from langchain.document_loaders.blockchain import BlockchainDocumentLoader from langchain.document_loaders.cha...
<vulnerable_code>from langchain.llms.huggingface_text_gen_inference import HuggingFaceTextGenInference from langchain.llms.human import HumanInputLLM from langchain.llms.llamacpp import LlamaCpp from langchain.llms.modal import Modal from langchain.llms.mosaicml import MosaicML from langchain.llms.nlpcloud import NLPCl...
<vulnerable_code> ConversationStringBufferMemory, ) from langchain.memory.buffer_window import ConversationBufferWindowMemory from langchain.memory.chat_message_histories import MomentoChatMessageHistory from langchain.memory.chat_message_histories.cassandra import ( CassandraChatMessageHistory, ) from langchain...
<vulnerable_code>from langchain.memory.chat_message_histories.firestore import ( FirestoreChatMessageHistory, ) from langchain.memory.chat_message_histories.momento import MomentoChatMessageHistory from langchain.memory.chat_message_histories.mongodb import MongoDBChatMessageHistory from langchain.memory.chat_messa...
<vulnerable_code>from langchain.output_parsers.datetime import DatetimeOutputParser from langchain.output_parsers.fix import OutputFixingParser from langchain.output_parsers.list import ( CommaSeparatedListOutputParser, from langchain.output_parsers.structured import ResponseSchema, StructuredOutputParser __all__ ...
<vulnerable_code> MessagesPlaceholder, SystemMessagePromptTemplate, ) from langchain.prompts.few_shot import FewShotPromptTemplate from langchain.prompts.few_shot_with_templates import FewShotPromptWithTemplates from langchain.prompts.loading import load_prompt from langchain.prompts.prompt import Prompt, Prompt...
<vulnerable_code>"""Logic for selecting examples to include in prompts.""" from langchain.prompts.example_selector.length_based import LengthBasedExampleSelector from langchain.prompts.example_selector.semantic_similarity import ( MaxMarginalRelevanceExampleSelector, SemanticSimilarityExampleSelector, __all__ ...
<vulnerable_code>from langchain.retrievers.docarray import DocArrayRetriever from langchain.retrievers.elastic_search_bm25 import ElasticSearchBM25Retriever from langchain.retrievers.knn import KNNRetriever from langchain.retrievers.merger_retriever import MergerRetriever from langchain.retrievers.metal import MetalRet...
<vulnerable_code>"""Core toolkit implementations.""" from langchain.tools.azure_cognitive_services import ( AzureCogsFormRecognizerTool, AzureCogsImageAnalysisTool, from langchain.tools.brave_search.tool import BraveSearch from langchain.tools.convert_to_openai import format_tool_to_openai_function from langch...
<vulnerable_code> class SearxSearchResults(BaseTool): """Tool that has capability to query a Searx instance and get back json.""" name = "Searx Search" description = ( "A meta search engine." "Useful for when you need to answer questions about current events."<commit_title>[PATCH 001/150] ...
<vulnerable_code>class QuerySQLDataBaseTool(BaseSQLDatabaseTool, BaseTool): """Tool for querying a SQL database.""" name = "query_sql_db" description = """ Input to this tool is a detailed and correct SQL query, output is a result from the database. If the query is not correct, an error message wil...
<vulnerable_code>from langchain.utilities.arxiv import ArxivAPIWrapper from langchain.utilities.awslambda import LambdaWrapper from langchain.utilities.bash import BashProcess from langchain.utilities.bing_search import BingSearchAPIWrapper from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper fr...
<vulnerable_code>from langchain.vectorstores.zilliz import Zilliz __all__ = [ "AzureSearch", "Redis", "ElasticVectorSearch", "FAISS", "VectorStore", "Pinecone", "Weaviate", "Qdrant", "Milvus", "Zilliz", "SingleStoreDB", "Chroma", "OpenSearchVectorSearch", "AtlasD...
<vulnerable_code> "ConversationalChatAgent", "LLMSingleActionAgent", "MRKLChain", "ReActChain", "ReActTextWorldAgent", "SelfAskWithSearchChain",<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> "Co...
<vulnerable_code> return subclasses _PARSERS_TO_SKIP = {"FakeOutputParser", "BaseOutputParser"} _NON_ABSTRACT_PARSERS = non_abstract_subclasses( BaseOutputParser, to_skip=_PARSERS_TO_SKIP )<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase...
<vulnerable_code> test_group_deps = sorted(poetry_conf["group"]["test"]["dependencies"]) assert test_group_deps == [ "duckdb-engine", # Should be removed "freezegun", "lark", # Should be removed "pytest", "pytest-asyncio", "pytest-cov",<commit_title>[PATCH 001/1...
<vulnerable_code> if isinstance(tool_class, type) and issubclass(tool_class, BaseTool): if tool_class in _EXCLUDE: continue if ( skip_tools_without_default_names and tool_class.__fields__["name"].default is None ): ...
<vulnerable_code>_EXPECTED = [ "AIPluginTool", "APIOperation", "AzureCogsFormRecognizerTool", "AzureCogsImageAnalysisTool", "AzureCogsSpeech2TextTool", "AzureCogsText2SpeechTool", "BaseTool", "BaseTool", "BaseTool", "BingSearchResults", "BingSearchRun", "ClickTool", "...
<vulnerable_code> _output_keys = [self.output_key] return _output_keys @classmethod def from_llm( cls,<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> _output_keys = [self.output_key]...
<vulnerable_code>from langchain.chains.combine_documents.map_rerank import MapRerankDocumentsChain from langchain.chains.combine_documents.refine import RefineDocumentsChain from langchain.chains.combine_documents.stuff import StuffDocumentsChain from langchain.chains.hyde.base import HypotheticalDocumentEmbedder from ...
<vulnerable_code>import os from langchain.chains.graph_qa.cypher import GraphCypherQAChain from langchain.graphs import Neo4jGraph from langchain.llms.openai import OpenAI output = chain.run("Who played in Pulp Fiction?") expected_output = [{"a.name": "Bruce Willis"}] assert output == expected_output<comm...
<vulnerable_code> if not token.special: if text_callback: text_callback(token.text) return text<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> ...
<vulnerable_code> inner_completion = "" role = "assistant" params["stream"] = True async for stream_resp in await acompletion_with_retry( self, messages=message_dicts, **params ): role = stream_resp["choices"][0]["delta"].get("ro...
<vulnerable_code> AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.searx_search import SearxSearchWrapper "Input should be a search query." ) wrapper: SearxSearchWrapper def _run( self, run_manag...
<vulnerable_code>use a self hosted instance and disable the rate limiter. If you are self-hosting an instance you can customize the rate limiter for your own network as described `here <https://github.com/searxng/searxng/pull/2129>`_. For a list of public SearxNG instances see https://searx.space/<commit_title>[PATC...
<vulnerable_code> ) assert docsearch.docstore.__dict__ == expected_docstore.__dict__ output = docsearch.similarity_search("foo", k=1, filter={"page": 1}) assert output == [] def test_faiss_search_not_found() -> None:<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a fe...
<vulnerable_code> try: import deeplake from deeplake.core.vectorstore import DeepLakeVectorStore _DEEPLAKE_INSTALLED = True "Please install it with `pip install deeplake`." ) version = deeplake.__version__ if version != "3.6.2": raise ValueError( ...
<vulnerable_code> index_type: str = "annoy" # Annoy supports L2Distance and cosineDistance. index_param: Optional[Union[List, Dict]] = [100, "'L2Distance'"] index_query_params: Dict[str, str] = {} column_map: Dict[str, str] = {<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_descriptio...
<vulnerable_code> examples=[ {k: v for k, v in e.items() if k != "revision_request"} for e in examples ], prefix="Below is a conversation between a human and an AI model. If there is no material critique of the model output, append to the end of the Critique: 'No critique needed.' If there is no mate...
<vulnerable_code> ) -> List[Document]: search_type = kwargs.get("search_type", self.search_type) if search_type == "similarity": docs = self.vector_search(query, k=k) elif search_type == "hybrid": docs = self.hybrid_search(query, k=k) elif search_type == "seman...
<vulnerable_code> """Retrieve the messages from DynamoDB""" from botocore.exceptions import ClientError try: response = self.table.get_item(Key={"SessionId": self.session_id}) except ClientError as error:<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_descriptio...
<vulnerable_code> .. code-block:: python from langchain.llms import AlephAlpha alpeh_alpha = AlephAlpha(aleph_alpha_api_key="my-api-key") """ client: Any #: :meta private: @property def _llm_type(self) -> str: """Return type of llm.""" return "alpeh_alph...
<vulnerable_code> @property def _llm_type(self) -> str: """Return type of llm.""" return "banana" def _call( self,<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> @property def _l...
<vulnerable_code> @property def _llm_type(self) -> str: """Return type of llm.""" return "hf_textgen_inference" def _call( self,<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> @prope...
<vulnerable_code> @property def _llm_type(self) -> str: """Return type of llm.""" return "llama.cpp" def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]: """<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my...
<vulnerable_code> @property def _llm_type(self) -> str: """Return type of llm.""" return "mosaicml" def _transform_prompt(self, prompt: str) -> str: """Transform prompt."""<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fi...
<vulnerable_code> @property def _llm_type(self) -> str: """Return the type of llm.""" return "rwkv-4" def run_rnn(self, _tokens: List[str], newline_adj: int = 0) -> Any: AVOID_REPEAT_TOKENS = []<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few e...
<vulnerable_code> return context_size def max_tokens_for_prompt(self, prompt: str) -> int: """Calculate the maximum number of tokens possible to generate for a prompt. max_tokens = openai.max_token_for_prompt("Tell me a joke.") """ num_tokens = self.get_num_tokens(p...
<vulnerable_code> _files = files returns = [] for file in files: if file["trashed"] and not self.load_trashed_files: continue elif file["mimeType"] == "application/vnd.google-apps.document":<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_...
<vulnerable_code> docs_and_scores = self.similarity_search_with_score( query, k=k, lamnbda_val=lambda_val, filter=filter, n_sentence_context=n_sentence_context, **kwargs,<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_descripti...
<vulnerable_code> llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, **kwargs: Any, ) -> BaseSingleActionAgent: """Construct an agent from an LLM and tools.""" if not isinstance(llm, ChatOpenAI): raise...
<vulnerable_code>from langchain.schema import AgentAction, AgentFinish, LLMResult MODEL_COST_PER_1K_TOKENS = { "gpt-4": 0.03, "gpt-4-0314": 0.03, "gpt-4-completion": 0.06, "gpt-4-0314-completion": 0.06, "gpt-4-32k": 0.06, "gpt-4-32k-0314": 0.06, "gpt-4-32k-completion": 0.12, "gpt-4-32k-...
<vulnerable_code>import uuid from typing import Any, Dict, List, Optional, Union import pandas as pd from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log data to A...
<vulnerable_code> embedding = OpenAIEmbeddings() vectorstore = Typesense( typesense_client, typesense_collection_name, embedding.embed_query, "text", ) """ def similarity_search_with_score( self, ...
<vulnerable_code> ) -> List[Document]: """Query the chroma collection.""" try: import chromadb except ImportError: raise ValueError( "Could not import chromadb python package. " "Please install it with `pip install chromadb`." ...
<vulnerable_code> async def _fetch( self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5 ) -> str: async with aiohttp.ClientSession() as session: for i in range(retries): try: async with session.get(<commit_title>[PATCH 001/150]...
<vulnerable_code>from json import JSONDecodeError from typing import Any, List, Optional, Sequence, Tuple, Union from langchain.agents import BaseSingleActionAgent from langchain.base_language import BaseLanguageModel from langchain.callbacks.base import BaseCallbackManager class OpenAIFunctionsAgent(BaseSingleActio...
<vulnerable_code>from pathlib import Path from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union from pydantic import Field from langchain.load.serializable import Serializable from langchain.memory.buffer import get_buffer_string input_variables: List[str] messages: List[Union[BaseMess...
<vulnerable_code>from pathlib import Path from typing import List from langchain.prompts import PromptTemplate from langchain.prompts.chat import ( AIMessagePromptTemplate, ) prompt_value_messages = prompt_value.to_messages() assert prompt_value_messages[-1] == HumanMessage(content="foo")<commit_title>...
<vulnerable_code>from langchain.chains.moderation import OpenAIModerationChain from langchain.chains.natbot.base import NatBotChain from langchain.chains.openai_functions import ( create_extraction_chain, create_extraction_chain_pydantic, create_tagging_chain, "create_tagging_chain", "create_tagging...
<vulnerable_code> """Call the chain on all inputs in the list.""" return [self(inputs, callbacks=callbacks) for inputs in input_list] def run( self, *args: Any, **kwargs: Any, ) -> str: """Run the chain as text in, text out or multiple variables, text out.""" ...
<vulnerable_code>"""Chain that just formats a prompt and calls an LLM.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from pydantic import Extra from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( from langchain.l...
<vulnerable_code>from langchain.chains.retrieval_qa.base import RetrievalQA, VectorDBQA from langchain.chains.sql_database.base import SQLDatabaseChain from langchain.llms.loading import load_llm, load_llm_from_config from langchain.prompts.loading import load_prompt, load_prompt_from_config from langchain.utilities.lo...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from langchain.chains.openai_functions.citation_fuzzy_match import ( create_citation_fuzzy_match_chain, ) from langchain.chains.openai_functions.extracti...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Iterator, List from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.chains.llm imp...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Any, List from pydantic import BaseModel from langchain.base_language import BaseLanguageModel from langchain.chains.base import Chain f...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Any, List from langchain.base_language import BaseLanguageModel from langchain.chains.base import Chain from langchain.chains.llm import ...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Any, Dict def _resolve_schema_references(schema: Any, definitions: Dict[str, Any]) -> Any: """ Resolves the $ref keys in a JSON ...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> import json from typing import Any, List from langchain.schema import BaseLLMOutputParser, ChatGeneration, Generation class OutputFunctionsParser(BaseLLMO...
<vulnerable_code>from langchain.prompts.base import BasePromptTemplate from langchain.prompts.few_shot import FewShotPromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain.utilities.loading import try_load_from_hub URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/...
<vulnerable_code>T = TypeVar("T") class BaseOutputParser(Serializable, ABC, Generic[T]): """Class to parse the output of an LLM call. Output parsers help structure language model responses. """ @abstractmethod def parse(self, text: str) -> T: """Parse the output of an LLM call. r...
<vulnerable_code> from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.output_parsers.openai_functions import ( PydanticOutputFunctionsParser, ) def create_citation_fuzzy_match_chain(llm: BaseLanguageModel) -> LLMChain: output_parser = PydanticOutputFunc...
<vulnerable_code>from langchain.chains.openai_functions.utils import ( _convert_schema, _resolve_schema_references, ) from langchain.output_parsers.openai_functions import ( JsonKeyOutputFunctionsParser, ) from langchain.prompts import ChatPromptTemplate EXTRACTION_NAME = "information_extraction" EXTRACTIO...
<vulnerable_code>from typing import Any, List from langchain.base_language import BaseLanguageModel from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.chains.openai_functions.utils import _convert_schema from langchain.output_parsers.openai_functions import ( JsonOutpu...
<vulnerable_code> "properties": props, "required": schema.get("required", []), }<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> "properties": props, "required": schema.get("required", [])...
<vulnerable_code> openai = ChatOpenAI(model_name="gpt-3.5-turbo") """ @property def lc_serializable(self) -> bool: return True<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> open...
<vulnerable_code>import importlib import json from typing import Any, Dict, Optional from langchain.load.serializable import Serializable if key in self.secrets_map: return self.secrets_map[key] else: raise KeyError(f'Missing key "{key}" in load(secrets_map)') ...
<vulnerable_code> secrets.update(this.lc_secrets) lc_kwargs.update(this.lc_attributes) return { "lc": 1, "type": "constructor",<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fix...
<vulnerable_code> assert dumps(chain, pretty=True) == snapshot @pytest.mark.requires("openai") def test_serialize_llmchain_chat(snapshot: Any) -> None: llm = ChatOpenAI(model="davinci", temperature=0.5, openai_api_key="hello") chain = LLMChain(llm=llm, prompt=prompt) assert dumps(chain, pretty=True) ==...
<vulnerable_code> assert isinstance(chain2.prompt, PromptTemplate) @pytest.mark.requires("openai") def test_load_llmchain_with_non_serializable_arg() -> None: llm = OpenAI(<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed...
<vulnerable_code>from langchain.chains.api.base import APIChain from langchain.chains.api.openapi.chain import OpenAPIEndpointChain from langchain.chains.combine_documents.base import AnalyzeDocumentChain from langchain.chains.constitutional_ai.base import ConstitutionalChain from langchain.chains.conversation.base imp...
<vulnerable_code> results: Dict[str, List[Any]] = {} async def process_example( example: Example, tracer: LangChainTracer, job_state: dict ) -> None: """Process a single example.""" result = await _arun_llm_or_chain( """ client_ = client or LangChainPlusClient() session_n...
<vulnerable_code> {"result": f"Result for example {example.id}"} for _ in range(n_repetitions) ] with mock.patch.object( LangChainPlusClient, "read_dataset", new=mock_read_dataset ), mock.patch.object( LangChainPlusClient, "list_examples", new=mock_list_examples ), mock.p...
<vulnerable_code># Import the necessary packages for ingestion import uuid from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult class ArizeCallbackHandler(BaseCallbackHandler): """Callback Han...
<vulnerable_code>from typing import Any, Dict, Mapping, Optional, Sequence, Union from langchainplus_sdk.evaluation import EvaluationResult from langchainplus_sdk.schemas import Example, Run from pydantic import BaseModel from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain ...
<vulnerable_code> Returns: str: Combined string with necessary HUMAN_PROMPT and AI_PROMPT tags. """ if not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") <commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a ...
<vulnerable_code> assert isinstance(response.content, str) def test_anthropic_streaming() -> None: """Test streaming tokens from anthropic.""" chat = ChatAnthropic(model="test", streaming=True)<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix ...
<vulnerable_code> ) return [doc for doc, _ in docs_and_scores] def max_marginal_relevance_search_by_vector( self, embedding: List[float],<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> ...
<vulnerable_code> anyscale_service_token = get_from_dict_or_env( values, "anyscale_service_token", "ANYSCALE_SERVICE_TOKEN" ) try: anyscale_service_endpoint = f"{anyscale_service_url}/-/route" headers = {"Authorization": f"Bearer {anyscale_service_token}"} ...
<vulnerable_code> # For backwards compatibility. The tool must be run with a single input all_args = list(args) + list(kwargs.values()) if len(all_args) != 1: raise ValueError( f"Too many arguments to single-input tool {self.name}." f" Args: {all_args}"...
<vulnerable_code>from langchain.agents.react.base import ReActDocstoreAgent, ReActTextWorldAgent from langchain.agents.self_ask_with_search.base import SelfAskWithSearchAgent from langchain.agents.tools import Tool, tool from tests.unit_tests.callbacks.fake_callback_handler import FakeCallbackHandler assert some_...
<vulnerable_code> assert isinstance(structured_tool_input, BaseTool) assert structured_tool_input.name == "structured_tool_input" args = {"arg1": 1, "arg2": 0.001, "opt_arg": {"foo": "bar"}} with pytest.raises(ValueError): assert structured_tool_input.run(args) <commit_title>[PATCH 001/150] Mong...
<vulnerable_code> create_citation_fuzzy_match_chain, create_extraction_chain, create_extraction_chain_pydantic, create_tagging_chain, create_tagging_chain_pydantic, ) "create_tagging_chain_pydantic", "load_chain", "create_citation_fuzzy_match_chain", "StuffDocumentsChain", "MapRer...
<vulnerable_code> create_extraction_chain, create_extraction_chain_pydantic, ) from langchain.chains.openai_functions.tagging import ( create_tagging_chain, create_tagging_chain_pydantic, "create_extraction_chain_pydantic", "create_extraction_chain", "create_citation_fuzzy_match_chain", ]<com...
<vulnerable_code><commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_code> from typing import Any, List from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.chains.llm import L...
<vulnerable_code> for message in messages: if isinstance(message, BaseMessagePromptTemplate): input_vars.update(message.input_variables) if "input_variables" in values: if input_vars != set(values["input_variables"]): raise ValueError(<commit_title>...
<vulnerable_code> messages = [HumanMessagePromptTemplate.from_template("{foo}")] prompt = ChatPromptTemplate(messages=messages) assert prompt.input_variables == ["foo"]<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixed_c...
<vulnerable_code>"""Wrapper around SingleStore DB.""" from __future__ import annotations import json from typing import ( Any, from langchain.vectorstores.base import VectorStore, VectorStoreRetriever class SingleStoreDB(VectorStore): """ This class serves as a Pythonic interface to the SingleStore DB da...