viruPVS/langchain-docs huggingface dataset:
langchain_experimental.generative_agents.generative_agent.GenerativeAgent¶
class langchain_experimental.generative_agents.generative_agent.GenerativeAgent[source]¶
Bases: BaseModel
An Agent as a character with memory and innate characteristics.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param age: Optional[int] = None¶
The optional age of the character.
param daily_summaries: List[str] [Optional]¶
Summary of the events in the plan that the agent took.
param last_refreshed: datetime.datetime [Optional]¶
The last time the character’s summary was regenerated.
param llm: langchain_core.language_models.base.BaseLanguageModel [Required]¶
The underlying language model.
param memory: langchain_experimental.generative_agents.memory.GenerativeAgentMemory [Required]¶
The memory object that combines relevance, recency, and ‘importance’.
param name: str [Required]¶
The character’s name.
param status: str [Required]¶
The traits of the character you wish not to change.
param summary: str = ''¶
Stateful self-summary generated via reflection on the character’s memory.
param summary_refresh_seconds: int = 3600¶
How frequently to re-generate the summary.
param traits: str = 'N/A'¶
Permanent traits to ascribe to the character.
param verbose: bool = False¶
chain(prompt: PromptTemplate) → LLMChain[source]¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include – fields to include in new model
exclude – fields to exclude from new model, as with values this takes precedence over include
update – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
classmethod from_orm(obj: Any) → Model¶
generate_dialogue_response(observation: str, now: Optional[datetime] = None) → Tuple[bool, str][source]¶
React to a given observation.
generate_reaction(observation: str, now: Optional[datetime] = None) → Tuple[bool, str][source]¶
React to a given observation.
get_full_header(force_refresh: bool = False, now: Optional[datetime] = None) → str[source]¶
Return a full header of the agent’s status, summary, and current time.
get_summary(force_refresh: bool = False, now: Optional[datetime] = None) → str[source]¶
Return a descriptive summary of the agent.
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
classmethod parse_obj(obj: Any) → Model¶
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
summarize_related_memories(observation: str) → str[source]¶
Summarize memories that are most relevant to an observation.
classmethod update_forward_refs(**localns: Any) → None¶
langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings¶
class langchain_experimental.open_clip.open_clip.OpenCLIPEmbeddings[source]¶
Bases: BaseModel, Embeddings
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param checkpoint: str = 'laion2b_s32b_b79k'¶
param model: Any = None¶
param model_name: str = 'ViT-H-14'¶
param preprocess: Any = None¶
param tokenizer: Any = None¶
async aembed_documents(texts: List[str]) → List[List[float]]¶
Asynchronous Embed search docs.
async aembed_query(text: str) → List[float]¶
Asynchronous Embed query text.
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include – fields to include in new model
exclude – fields to exclude from new model, as with values this takes precedence over include
update – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
the new model: you should trust this data
deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
embed_documents(texts: List[str]) → List[List[float]][source]¶
Embed search docs.
embed_image(uris: List[str]) → List[List[float]][source]¶
embed_query(text: str) → List[float][source]¶
Embed query text.
classmethod from_orm(obj: Any) → Model¶
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
langchain_community.docstore.arbitrary_fn.DocstoreFn¶
class langchain_community.docstore.arbitrary_fn.DocstoreFn(lookup_fn: Callable[[str], Union[Document, str]])[source]¶
Langchain Docstore via arbitrary lookup function.
This is useful when:
it’s expensive to construct an InMemoryDocstore/dict
you retrieve documents from remote sources
you just want to reuse existing objects
Methods
__init__(lookup_fn)
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Search for a document.
__init__(lookup_fn: Callable[[str], Union[Document, str]])[source]¶
delete(ids: List) → None¶
Deleting IDs from in memory dictionary.
search(search: str) → Document[source]¶
Search for a document.
Parameters
search – search string
Returns
Document if found, else error message.
langchain_community.docstore.base.Docstore¶
class langchain_community.docstore.base.Docstore[source]¶
Interface to access to place that stores documents.
Methods
__init__()
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Search for document.
__init__()¶
delete(ids: List) → None[source]¶
Deleting IDs from in memory dictionary.
abstract search(search: str) → Union[str, Document][source]¶
Search for document.
If page exists, return the page summary, and a Document object.
If page does not exist, return similar entries.
langchain_community.docstore.in_memory.InMemoryDocstore¶
class langchain_community.docstore.in_memory.InMemoryDocstore(_dict: Optional[Dict[str, Document]] = None)[source]¶
Simple in memory docstore in the form of a dict.
Initialize with dict.
Methods
__init__([_dict])
Initialize with dict.
add(texts)
Add texts to in memory dictionary.
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Search via direct lookup.
__init__(_dict: Optional[Dict[str, Document]] = None)[source]¶
Initialize with dict.
add(texts: Dict[str, Document]) → None[source]¶
Add texts to in memory dictionary.
Parameters
texts – dictionary of id -> document.
Returns
None
delete(ids: List) → None[source]¶
Deleting IDs from in memory dictionary.
search(search: str) → Union[str, Document][source]¶
Search via direct lookup.
Parameters
search – id of a document to search for.
Returns
Document if found, else error message.
Examples using InMemoryDocstore¶
Annoy
Agents
AutoGPT
BabyAGI User Guide
BabyAGI with Tools
!pip install bs4
Generative Agents in LangChain
langchain_community.docstore.wikipedia.Wikipedia¶
class langchain_community.docstore.wikipedia.Wikipedia[source]¶
Wrapper around wikipedia API.
Check that wikipedia package is installed.
Methods
__init__()
Check that wikipedia package is installed.
delete(ids)
Deleting IDs from in memory dictionary.
search(search)
Try to search for wiki page.
__init__() → None[source]¶
Check that wikipedia package is installed.
delete(ids: List) → None¶
Deleting IDs from in memory dictionary.
search(search: str) → Union[str, Document][source]¶
Try to search for wiki page.
If page exists, return the page summary, and a PageWithLookups object.
If page does not exist, return similar entries.
Parameters
search – search string.
Returns: a Document object or error message.
langchain_core.chat_history.BaseChatMessageHistory¶
class langchain_core.chat_history.BaseChatMessageHistory[source]¶
Abstract base class for storing chat message history.
See ChatMessageHistory for default implementation.
Example
class FileChatMessageHistory(BaseChatMessageHistory):
    storage_path:  str
    session_id: str
   @property
   def messages(self):
       with open(os.path.join(storage_path, session_id), 'r:utf-8') as f:
           messages = json.loads(f.read())
        return messages_from_dict(messages)
   def add_message(self, message: BaseMessage) -> None:
       messages = self.messages.append(_message_to_dict(message))
       with open(os.path.join(storage_path, session_id), 'w') as f:
           json.dump(f, messages)
   def clear(self):
       with open(os.path.join(storage_path, session_id), 'w') as f:
           f.write("[]")
