id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
50
116
f1a9f7863715-26
{'action': 'on_llm_end', 'token_usage_prompt_tokens': 242, 'token_usage_completion_tokens': 28, 'token_usage_total_tokens': 270, 'model_name': 'text-davinci-003', 'step': 8, 'starts': 5, 'ends': 3, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_ends': 2, 'llm_streams': 0, 'tool_st...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-27
I need to find out who Bryan Adams is married to. Action: Search Action Input: "Who is Bryan Adams married to"{'action': 'on_agent_action', 'tool': 'Search', 'tool_input': 'Who is Bryan Adams married to', 'log': ' I need to find out who Bryan Adams is married to.\nAction: Search\nAction Input: "Who is Bryan Adams marri...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-28
Thought:{'action': 'on_tool_end', 'output': 'Bryan Adams has never married. In the 1990s, he was in a relationship with Danish model Cecilie Thomsen. In 2011, Bryan and Alicia Grimaldi, his ...', 'step': 11, 'starts': 7, 'ends': 4, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 2, 'llm_en...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-29
{'action': 'on_llm_start', 'name': 'OpenAI', 'step': 12, 'starts': 8, 'ends': 4, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 3, 'llm_ends': 2, 'llm_streams': 0, 'tool_starts': 4, 'tool_ends': 2, 'agent_ends': 0, 'prompts': 'Answer the following questions as best you can. You have acces...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-30
to the original input question\n\nBegin!\n\nQuestion: Who is the wife of the person who sang summer of 69?\nThought: I need to find out who sang summer of 69 and then find out who their wife is.\nAction: Search\nAction Input: "Who sang summer of 69"\nObservation: Bryan Adams - Summer Of 69 (Official Music Video).\nThou...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-31
{'action': 'on_llm_end', 'token_usage_prompt_tokens': 314, 'token_usage_completion_tokens': 18, 'token_usage_total_tokens': 332, 'model_name': 'text-davinci-003', 'step': 13, 'starts': 8, 'ends': 5, 'errors': 0, 'text_ctr': 0, 'chain_starts': 1, 'chain_ends': 0, 'llm_starts': 3, 'llm_ends': 3, 'llm_streams': 0, 'tool_s...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-32
I now know the final answer. Final Answer: Bryan Adams has never been married. {'action': 'on_agent_finish', 'output': 'Bryan Adams has never been married.', 'log': ' I now know the final answer.\nFinal Answer: Bryan Adams has never been married.', 'step': 14, 'starts': 8, 'ends': 6, 'errors': 0, 'text_ctr': 0, 'chain_...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-33
4 on_llm_start OpenAI 1 1 0 0 0 .. ... ... ... ... ... ... ... 66 on_tool_end NaN 11 7 4 0 0 67 on_llm_start OpenAI 12 8 4 0 0 68 on_llm_end NaN 13 8 ...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-34
69 1 0 3 ... NaN NaN NaN 70 1 1 3 ... NaN NaN NaN tool tool_input log \ 0 NaN NaN NaN 1 NaN ...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-35
0 2 Answer the following questions as best you can... OpenAI 1 7 Answer the following questions as best you can... OpenAI 2 12 Answer the following questions as best you can... OpenAI output_step output \ 0 3 I n...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
f1a9f7863715-36
2 3rd and 4th grade 115.70 110.84 49.79 crawford gulpease_index osman 0 0.9 72.7 92.16 1 0.7 74.7 84.20 2 0.7 85.4 83.14 [3 rows x 24 columns]} Could not update last created model in Task 988bd727b0e94a29a3ac0ee526813545...
https:///python.langchain.com/en/latest/ecosystem/clearml_tracking.html
2b82ac8374a6-0
.md .pdf Metal Contents What is Metal? Quick start Metal# This page covers how to use Metal within LangChain. What is Metal?# Metal is a managed retrieval & memory platform built for production. Easily index your data into Metal and run semantic search and retrieval on it. Quick start# Get started by creating a Meta...
https:///python.langchain.com/en/latest/ecosystem/metal.html
6908f86a9652-0
.md .pdf RWKV-4 Contents Installation and Setup Usage RWKV Model File Rwkv-4 models -> recommended VRAM RWKV-4# This page covers how to use the RWKV-4 wrapper within LangChain. It is broken into two parts: installation and setup, and then usage with an example. Installation and Setup# Install the Python package with ...
https:///python.langchain.com/en/latest/ecosystem/rwkv.html
6908f86a9652-1
RWKV VRAM Model | 8bit | bf16/fp16 | fp32 14B | 16GB | 28GB | >50GB 7B | 8GB | 14GB | 28GB 3B | 2.8GB| 6GB | 12GB 1b5 | 1.3GB| 3GB | 6GB See the rwkv pip page for more information about strategies, including streaming and cuda support. previous Runhouse next SearxNG Search API Contents...
https:///python.langchain.com/en/latest/ecosystem/rwkv.html
c7a366428011-0
.md .pdf Replicate Contents Installation and Setup Calling a model Replicate# This page covers how to run models on Replicate within LangChain. Installation and Setup# Create a Replicate account. Get your API key and set it as an environment variable (REPLICATE_API_TOKEN) Install the Replicate python client with pip ...
https:///python.langchain.com/en/latest/ecosystem/replicate.html
c7a366428011-1
And run it: prompt = """ Answer the following yes/no question by reasoning step by step. Can a dog drive a car? """ llm(prompt) We can call any Replicate model (not just LLMs) using this syntax. For example, we can call Stable Diffusion: text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46e...
https:///python.langchain.com/en/latest/ecosystem/replicate.html
390663403a74-0
.ipynb .pdf Aim Aim# Aim makes it super easy to visualize and debug LangChain executions. Aim tracks inputs and outputs of LLMs and tools, as well as actions of agents. With Aim, you can easily debug and examine an individual execution: Additionally, you have the option to compare multiple executions side by side: Aim ...
https:///python.langchain.com/en/latest/ecosystem/aim_tracking.html
390663403a74-1
aim_callback = AimCallbackHandler( repo=".", experiment_name="scenario 1: OpenAI LLM", ) callbacks = [StdOutCallbackHandler(), aim_callback] llm = OpenAI(temperature=0, callbacks=callbacks) The flush_tracker function is used to record LangChain assets on Aim. By default, the session is reset rather than being t...
https:///python.langchain.com/en/latest/ecosystem/aim_tracking.html
390663403a74-2
) Scenario 3 The third scenario involves an agent with tools. from langchain.agents import initialize_agent, load_tools from langchain.agents import AgentType # scenario 3 - Agent with Tools tools = load_tools(["serpapi", "llm-math"], llm=llm, callbacks=callbacks) agent = initialize_agent( tools, llm, agent...
https:///python.langchain.com/en/latest/ecosystem/aim_tracking.html
390663403a74-3
AnalyticDB By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/ecosystem/aim_tracking.html
357ca65413db-0
.md .pdf Tair Contents Installation and Setup Wrappers VectorStore Tair# This page covers how to use the Tair ecosystem within LangChain. Installation and Setup# Install Tair Python SDK with pip install tair. Wrappers# VectorStore# There exists a wrapper around TairVector, allowing you to use it as a vectorstore, whe...
https:///python.langchain.com/en/latest/ecosystem/tair.html
0c686406e479-0
.md .pdf Locally Hosted Setup Contents Installation Environment Setup Locally Hosted Setup# This page contains instructions for installing and then setting up the environment to use the locally hosted version of tracing. Installation# Ensure you have Docker installed (see Get Docker) and that it’s running. Install th...
https:///python.langchain.com/en/latest/tracing/local_installation.html
0c686406e479-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/tracing/local_installation.html
50240fd1997b-0
.md .pdf Cloud Hosted Setup Contents Installation Environment Setup Cloud Hosted Setup# We offer a hosted version of tracing at langchainplus.vercel.app. You can use this to view traces from your run without having to run the server locally. Note: we are currently only offering this to a limited number of users. The ...
https:///python.langchain.com/en/latest/tracing/hosted_installation.html
50240fd1997b-1
os.environ["LANGCHAIN_API_KEY"] = "my_api_key" # Don't commit this to your repo! Better to set it in your terminal. Contents Installation Environment Setup By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/tracing/hosted_installation.html
eb3bdd709883-0
.ipynb .pdf Tracing Walkthrough Tracing Walkthrough# There are two recommended ways to trace your LangChains: Setting the LANGCHAIN_TRACING environment variable to “true”. Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is set, all code will be traced...
https:///python.langchain.com/en/latest/tracing/agent_with_tracing.html
eb3bdd709883-1
I need to use a calculator to solve this. Action: Calculator Action Input: 2^.123243 Observation: Answer: 1.0891804557407723 Thought: I now know the final answer. Final Answer: 1.0891804557407723 > Finished chain. '1.0891804557407723' # Agent run with tracing using a chat model agent = initialize_agent( tools, Chat...
https:///python.langchain.com/en/latest/tracing/agent_with_tracing.html
eb3bdd709883-2
Action: Calculator Action Input: 5 ^ .123243 Observation: Answer: 1.2193914912400514 Thought:I now know the answer to the question. Final Answer: 1.2193914912400514 > Finished chain. # Now, we unset the environment variable and use a context manager. if "LANGCHAIN_TRACING" in os.environ: del os.environ["LANGCHAIN_...
https:///python.langchain.com/en/latest/tracing/agent_with_tracing.html
eb3bdd709883-3
del os.environ["LANGCHAIN_TRACING"] questions = [f"What is {i} raised to .123 power?" for i in range(1,4)] # start a background task task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[...
https:///python.langchain.com/en/latest/tracing/agent_with_tracing.html
87147a8e359e-0
Source code for langchain.text_splitter """Functionality for splitting text.""" from __future__ import annotations import copy import logging from abc import ABC, abstractmethod from typing import ( AbstractSet, Any, Callable, Collection, Iterable, List, Literal, Optional, Sequence, ...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-1
for chunk in self.split_text(text): new_doc = Document( page_content=chunk, metadata=copy.deepcopy(_metadatas[i]) ) documents.append(new_doc) return documents [docs] def split_documents(self, documents: List[Document]) -> List[Document]: ...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-2
docs.append(doc) # Keep on popping if: # - we have a larger chunk than in the chunk overlap # - or if we still have any chunks and the length is long while total > self._chunk_overlap or ( total + _len + (separator_l...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-3
[docs] @classmethod def from_tiktoken_encoder( cls, encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all", **kwargs: Any, ...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-4
"""Asynchronously transform a sequence of documents by splitting them.""" raise NotImplementedError [docs]class CharacterTextSplitter(TextSplitter): """Implementation of splitting text that looks at characters.""" def __init__(self, separator: str = "\n\n", **kwargs: Any): """Create a new TextSp...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-5
enc = tiktoken.encoding_for_model(model_name) else: enc = tiktoken.get_encoding(encoding_name) self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text(self, text: str) -> List[str]: """Split ...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-6
# Get appropriate separator to use separator = self._separators[-1] for _s in self._separators: if _s == "": separator = _s break if _s in text: separator = _s break # Now that we have the separator, split th...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-7
[docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" # First we naively split the large input into a bunch of smaller ones. splits = self._tokenizer(text) return self._merge_splits(splits, self._separator) [docs]class SpacyTextSplitter(Text...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-8
# Note the alternative syntax for headings (below) is not handled here # Heading level 2 # --------------- # End of code block "```\n\n", # Horizontal lines "\n\n***\n\n", "\n\n---\n\n", "\n\n___\n\n", # Note tha...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
87147a8e359e-9
# Now split by the normal type of lines " ", "", ] super().__init__(separators=separators, **kwargs) [docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Python syntax.""" def __init__(self, **kwargs: Any): """Ini...
https:///python.langchain.com/en/latest/_modules/langchain/text_splitter.html
71c2a2faee1f-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper aroun...
https:///python.langchain.com/en/latest/_modules/langchain/requests.html
71c2a2faee1f-1
def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.Clien...
https:///python.langchain.com/en/latest/_modules/langchain/requests.html
71c2a2faee1f-2
"""PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: ...
https:///python.langchain.com/en/latest/_modules/langchain/requests.html
71c2a2faee1f-3
"""POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, ur...
https:///python.langchain.com/en/latest/_modules/langchain/requests.html
71c2a2faee1f-4
"""PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.req...
https:///python.langchain.com/en/latest/_modules/langchain/requests.html
8245ffcd92df-0
Source code for langchain.document_transformers """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.math_utils import cosine_similarity from langchain.schema import BaseDocumen...
https:///python.langchain.com/en/latest/_modules/langchain/document_transformers.html
8245ffcd92df-1
for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: # Default to dropping the second document of any highly similar pair. included_idxs.remove(second_idx) return list(sorted(included_idxs)) def _get_embeddin...
https:///python.langchain.com/en/latest/_modules/langchain/document_transformers.html
8245ffcd92df-2
"""Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( self.embeddings, stateful_documents ) included_idxs = _filter_similar_embeddings( embedded_documents, self.similarity_fn, s...
https:///python.langchain.com/en/latest/_modules/langchain/document_transformers.html
6cdb29db0b1a-0
Source code for langchain.experimental.autonomous_agents.baby_agi.baby_agi """BabyAGI agent.""" from collections import deque from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerFo...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
6cdb29db0b1a-1
print(str(t["task_id"]) + ": " + t["task_name"]) def print_next_task(self, task: Dict) -> None: print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m") print(str(task["task_id"]) + ": " + task["task_name"]) def print_task_result(self, result: str) -> None: print("\033[93m...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
6cdb29db0b1a-2
next_task_id = int(this_task_id) + 1 response = self.task_prioritization_chain.run( task_names=", ".join(task_names), next_task_id=str(next_task_id), objective=objective, ) new_tasks = response.split("\n") prioritized_task_list = [] for task_st...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
6cdb29db0b1a-3
"""Run the agent.""" objective = inputs["objective"] first_task = inputs.get("first_task", "Make a todo list") self.add_task({"task_id": 1, "task_name": first_task}) num_iters = 0 while True: if self.task_list: self.print_task_list() # ...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
6cdb29db0b1a-4
break return {} [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, vectorstore: VectorStore, verbose: bool = False, task_execution_chain: Optional[Chain] = None, **kwargs: Dict[str, Any], ) -> "BabyAGI": """Initialize the BabyAGI Con...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/baby_agi/baby_agi.html
5198cfa20be5-0
Source code for langchain.experimental.autonomous_agents.autogpt.agent from __future__ import annotations from typing import List, Optional from pydantic import ValidationError from langchain.chains.llm import LLMChain from langchain.chat_models.base import BaseChatModel from langchain.experimental.autonomous_agents.au...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
5198cfa20be5-1
ai_role: str, memory: VectorStoreRetriever, tools: List[BaseTool], llm: BaseChatModel, human_in_the_loop: bool = False, output_parser: Optional[BaseAutoGPTOutputParser] = None, ) -> AutoGPT: prompt = AutoGPTPrompt( ai_name=ai_name, ai_role=ai_r...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
5198cfa20be5-2
# Get command name and arguments action = self.output_parser.parse(assistant_reply) tools = {t.name: t for t in self.tools} if action.name == FINISH_NAME: return action.args["response"] if action.name in tools: tool = tools[action.name] ...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/autonomous_agents/autogpt/agent.html
66ee35c90655-0
Source code for langchain.experimental.generative_agents.generative_agent import re from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.experimental.gen...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-1
arbitrary_types_allowed = True # LLM-related methods @staticmethod def _parse_list(text: str) -> List[str]: """Parse a newline-separated string into a list of strings.""" lines = re.split(r"\n", text.strip()) return [re.sub(r"^\s*\d+\.\s*", "", line).strip() for line in lines] de...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-2
entity_action = self._get_entity_action(observation, entity_name) q1 = f"What is the relationship between {self.name} and {entity_name}" q2 = f"{entity_name} is {entity_action}" return self.chain(prompt=prompt).run(q1=q1, queries=[q1, q2]).strip() def _generate_reaction(self, observation: st...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-3
return self.chain(prompt=prompt).run(**kwargs).strip() def _clean_response(self, text: str) -> str: return re.sub(f"^{self.name} ", "", text.strip()).strip() [docs] def generate_reaction(self, observation: str) -> Tuple[bool, str]: """React to a given observation.""" call_to_action_templa...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-4
"""React to a given observation.""" call_to_action_template = ( "What would {agent_name} say? To end the conversation, write:" ' GOODBYE: "what to say". Otherwise to continue the conversation,' ' write: SAY: "what to say next"\n\n' ) full_result = self._genera...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-5
"How would you summarize {name}'s core characteristics given the" + " following statements:\n" + "{relevant_memories}" + "Do not embellish." + "\n\nSummary: " ) # The agent seeks to think about their core characteristics. return ( self....
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
66ee35c90655-6
) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/generative_agent.html
0b5f766121a5-0
Source code for langchain.experimental.generative_agents.memory import logging import re from typing import Any, Dict, List, Optional from langchain import LLMChain from langchain.base_language import BaseLanguageModel from langchain.prompts import PromptTemplate from langchain.retrievers import TimeWeightedVectorStore...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0b5f766121a5-1
relevant_memories_simple_key: str = "relevant_memories_simple" most_recent_memories_key: str = "most_recent_memories" def chain(self, prompt: PromptTemplate) -> LLMChain: return LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose) @staticmethod def _parse_list(text: str) -> List[str]: ...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0b5f766121a5-2
+ "What 5 high-level insights can you infer from the above statements?" + " (example format: insight (because of 1, 5, 3))" ) related_memories = self.fetch_memories(topic) related_statements = "\n".join( [ f"{i+1}. {memory.page_content}" fo...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0b5f766121a5-3
+ "\nMemory: {memory_content}" + "\nRating: " ) score = self.chain(prompt).run(memory_content=memory_content).strip() if self.verbose: logger.info(f"Importance score: {score}") match = re.search(r"^\D*(\d+)", score) if match: return (float(scor...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0b5f766121a5-4
content = [] for mem in relevant_memories: if mem.page_content in content_strs: continue content_strs.add(mem.page_content) created_time = mem.metadata["created_at"].strftime("%B %d, %Y, %I:%M %p") content.append(f"- {created_time}: {mem.page_conte...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0b5f766121a5-5
relevant_memories ), self.relevant_memories_simple_key: self.format_memories_simple( relevant_memories ), } most_recent_memories_token = inputs.get(self.most_recent_memories_token_key) if most_recent_memories_token is not No...
https:///python.langchain.com/en/latest/_modules/langchain/experimental/generative_agents/memory.html
0c3430986812-0
Source code for langchain.retrievers.time_weighted_retriever """Retriever that combines embedding similarity with recency in retrieving values.""" from copy import deepcopy from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain.schema impor...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
0c3430986812-1
""" class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def _get_combined_score( self, document: Document, vector_relevance: Optional[float], current_time: datetime, ) -> float: """Return the combined score for a ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
0c3430986812-2
for doc in self.memory_stream[-self.k :] } # If a doc is considered salient, update the salience score docs_and_scores.update(self.get_salient_docs(query)) rescored_docs = [ (doc, self._get_combined_score(doc, relevance, current_time)) for doc, relevance in docs_a...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
0c3430986812-3
self.memory_stream.extend(dup_docs) return self.vectorstore.add_documents(dup_docs, **kwargs) [docs] async def aadd_documents( self, documents: List[Document], **kwargs: Any ) -> List[str]: """Add documents to vectorstore.""" current_time = kwargs.get("current_time", datetime.now(...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
f7dd5ec0c2a2-0
Source code for langchain.retrievers.pinecone_hybrid_search """Taken from: https://docs.pinecone.io/docs/hybrid-search""" import hashlib from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.schema import BaseRe...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
f7dd5ec0c2a2-1
vectors = [] # loop through the data and create dictionaries for upserts for doc_id, sparse, dense, metadata in zip( batch_ids, sparse_embeds, dense_embeds, meta ): vectors.append( { "id": doc_id, "sparse_values": sp...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
f7dd5ec0c2a2-2
[docs] def get_relevant_documents(self, query: str) -> List[Document]: from pinecone_text.hybrid import hybrid_convex_scale sparse_vec = self.sparse_encoder.encode_queries(query) # convert the question into a dense vector dense_vec = self.embeddings.embed_query(query) # scale ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
8ec8956f5ffb-0
Source code for langchain.retrievers.vespa_retriever """Wrapper for retrieving documents from Vespa.""" from __future__ import annotations import json from typing import TYPE_CHECKING, List from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from vespa.application import Vespa [docs]class VespaRe...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
6d13cd243caf-0
Source code for langchain.retrievers.tfidf """TF-IDF Retriever. Largely based on https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb""" from typing import Any, Dict, List, Optional from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
6d13cd243caf-1
results = cosine_similarity(self.tfidf_array, query_vec).reshape( (-1,) ) # Op -- (n_docs,1) -- Cosine Sim with each doc return_docs = [] for i in results.argsort()[-self.k :][::-1]: return_docs.append(self.docs[i]) return return_docs [docs] async def aget_rel...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
878fc7f4d544-0
Source code for langchain.retrievers.svm """SMV Retriever. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb""" from __future__ import annotations import concurrent.futures from typing import Any, List, Optional import numpy as np from pydantic import BaseModel from langchain.embedding...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
878fc7f4d544-1
y[0] = 1 clf = svm.LinearSVC( class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1 ) clf.fit(x, y) similarities = clf.decision_function(x) sorted_ix = np.argsort(-similarities) # svm.LinearSVC in scikit-learn is non-deterministic. # ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
6742566a74ef-0
Source code for langchain.retrievers.elastic_search_bm25 """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from typing import Any, Iterable, List from langchain.docstore.document import Document from langchain.schema import BaseRetriever [docs]class ElasticSearchBM25Retr...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
6742566a74ef-1
self.index_name = index_name [docs] @classmethod def create( cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75 ) -> ElasticSearchBM25Retriever: from elasticsearch import Elasticsearch # Create an Elasticsearch client instance es = Elasticsearch(ela...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
6742566a74ef-2
raise ValueError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) requests = [] ids = [] for i, text in enumerate(texts): _id = str(uuid.uuid4()) request = { ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
6f66422d69d3-0
Source code for langchain.retrievers.remote_retriever from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class RemoteLangChainRetriever(BaseRetriever, BaseModel): url: str headers: Optional[dict] = None i...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html
bbc098aeae7e-0
Source code for langchain.retrievers.contextual_compression """Retriever that wraps a base retriever and filters the results.""" from typing import List from pydantic import BaseModel, Extra from langchain.retrievers.document_compressors.base import ( BaseDocumentCompressor, ) from langchain.schema import BaseRetri...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
bbc098aeae7e-1
return list(compressed_docs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
6bf6fa91f949-0
Source code for langchain.retrievers.weaviate_hybrid_search """Wrapper around weaviate vector database.""" from __future__ import annotations from typing import Any, Dict, List, Optional from uuid import uuid4 from pydantic import Extra from langchain.docstore.document import Document from langchain.schema import BaseR...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
6bf6fa91f949-1
"""Upload documents to Weaviate.""" from weaviate.util import get_valid_uuid with self._client.batch as batch: ids = [] for i, doc in enumerate(docs): metadata = doc.metadata or {} data_properties = {self._text_key: doc.page_content, **metadata} ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
daf3147b9a66-0
Source code for langchain.retrievers.databerry from typing import List, Optional import aiohttp import requests from langchain.schema import BaseRetriever, Document [docs]class DataberryRetriever(BaseRetriever): datastore_url: str top_k: Optional[int] api_key: Optional[str] def __init__( self, ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
daf3147b9a66-1
self.datastore_url, json={ "query": query, **({"topK": self.top_k} if self.top_k is not None else {}), }, headers={ "Content-Type": "application/json", **( {"Authorizat...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
b588956a6bd3-0
Source code for langchain.retrievers.chatgpt_plugin_retriever from __future__ import annotations from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class ChatGPTPluginRetriever(BaseRetriever, BaseModel): url: str...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
b588956a6bd3-1
docs = [] for d in results: content = d.pop("text") docs.append(Document(page_content=content, metadata=d)) return docs def _create_request(self, query: str) -> tuple[str, dict, dict]: url = f"{self.url}/query" json = { "queries": [ ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
2e0d570bff24-0
Source code for langchain.retrievers.metal from typing import Any, List, Optional from langchain.schema import BaseRetriever, Document [docs]class MetalRetriever(BaseRetriever): def __init__(self, client: Any, params: Optional[dict] = None): from metal_sdk.metal import Metal if not isinstance(client...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html
b1e545e46634-0
Source code for langchain.retrievers.document_compressors.embeddings_filter """Document compressor that uses embeddings to drop documents unrelated to the query.""" from typing import Callable, Dict, Optional, Sequence import numpy as np from pydantic import root_validator from langchain.document_transformers import ( ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
b1e545e46634-1
return values [docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embed...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
9e9715e911b3-0
Source code for langchain.retrievers.document_compressors.base """Interface for retrieved document compressors.""" from abc import ABC, abstractmethod from typing import List, Sequence, Union from pydantic import BaseModel from langchain.schema import BaseDocumentTransformer, Document class BaseDocumentCompressor(BaseM...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
9e9715e911b3-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): documents = await _transformer.acompress_docume...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
7f1a0da7eb8e-0
Source code for langchain.retrievers.document_compressors.chain_filter """Filter that uses an LLM to drop documents that aren't relevant to the query.""" from typing import Any, Callable, Dict, Optional, Sequence from langchain import BasePromptTemplate, LLMChain, PromptTemplate from langchain.base_language import Base...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
7f1a0da7eb8e-1
include_doc = self.llm_chain.predict_and_parse(**_input) if include_doc: filtered_docs.append(doc) return filtered_docs [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter down documents.""" ...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
3fbe180ab87f-0
Source code for langchain.retrievers.document_compressors.cohere_rerank from __future__ import annotations from typing import TYPE_CHECKING, Dict, Sequence from pydantic import root_validator from langchain.retrievers.document_compressors.base import BaseDocumentCompressor from langchain.schema import Document from lan...
https:///python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html