text stringlengths 79 3.72M |
|---|
<vulnerable_code>"""Agent for working with pandas objects."""
from typing import Any, Dict, List, Optional, Tuple
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.pandas.prompt import (
MULTI_DF_PREFIX,
PREFIX,
SUFFIX_NO_DF,
SUFFIX_WITH_DF,
SUFFIX_WITH_MULTI_DF,... |
<vulnerable_code>Begin!
Question: {input}
{agent_scratchpad}"""<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>
Begin!
Question: {input}
{agent_scratchpad}"""
PREFIX_FUNCTIONS = """
You are working with a pandas dataframe ... |
<vulnerable_code>
from typing import Any, Dict, Optional
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.python.prompt import PREFIX
from langchain.agents.mrkl.base import ZeroShotAgent
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.base import Base... |
<vulnerable_code>"""SQL agent."""
from typing import Any, Dict, List, Optional
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.sql.prompt import SQL_PREFIX, SQL_SUFFIX
from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit
from langchain.agents.mrkl.base import... |
<vulnerable_code>Question: {input}
Thought: I should look at the tables in the database to see what I can query. Then I should query the schema of the most relevant tables.
{agent_scratchpad}"""<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. ... |
<vulnerable_code>from langchain.agents import BaseSingleActionAgent
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.base import BaseCallbackManager
from langchain.callbacks.manager import (
Callbacks,
)
from langchain.chat_models.openai import ChatOpenAI
from langchain.prompts.base im... |
<vulnerable_code>class ArxivQueryRun(BaseTool):
"""Tool that adds the capability to search using the Arxiv API."""
name = "Arxiv"
description = (
"A wrapper around Arxiv.org "
"Useful for when you need to answer questions about Physics, Mathematics, "<commit_title>[PATCH 001/150] Mongo db d... |
<vulnerable_code> azure_cogs_endpoint: str = "" #: :meta private:
doc_analysis_client: Any #: :meta private:
name = "Azure Cognitive Services Form Recognizer"
description = (
"A wrapper around Azure Cognitive Services Form Recognizer. "
"Useful for when you need to "<commit_title>[PATC... |
<vulnerable_code> vision_service: Any #: :meta private:
analysis_options: Any #: :meta private:
name = "Azure Cognitive Services Image Analysis"
description = (
"A wrapper around Azure Cognitive Services Image Analysis. "
"Useful for when you need to analyze images. "<commit_title>[PAT... |
<vulnerable_code> speech_language: str = "en-US" #: :meta private:
speech_config: Any #: :meta private:
name = "Azure Cognitive Services Speech2Text"
description = (
"A wrapper around Azure Cognitive Services Speech2Text. "
"Useful for when you need to transcribe audio to text. "<commi... |
<vulnerable_code> speech_language: str = "en-US" #: :meta private:
speech_config: Any #: :meta private:
name = "Azure Cognitive Services Text2Speech"
description = (
"A wrapper around Azure Cognitive Services Text2Speech. "
"Useful for when you need to convert text to speech. "<commit_... |
<vulnerable_code>class BingSearchRun(BaseTool):
"""Tool that adds the capability to query the Bing search API."""
name = "Bing Search"
description = (
"A wrapper around Bing Search. "
"Useful for when you need to answer questions about current events. "<commit_title>[PATCH 001/150] Mongo db... |
<vulnerable_code>
class BraveSearch(BaseTool):
name = "brave-search"
description = (
"a search engine. "
"useful for when you need to answer questions about current events."<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase... |
<vulnerable_code>class DuckDuckGoSearchRun(BaseTool):
"""Tool that adds the capability to query the DuckDuckGo search API."""
name = "DuckDuckGo Search"
description = (
"A wrapper around DuckDuckGo Search. "
"Useful for when you need to answer questions about current events. "<commit_title>... |
<vulnerable_code>class GooglePlacesTool(BaseTool):
"""Tool that adds the capability to query the Google places API."""
name = "Google Places"
description = (
"A wrapper around Google Places. "
"Useful for when you need to validate or "<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<c... |
<vulnerable_code>class GoogleSearchRun(BaseTool):
"""Tool that adds the capability to query the Google search API."""
name = "Google Search"
description = (
"A wrapper around Google Search. "
"Useful for when you need to answer questions about current events. "<commit_title>[PATCH 001/150] ... |
<vulnerable_code>class GoogleSerperRun(BaseTool):
"""Tool that adds the capability to query the Serper.dev Google search API."""
name = "Google Serper"
description = (
"A low-cost Google Search API."
"Useful for when you need to answer questions about current events."<commit_title>[PATCH 00... |
<vulnerable_code>class HumanInputRun(BaseTool):
"""Tool that adds the capability to ask user for input."""
name = "Human"
description = (
"You can ask a human for guidance when you think you "
"got stuck or you are not sure what to do next. "<commit_title>[PATCH 001/150] Mongo db doc fix (#... |
<vulnerable_code>class MetaphorSearchResults(BaseTool):
"""Tool that has capability to query the Metaphor Search API and get back json."""
name = "Metaphor Search Results JSON"
description = (
"A wrapper around Metaphor Search. "
"Input should be a Metaphor-optimized query. "<commit_title>[... |
<vulnerable_code>class PythonREPLTool(BaseTool):
"""A tool for running python code in a REPL."""
name = "Python REPL"
description = (
"A Python shell. Use this to execute python commands. "
"Input should be a valid python command. "<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<comm... |
<vulnerable_code>class SceneXplainTool(BaseTool):
"""Tool that adds the capability to explain images."""
name = "Image Explainer"
description = (
"An Image Captioning Tool: Use this tool to generate a detailed caption "
"for an image. The input can be an image file of any format, and "<comm... |
<vulnerable_code>class SearxSearchRun(BaseTool):
"""Tool that adds the capability to query a Searx instance."""
name = "Searx Search"
description = (
"A meta search engine."
"Useful for when you need to answer questions about current events."<commit_title>[PATCH 001/150] Mongo db doc fix (#... |
<vulnerable_code>class WolframAlphaQueryRun(BaseTool):
"""Tool that adds the capability to query using the Wolfram Alpha SDK."""
name = "Wolfram Alpha"
description = (
"A wrapper around Wolfram Alpha. "
"Useful for when you need to answer questions about Math, "<commit_title>[PATCH 001/150]... |
<vulnerable_code>
class YouTubeSearchTool(BaseTool):
name = "YouTubeSearch"
description = (
"search for youtube videos associated with a person. "
"the input to this tool should be a comma separated list, "<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few ... |
<vulnerable_code>
"""
name = "Zapier NLA: List Actions"
description = BASE_ZAPIER_TOOL_PROMPT + (
"This tool returns a list of the user's exposed actions."
)<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1. Thanks!<fixe... |
<vulnerable_code> """Whether to print out response text."""
callbacks: Callbacks = Field(default=None, exclude=True)
callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)
@root_validator()
def raise_deprecation(cls, values: Dict) -> Dict:
messages: List[List[Bas... |
<vulnerable_code>import functools
import logging
from datetime import datetime
from typing import Any, Callable, Coroutine, Dict, Iterator, List, Optional, Union
from langchainplus_sdk import LangChainPlusClient
from langchainplus_sdk.schemas import Example
llm: BaseLanguageModel,
inputs: Dict[str, Any],
l... |
<vulnerable_code> """Whether to print out response text."""
callbacks: Callbacks = Field(default=None, exclude=True)
callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)
class Config:
"""Configuration for this pydantic object."""
prompts: List[str],
... |
<vulnerable_code>"""Test the LangChain+ client."""
import uuid
from datetime import datetime
from typing import Any, Dict, List, Union
from unittest import mock
import pytest
llm_or_chain: Union[BaseLanguageModel, Chain],
n_repetitions: int,
tracer: Any,
) -> List[Dict[str, Any]]:
r... |
<vulnerable_code>"""All different types of document loaders."""
from langchain.document_loaders.airbyte_json import AirbyteJSONLoader
from langchain.document_loaders.airtable import AirtableLoader
from langchain.document_loaders.apify_dataset import ApifyDatasetLoader
TelegramChatLoader = TelegramChatFileLoader
__all... |
<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>
"""Loader that loads acreom vault from a directory."""
import re
from pathlib import Path
from typing import Iterator, List
from langchain.docstore.document... |
<vulnerable_code>from langchain.experimental.autonomous_agents.autogpt.prompt_generator import (
FINISH_NAME,
)
from langchain.schema import (
AIMessage,
BaseMessage,
Document,
HumanMessage,
SystemMessage,
output_parser: BaseAutoGPTOutputParser,
tools: List[BaseTool],
fee... |
<vulnerable_code> **kwargs,
)
else:
logger.warning(f"Error in {event_name} callback: {e}")
except Exception as e:
if handler.raise_error:
raise e
logger.warning(f"Error in {event_name} callback: {e}")
async ... |
<vulnerable_code> CallbackManagerForChainRun,
)
from langchain.chains.base import Chain
from langchain.chains.llm import LLMChain
from langchain.schema import RUN_KEY, BaseOutputParser
input_mapper: RunEvaluatorInputMapper
"""Maps the Run and Optional example to a dictionary for the eval chain."""
eva... |
<vulnerable_code>from typing import Any, Dict, Mapping, Optional, Sequence, Union
from langchainplus_sdk.evaluation.evaluator import EvaluationResult
from langchainplus_sdk.schemas import Example, Run
from pydantic import BaseModel
<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a fe... |
<vulnerable_code>from langchain.chains.loading import load_chain
from langchain.chains.mapreduce import MapReduceChain
from langchain.chains.moderation import OpenAIModerationChain
from langchain.chains.pal.base import PALChain
from langchain.chains.qa_generation.base import QAGenerationChain
from langchain.chains.qa_w... |
<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 functools import partial
from typing import Any, Dict, List, Optional
from pydantic import BaseModel
from langchain.base_language import B... |
<vulnerable_code>from functools import partial
from typing import Any, Dict, List, Optional
from pydantic import BaseModel
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import (
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.chat import ChatPrompt... |
<vulnerable_code> docs = []
for d in results:
content = d.pop("text")
docs.append(Document(page_content=content, metadata=d))
return docs
async def aget_relevant_documents(self, query: str) -> List[Document]:
docs = []
for d in results:
con... |
<vulnerable_code> """
endpoint_url: str = (
"https://models.hosted-on.mosaicml.hosting/instructor-large/v1/predict"
)
"""Endpoint URL to use."""
embed_instruction: str = "Represent the document for retrieval: "
f"Error raised by inference API: {parsed_response['error']}"
... |
<vulnerable_code> f"Error raised by inference API: {parsed_response['error']}"
)
if "data" not in parsed_response:
raise ValueError(
f"Error raised by inference API, no key data: {parsed_response}"
)
generate... |
<vulnerable_code>"""Util that calls Arxiv."""
import logging
import os
from typing import Any, Dict, List
from pydantic import BaseModel, Extra, root_validator
ARXIV_MAX_QUERY_LENGTH = 300
load_max_docs: int = 100
load_all_available_meta: bool = False
doc_content_chars_max: int = 4000
class Confi... |
<vulnerable_code> assert_docs(docs)
def test_load_returns_full_set_of_metadata() -> None:
"""Test that returns several docs"""
api_client = ArxivAPIWrapper(load_max_docs=1, load_all_available_meta=True)<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my ini... |
<vulnerable_code>
import toml
with open("../pyproject.toml") as f:
data = toml.load(f)
# -- Project information -----------------------------------------------------
"sphinx_copybutton",
"sphinx_panels",
"IPython.sphinxext.ipython_console_highlighting",
]
source_suffix = [".ipynb", ".html", ".md", ".r... |
<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>
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root d... |
<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>
/* eslint-disable prefer-template */
/* eslint-disable no-param-reassign */
// eslint-disable-next-line import/no-extraneous-dependencies
const babel = requi... |
<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>
document.addEventListener('DOMContentLoaded', () => {
// Load the external dependencies
function loadScript(src, onLoadCallback) {
const script = doc... |
<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>
/* eslint-disable global-require,import/no-extraneous-dependencies */
// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion
// ... |
<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>
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root d... |
<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>
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root d... |
<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>
/* eslint-disable react/jsx-props-no-spreading */
import React from "react";
import CodeBlock from "@theme-original/CodeBlock";
function Imports({ imports }... |
<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>
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root d... |
<vulnerable_code>
class VectorStoreRouterToolkit(BaseToolkit):
"""Toolkit for routing between vectorstores."""
vectorstores: List[VectorStoreInfo] = Field(exclude=True)
llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commi... |
<vulnerable_code> .. code-block:: python
from langchain import ConversationChain, OpenAI
conversation = ConversationChain(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_code... |
<vulnerable_code>"""Test loading functionality."""
import os
from contextlib import contextmanager
from pathlib import Path
from langchain.prompts.loading import load_prompt
from langchain.prompts.prompt import PromptTemplate
@contextmanager
def change_directory() -> Iterator:
"""Change the working directory to ... |
<vulnerable_code> },
{
type: "link",
href: "https://api.python.langchain.com/en/dev2049-docs_docusaurus/",
label: "API reference",
},
],<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>
llm_chain: LLMChain
requests_wrapper: TextRequestsWrapper = Field(
default_factory=TextRequestsWrapper, exclude=True
)
text_length: int = 8000
requests_key: str = "requests_result" #: :meta private:<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I... |
<vulnerable_code> self,
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
**kwargs: Any,
) -> List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
... |
<vulnerable_code>from __future__ import annotations
import logging
import uuid
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
import numpy as np
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from lang... |
<vulnerable_code> output = docsearch.similarity_search("foo", k=1)
assert output == [Document(page_content="foo")]
docsearch.persist()
# Get a new VectorStore from the persisted directory
docsearch = DeepLake(
dataset_path=dataset_path,
output = docsearch.similarity_search("foo", k=1)
... |
<vulnerable_code>
class ConversationEntityMemory(BaseChatMemory):
"""Entity extractor & summarizer to memory."""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT
entity_summarization_prompt: BasePro... |
<vulnerable_code> headers=self.__get_headers(),
)
res_data = res.json()
messages = res_data.get("messages", [])
context = res_data.get("context", "NONE")
<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors in my initial fix @hwchase1... |
<vulnerable_code>from langchain.retrievers.chatgpt_plugin_retriever import ChatGPTPluginRetriever
from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
from langchain.retrievers.databerry import DataberryRetriever
from langchain.retrievers.elastic_search_bm25 import ElasticSearchBM25Ret... |
<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 enum import Enum
from typing import Any, Dict, List, Optional, Union
import numpy as np
from pydantic import BaseModel
from langchain.embeddings.base ... |
<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 pathlib import Path
from typing import Any, Dict, Generator, Tuple
import numpy as np
import pytest
from docarray import BaseDoc
from docarray.index im... |
<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
import pytest
from vcr.request import Request
from langchain.retrievers import DocArrayRetriever
from tests.integration_tests.retrie... |
<vulnerable_code> disallowed_special=self.disallowed_special,
)
def modelname_to_contextsize(self, modelname: str) -> int:
"""Calculate the maximum number of tokens possible to generate for a model.
Args:<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I... |
<vulnerable_code>
import logging
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
import sqlalchemy
from sqlalchemy import REAL, Index
from sqlalchemy.dialects.postgresql import ARRAY, JSON, UUID
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.... |
<vulnerable_code>import os
from typing import List
from sqlalchemy.orm import Session
from langchain.docstore.document import Document
from langchain.vectorstores.analyticdb import AnalyticDB
from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings
CONNECTION_STRING = AnalyticDB.connection_stri... |
<vulnerable_code>from langchain.llms.self_hosted import SelfHostedPipeline
from langchain.llms.self_hosted_hugging_face import SelfHostedHuggingFaceLLM
from langchain.llms.stochasticai import StochasticAI
from langchain.llms.vertexai import VertexAI
from langchain.llms.writer import Writer
"GooseAI",
"GPT4All"... |
<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>
"""Wrapper around text-generation-webui."""
import logging
from typing import Any, Dict, List, Optional
import requests
from pydantic import Field
from lan... |
<vulnerable_code># 4. For service accounts visit
# https://cloud.google.com/iam/docs/service-accounts-create
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
"""Load credentials."""
# Adapted from https://developers.google.com/drive/api/v3/quickstart/python
... |
<vulnerable_code> all of them
- 'all' - query all replicas, and return values present in all replicas
Returns:
List of documents most similar to the query text and cosine
distance in float for each.
qdrant_filter = filter
r... |
<vulnerable_code> assert output == [Document(page_content="foo")]
@pytest.mark.parametrize("batch_size", [1, 64])
def test_qdrant_add_documents(batch_size: int) -> None:
"""Test end to end construction and search."""<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_description>I missed a few errors... |
<vulnerable_code> @classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
validate_tools_single_input(cls.__name__, tools)
for tool in tools:
if tool.description is None:
raise ValueError(<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_d... |
<vulnerable_code>
from langchain.agents.agent_types import AgentType
from langchain.agents.initialize import initialize_agent, load_agent
from langchain.llms.fake import FakeListLLM
def test_mrkl_serialization() -> None:
agent = initialize_agent(
[],
FakeListLLM(responses=[]),
agent=AgentT... |
<vulnerable_code> Sequence of relevant documents
"""
docs = self.base_retriever.get_relevant_documents(query)
compressed_docs = self.base_compressor.compress_documents(docs, query)
return list(compressed_docs)
async def aget_relevant_documents(self, query: str) -> List[Do... |
<vulnerable_code> ]
if len(docs_and_similarities) == 0:
warnings.warn(
f"No relevant docs were retrieved using the relevance score\
threshold {score_threshold}"
)
return docs_and_similarities
<commit_title>[PATC... |
<vulnerable_code> k: int = 4,
filter: Optional[Dict[str, Any]] = None,
fetch_k: int = 20,
) -> List[Tuple[Document, float]]:
"""Return docs most similar to query.
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
fetch_k: (Optional[int])... |
<vulnerable_code> default_request_timeout: Optional[Union[float, Tuple[float, float]]] = None
"""Timeout for requests to Anthropic Completion API. Default is 600 seconds."""
anthropic_api_key: Optional[str] = None
HUMAN_PROMPT: Optional[str] = None
anthropic_api_key = get_from_dict_or_env(
... |
<vulnerable_code>from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
model = ChatAnthropic(model="<model_name>", anthropic_api_key="my-api-key")
"""
class Config:
... |
<vulnerable_code>from functools import partial
from typing import Any, Dict, List, Mapping, Optional, Sequence
from pydantic import Extra, Field, root_validator
import langchain
from langchain.base_language import BaseLanguageModel
class Config:
"""Configuration for this pydantic object."""
extra... |
<vulnerable_code> Union,
)
from pydantic import Extra, Field, root_validator
from tenacity import (
before_sleep_log,
retry,
class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
allow_population_by_field_name = True
@root_validator(pre=True)<comm... |
<vulnerable_code>import warnings
from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union
from pydantic import BaseModel, Extra, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
)
return values
class Config:
"""Con... |
<vulnerable_code>from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
import yaml
from pydantic import Extra, Field, root_validator, validator
import langchain
from langchain.base_language import BaseLanguageModel
class Config:
"""Configuration for this pydantic object."""
... |
<vulnerable_code> Union,
)
from pydantic import Extra, Field, root_validator
from tenacity import (
before_sleep_log,
retry,
class Config:
"""Configuration for this pydantic object."""
extra = Extra.ignore
allow_population_by_field_name = True
@root_validator(pre=True)
... |
<vulnerable_code>from abc import ABC
from typing import Any, Dict, List, Literal, TypedDict, Union, cast
from pydantic import BaseModel, Field
class BaseSerialized(TypedDict):
"""
return {}
lc_kwargs: Dict[str, Any] = Field(default_factory=dict, exclude=True, repr=False)
def __init__(self, ... |
<vulnerable_code>from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union
import yaml
from pydantic import Extra, Field, root_validator
from langchain.formatting import formatter
from langchain.load.serializable import Serializable
class Config:
"""Configuration for this pydantic object... |
<vulnerable_code>from string import Formatter
from typing import Any, Dict, List, Union
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
"""Return the prompt type key."""
return "prompt"
class Config:
"""Configuration for this ... |
<vulnerable_code>)
from uuid import UUID
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.load.serializable import Serializable
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property<commit... |
<vulnerable_code> """kwargs for requests"""
def __init__(
self, web_path: Union[str, List[str]], header_template: Optional[dict] = None
):
"""Initialize with webpage path."""
"bs4 package not found, please install it with " "`pip install bs4`"
)
headers ... |
<vulnerable_code> "gpt-4-32k-0314": 0.06,
"gpt-4-32k-completion": 0.12,
"gpt-4-32k-0314-completion": 0.12,
"gpt-3.5-turbo": 0.002,
"gpt-3.5-turbo-0301": 0.002,
"text-ada-001": 0.0004,
"ada": 0.0004,
"text-babbage-001": 0.0005,<commit_title>[PATCH 001/150] Mongo db doc fix (#6042)<commit_d... |
<vulnerable_code>import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
from langchain.vectorstores.base import VectorStore
IMPORT_OPENSEARCH_PY_ERROR =... |
<vulnerable_code>from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
@classmethod
def from_rail(cls, rail_file: str... |
<vulnerable_code> recursive: bool = False
file_types: Optional[Sequence[str]] = None
load_trashed_files: bool = False
@root_validator
def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
returns.append(self._load_document_from_id(file["id"])) # type: ignore
... |
<vulnerable_code> def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> None:
"""Do nothing when LLM chain starts."""
if "input" in inputs:
self.prompts.update(
{
)
def on_chain_end(self, outputs: Dict... |
<vulnerable_code> [{**{self.document_variable_name: d.page_content}, **kwargs} for d in docs],
callbacks=callbacks,
)
return self._process_results(results, docs, callbacks=callbacks, **kwargs)
def _process_results(
self,
results: List[Dict],
docs: List... |
<vulnerable_code> )
self.web_path = self.file_path
self.temp_file = tempfile.NamedTemporaryFile()
self.temp_file.write(r.content)
self.file_path = self.temp_file.name
elif not os.path.isfile(self.file_path):
raise ValueError("File path ... |
<vulnerable_code> GTE = "gte"
LT = "lt"
LTE = "lte"
class FilterDirective(Expr, ABC):<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>
GTE = "gte"
LT = "lt"
LTE = "lte"
CONTAIN = "contain"
LI... |
<vulnerable_code>from typing import Any, Optional, Sequence, Union
try:
?value: SIGNED_INT -> int
| SIGNED_FLOAT -> float
| list
| string
| ("false" | "False" | "FALSE") -> false
| ("true" | "True" | "TRUE") -> true
args: expr ("," expr)*
string: /'[^']*'/ | ESCAPE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.