Attributes
messages
A list of Messages stored in-memory.
Methods
__init__()
add_ai_message(message)
Convenience method for adding an AI message string to the store.
add_message(message)
Add a Message object to the store.
add_user_message(message)
Convenience method for adding a human message string to the store.
clear()
Remove all messages from the store
__init__()¶
add_ai_message(message: str) → None[source]¶
Convenience method for adding an AI message string to the store.
Parameters
message – The string contents of an AI message.
abstract add_message(message: BaseMessage) → None[source]¶
Add a Message object to the store.
Parameters
message – A BaseMessage object to store.
add_user_message(message: str) → None[source]¶
Convenience method for adding a human message string to the store.
Parameters
langchain_core.exceptions.OutputParserException¶
class langchain_core.exceptions.OutputParserException(error: Any, observation: Optional[str] = None, llm_output: Optional[str] = None, send_to_llm: bool = False)[source]¶
Exception that output parsers should raise to signify a parsing error.
This exists to differentiate parsing errors from other code or execution errors
that also may arise inside the output parser. OutputParserExceptions will be
available to catch and handle in ways to fix the parsing error, while other
errors will be raised.
Parameters
error – The error that’s being re-raised or an error message.
observation – String explanation of error which can be passed to a
model to try and remediate the issue.
llm_output – String model output which is error-ing.
send_to_llm – Whether to send the observation and llm_output back to an Agent
after an OutputParserException has been raised. This gives the underlying
model driving the agent the context that the previous output was improperly
structured, in the hopes that it will update the output to the correct
format.
langchain_core.beta.runnables.context.PrefixContext¶
class langchain_core.beta.runnables.context.PrefixContext(prefix: str = '')[source]¶
Attributes
prefix
Methods
__init__([prefix])
getter(key, /)
setter([_key, _value])
__init__(prefix: str = '')[source]¶
getter(key: Union[str, List[str]], /) → ContextGet[source]¶
setter(_key: Optional[str] = None, _value: Optional[Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Any]] = None, /, **kwargs: Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Any]) → ContextSet[source]¶
langchain_core.beta.runnables.context.Context¶
class langchain_core.beta.runnables.context.Context[source]¶
Methods
__init__()
create_scope(scope, /)
getter(key, /)
setter([_key, _value])
__init__()¶
static create_scope(scope: str, /) → PrefixContext[source]¶
static getter(key: Union[str, List[str]], /) → ContextGet[source]¶
static setter(_key: Optional[str] = None, _value: Optional[Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Any]] = None, /, **kwargs: Union[Runnable[Input, Output], Callable[[Input], Output], Callable[[Input], Awaitable[Output]], Any]) → ContextSet[source]¶
langchain_core.beta.runnables.context.ContextSet¶
class langchain_core.beta.runnables.context.ContextSet[source]¶
Bases: RunnableSerializable
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param keys: Mapping[str, Optional[langchain_core.runnables.base.Runnable]] [Required]¶
param prefix: str = ''¶
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
async ainvoke(input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any) → Any[source]¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code even if
the runnable did not implement a native async version of invoke.
Subclasses should override this method if they can run asynchronously.
async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
This method allows to get an input schema for a specific configuration.
Parameters
config – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
classmethod get_lc_namespace() → List[str]¶
Get the namespace of the langchain object.
For example, if the class is langchain.llms.openai.OpenAI, then the
namespace is [“langchain”, “llms”, “openai”]
get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Get a pydantic model that can be used to validate output to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic output schema that depends on which
configuration the runnable is invoked with.
This method allows to get an output schema for a specific configuration.
Parameters
config – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
invoke(input: Any, config: Optional[RunnableConfig] = None) → Any[source]¶
Transform a single input into an output. Override to implement.
Parameters
input – The input to the runnable.
config – A config to use when invoking the runnable.
The config supports standard keys like ‘tags’, ‘metadata’ for tracing
purposes, ‘max_concurrency’ for controlling how much work to do
in parallel, and other keys. Please refer to the RunnableConfig
for more details.
Returns
The output of the runnable.
classmethod is_lc_serializable() → bool¶
Is this class serializable?
property OutputType: Type[langchain_core.runnables.utils.Output]¶
The type of output this runnable produces specified as a type annotation.
property config_specs: List[langchain_core.runnables.utils.ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property ids: List[str]¶
property input_schema: Type[pydantic.main.BaseModel]¶
The type of input this runnable accepts specified as a pydantic model.
property lc_attributes: Dict¶
List of attribute names that should be included in the serialized kwargs.
These attributes must be accepted by the constructor.
property lc_secrets: Dict[str, str]¶
A map of constructor argument names to secret ids.
For example,{“openai_api_key”: “OPENAI_API_KEY”}
property output_schema: Type[pydantic.main.BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
langchain_core.beta.runnables.context.ContextGet¶
class langchain_core.beta.runnables.context.ContextGet[source]¶
Bases: RunnableSerializable
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param key: Union[str, List[str]] [Required]¶
param prefix: str = ''¶
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Default implementation runs ainvoke in parallel using asyncio.gather.
The default implementation of batch works well for IO bound runnables.
Subclasses should override this method if they can batch more efficiently;
e.g., if the underlying runnable uses an API which supports a batch mode.
async ainvoke(input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any) → Any[source]¶
Default implementation of ainvoke, calls invoke from a thread.
The default implementation allows usage of async code even if
the runnable did not implement a native async version of invoke.
Subclasses should override this method if they can run asynchronously.
async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶
Default implementation of astream, which calls ainvoke.
Subclasses should override this method if they support streaming output.
langchain_core.documents.base.Document¶
class langchain_core.documents.base.Document[source]¶
Bases: Serializable
Class for storing a piece of text and associated metadata.
Create a new model by parsing and validating input data from keyword arguments.
Raises ValidationError if the input data cannot be parsed to form a valid model.
param metadata: dict [Optional]¶
Arbitrary metadata about the page content (e.g., source, relationships to other
documents, etc.).
param page_content: str [Required]¶
String text.
param type: Literal['Document'] = 'Document'¶
classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶
Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶
Duplicate a model, optionally choose which fields to include, exclude and change.
Parameters
include – fields to include in new model
exclude – fields to exclude from new model, as with values this takes precedence over include
update – values to change/add in the new model. Note: the data is not validated before creating
the new model: you should trust this data
deep – set to True to make a deep copy of the model
Returns
new model instance
deep – set to True to make a deep copy of the model
Returns
new model instance
dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
classmethod from_orm(obj: Any) → Model¶
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
classmethod is_lc_serializable() → bool[source]¶
Return whether this class is serializable.
json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶
Generate a JSON representation of the model, include and exclude arguments as per dict().
encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().
classmethod lc_id() → List[str]¶
A unique identifier for this class for serialization purposes.
The unique identifier is a list of strings that describes the path
to the object.