Tony20100/langchain_full huggingface dataset:
langchain_community.chat_models.coze.ChatCoze¶
class langchain_community.chat_models.coze.ChatCoze[source]¶
Bases: BaseChatModel
ChatCoze chat models API by coze.com
For more information, see https://www.coze.com/open/docs/chat
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 bot_id: str = ''¶
The ID of the bot that the API interacts with.
param cache: Union[BaseCache, bool, None] = None¶
Whether to cache the response.
If true, will use the global cache.
If false, will not use a cache
If None, will use the global cache if it’s set, otherwise no cache.
If instance of BaseCache, will use the provided cache.
Caching is not currently supported for streaming methods of models.
param callback_manager: Optional[BaseCallbackManager] = None¶
[DEPRECATED] Callback manager to add to the run trace.
param callbacks: Callbacks = None¶
Callbacks to add to the run trace.
param conversation_id: str = ''¶
Indicate which conversation the dialog is taking place in. If there is no need to
distinguish the context of the conversation(just a question and answer), skip this
parameter. It will be generated by the system.
param coze_api_base: str = 'https://api.coze.com'¶
Coze custom endpoints
param coze_api_key: Optional[SecretStr] = None¶
Coze API Key
Constraints
type = string
writeOnly = True
format = password
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param metadata: Optional[Dict[str, Any]] = None¶
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param request_timeout: int = 60 (alias 'timeout')¶
request timeout for chat http requests
param streaming: bool = False¶
Whether to stream the response to the client.
false: if no value is specified or set to false, a non-streaming response is
returned. “Non-streaming response” means that all responses will be returned at once
after they are all ready, and the client does not need to concatenate the content.
true: set to true, partial message deltas will be sent .
“Streaming response” will provide real-time response of the model to the client, and
the client needs to assemble the final reply based on the type of message.
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param user: str = ''¶
The user who calls the API to chat with the bot.
param verbose: bool [Optional]¶
Whether to print out response text.
__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → BaseMessage¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
messages (List[BaseMessage]) – 
stop (Optional[List[str]]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
BaseMessage
async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶
Not implemented on this class.
Parameters
schema (Union[Dict, Type[BaseModel]]) – 
kwargs (Any) – 
Return type
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, BaseModel]]
with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶
Bind input and output types to a Runnable, returning a new Runnable.
Parameters
input_type (Optional[Type[Input]]) – 
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: TypeAlias¶
Get the input type for this runnable.
property OutputType: Any¶
Get the output type for this runnable.
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[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 lc_serializable: bool¶
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
Examples using ChatCoze¶
Chat with Coze Bot
langchain_upstage.chat_models.ChatUpstage¶
class langchain_upstage.chat_models.ChatUpstage[source]¶
Bases: BaseChatOpenAI
ChatUpstage chat model.
To use, you should have the environment variable UPSTAGE_API_KEY
set with your API key or pass it as a named parameter to the constructor.
Example
from langchain_upstage import ChatUpstage
model = ChatUpstage()
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 cache: Union[BaseCache, bool, None] = None¶
Whether to cache the response.
If true, will use the global cache.
If false, will not use a cache
If None, will use the global cache if it’s set, otherwise no cache.
If instance of BaseCache, will use the provided cache.
Caching is not currently supported for streaming methods of models.
param callback_manager: Optional[BaseCallbackManager] = None¶
[DEPRECATED] Callback manager to add to the run trace.
param callbacks: Callbacks = None¶
Callbacks to add to the run trace.
param custom_get_token_ids: Optional[Callable[[str], List[int]]] = None¶
Optional encoder to use for counting tokens.
param default_headers: Union[Mapping[str, str], None] = None¶
param default_query: Union[Mapping[str, object], None] = None¶
param http_async_client: Union[Any, None] = None¶
Optional httpx.AsyncClient. Only used for async invocations. Must specify
http_client as well if you’d like a custom client for sync invocations.
param http_client: Union[Any, None] = None¶
Optional httpx.Client. Only used for sync invocations. Must specify
Optional httpx.Client. Only used for sync invocations. Must specify
http_async_client as well if you’d like a custom client for async invocations.
param max_retries: int = 2¶
Maximum number of retries to make when generating.
param max_tokens: Optional[int] = None¶
Maximum number of tokens to generate.
param metadata: Optional[Dict[str, Any]] = None¶
Metadata to add to the run trace.
param model_kwargs: Dict[str, Any] [Optional]¶
Holds any model parameters valid for create call not explicitly specified.
param model_name: str = 'solar-1-mini-chat' (alias 'model')¶
Model name to use.
param n: int = 1¶
Number of chat completions to generate for each prompt.
param openai_api_base: Optional[str] = None¶
openai api base is not supported for upstage. use upstage_api_base instead.
param openai_api_key: Optional[SecretStr] = None¶
openai api key is not supported for upstage. use upstage_api_key instead.
Constraints
type = string
writeOnly = True
format = password
param openai_organization: Optional[str] = None¶
openai organization is not supported for upstage.
param openai_proxy: Optional[str] = None¶
param request_timeout: Union[float, Tuple[float, float], Any, None] = None (alias 'timeout')¶
Timeout for requests to OpenAI completion API. Can be float, httpx.Timeout or
None.
param streaming: bool = False¶
Whether to stream the results or not.
param tags: Optional[List[str]] = None¶
Tags to add to the run trace.
param temperature: float = 0.7¶
What sampling temperature to use.
param temperature: float = 0.7¶
What sampling temperature to use.
param tiktoken_model_name: Optional[str] = None¶
tiktoken is not supported for upstage.
param upstage_api_base: Optional[str] = 'https://api.upstage.ai/v1/solar' (alias 'base_url')¶
Base URL path for API requests, leave blank if not using a proxy or service
emulator.
param upstage_api_key: Optional[SecretStr] = None (alias 'api_key')¶
Automatically inferred from env are UPSTAGE_API_KEY if not provided.
Constraints
type = string
writeOnly = True
format = password
param verbose: bool [Optional]¶
Whether to print out response text.
__call__(messages: List[BaseMessage], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → BaseMessage¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
messages (List[BaseMessage]) – 
stop (Optional[List[str]]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
BaseMessage
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.
Parameters
e.g., if the underlying runnable uses an API which supports a batch mode.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
async agenerate(messages: List[List[BaseMessage]], stop: Optional[List[str]] = None, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, run_id: Optional[UUID] = None, **kwargs: Any) → LLMResult¶
Asynchronously pass a sequence of prompts to a model and return generations.
This method should make use of batched calls for models that expose a batched
API.
Use this method when you want to:
take advantage of batched calls,
need more output from the model than just the top generated value,
are building chains that are agnostic to the underlying language modeltype (e.g., pure text completion models vs chat models).
Parameters
Parameters
kwargs (Any) – 
Return type
Runnable[Input, Output]
bind_functions(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]], function_call: Optional[Union[_FunctionCall, str, Literal['auto', 'none']]] = None, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]¶
Bind functions (and other objects) to this chat model.
Assumes model is compatible with OpenAI function-calling API.
NOTE: Using bind_tools is recommended instead, as the functions andfunction_call request parameters are officially marked as deprecated by
OpenAI.
Parameters
functions (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]) – A list of function definitions to bind to this chat model.
Can be  a dictionary, pydantic model, or callable. Pydantic
models and callables will be automatically converted to
their schema dictionary representation.
function_call (Optional[Union[_FunctionCall, str, Literal['auto', 'none']]]) – Which function to require the model to call.
Must be the name of the single provided function or
“auto” to automatically determine which function to call
(if any).
**kwargs (Any) – Any additional parameters to pass to the
Runnable constructor.
Return type
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]
bind_tools(tools: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]], *, tool_choice: Optional[Union[dict, str, Literal['auto', 'none', 'required', 'any'], bool]] = None, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]¶
Bind tool-like objects to this chat model.
Assumes model is compatible with OpenAI tool-calling API.
Parameters
tools (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable, BaseTool]]) – A list of tool definitions to bind to this chat model.
Can be  a dictionary, pydantic model, callable, or BaseTool. Pydantic
models, callables, and BaseTools will be automatically converted to
their schema dictionary representation.
tool_choice (Optional[Union[dict, str, Literal['auto', 'none', 'required', 'any'], bool]]) – Which tool to require the model to call.
Options are:
name of the tool (str): calls corresponding tool;
“auto”: automatically selects a tool (including no tool);
“none”: does not call a tool;
“any” or “required”: force at least one tool to be called;
True: forces tool call (requires tools be length 1);
False: no effect;
or a dict of the form:
{“type”: “function”, “function”: {“name”: <<tool_name>>}}.
**kwargs (Any) – Any additional parameters to pass to the
Runnable constructor.
Return type
Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], BaseMessage]
call_as_llm(message: str, stop: Optional[List[str]] = None, **kwargs: Any) → str¶
[Deprecated]
Notes
Deprecated since version langchain-core==0.1.7: Use invoke instead.
Parameters
message (str) – 
stop (Optional[List[str]]) – 
kwargs (Any) – 
Return type
str
config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶
The type of config this runnable accepts specified as a pydantic model.
To mark a field as configurable, see the configurable_fields
and configurable_alternatives methods.
Parameters
include (Optional[Sequence[str]]) – A list of fields to include in the config schema.
Returns
A pydantic model that can be used to validate config.
Return type
Type[BaseModel]
configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶
Configure alternatives for runnables that can be set at runtime.
from langchain_anthropic import ChatAnthropic
from langchain_core.runnables.utils import ConfigurableField
from langchain_openai import ChatOpenAI
model = ChatAnthropic(
    model_name="claude-3-sonnet-20240229"
).configurable_alternatives(
    ConfigurableField(id="llm"),
    default_key="anthropic",
    openai=ChatOpenAI()
)
# uses the default model ChatAnthropic
print(model.invoke("which organization created you?").content)
# uses ChatOpenAI
print(
    model.with_config(
        configurable={"llm": "openai"}
Get a pydantic model that can be used to validate input to the runnable.
Runnables that leverage the configurable_fields and configurable_alternatives
methods will have a dynamic input schema that depends on which
configuration the runnable is invoked with.
This method allows to get an input schema for a specific configuration.
Parameters
config (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
classmethod get_lc_namespace() → List[str][source]¶
Get the namespace of the langchain object.
For example, if the class is langchain.llms.openai.OpenAI, then the
namespace is [“langchain”, “llms”, “openai”]
Return type
List[str]
get_name(suffix: Optional[str] = None, *, name: Optional[str] = None) → str¶
Get the name of the runnable.
Parameters
suffix (Optional[str]) – 
name (Optional[str]) – 
Return type
str
get_num_tokens(text: str) → int¶
Get the number of tokens present in the text.
Useful for checking if an input will fit in a model’s context window.
Parameters
text (str) – The string input to tokenize.
Returns
The integer number of tokens in the text.
Return type
int
get_num_tokens_from_messages(messages: List[BaseMessage]) → int¶
Calculate num tokens for gpt-3.5-turbo and gpt-4 with tiktoken package.
Official documentation: https://github.com/openai/openai-cookbook/blob/
main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
Parameters
messages (List[BaseMessage]) – 
Return type
int
Parameters
messages (List[BaseMessage]) – 
Return type
int
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 (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate output.
Return type
Type[BaseModel]
get_prompts(config: Optional[RunnableConfig] = None) → List[BasePromptTemplate]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
get_token_ids(text: str) → List[int]¶
Get the tokens present in the text with tiktoken package.
Parameters
text (str) – 
Return type
List[int]
invoke(input: LanguageModelInput, config: Optional[RunnableConfig] = None, *, stop: Optional[List[str]] = None, **kwargs: Any) → BaseMessage¶
Transform a single input into an output. Override to implement.
Parameters
input (LanguageModelInput) – The input to the runnable.
config (Optional[RunnableConfig]) – 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.
stop (Optional[List[str]]) – 
kwargs (Any) – 
Returns
The output of the runnable.
Return type
BaseMessage
Returns
The output of the runnable.
Return type
BaseMessage
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
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().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) – 
dumps_kwargs (Any) – 
Return type
unicode
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.
Return type
List[str]
map() → Runnable[List[Input], List[Output]]¶
Return a new Runnable that maps a list of inputs to a list of outputs,
by calling invoke() with each input.
Example
count = 0
def _lambda(x: int) -> None:
    global count
    count = count + 1
    if x == 1:
        raise ValueError("x is 1")
    else:
         pass
runnable = RunnableLambda(_lambda)
try:
    runnable.with_retry(
        stop_after_attempt=2,
        retry_if_exception_type=(ValueError,),
    ).invoke(1)
except ValueError:
    pass
assert (count == 2)
Parameters
retry_if_exception_type (Tuple[Type[BaseException], ...]) – A tuple of exception types to retry on
wait_exponential_jitter (bool) – Whether to add jitter to the wait time
between retries
stop_after_attempt (int) – The maximum number of attempts to make before giving up
Returns
A new Runnable that retries the original runnable on exceptions.
Return type
Runnable[Input, Output]
with_structured_output(schema: Optional[Union[Dict[str, Any], Type[_BM]]] = None, *, method: Literal['function_calling', 'json_mode'] = 'function_calling', include_raw: bool = False, **kwargs: Any) → Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[Dict, _BM]]¶
Model wrapper that returns outputs formatted to match the given schema.
Args:
schema: The output schema as a dict or a Pydantic class. If a Pydantic classthen the model output will be an object of that class. If a dict then
the model output will be a dict. With a Pydantic class the returned
attributes will be validated, whereas with a dict they will not be. If
attributes will be validated, whereas with a dict they will not be. If
method is “function_calling” and schema is a dict, then the dict
must match the OpenAI function-calling spec or be a valid JSON schema
with top level ‘title’ and ‘description’ keys specified.
method: The method for steering model generation, either “function_calling”or “json_mode”. If “function_calling” then the schema will be converted
to an OpenAI function and the returned model will make use of the
function-calling API. If “json_mode” then OpenAI’s JSON mode will be
used. Note that if using “json_mode” then you must include instructions
for formatting the output into the desired schema into the model call.
include_raw: If False then only the parsed structured output is returned. Ifan error occurs during model output parsing it will be raised. If True
then both the raw model response (a BaseMessage) and the parsed model
response will be returned. If an error occurs during output parsing it
will be caught and returned as well. The final output is always a dict
with keys “raw”, “parsed”, and “parsing_error”.
Returns:A Runnable that takes any ChatModel input and returns as output:
If include_raw is True then a dict with keys:raw: BaseMessage
parsed: Optional[_DictOrPydantic]
parsing_error: Optional[BaseException]
If include_raw is False then just _DictOrPydantic is returned,
where _DictOrPydantic depends on the schema:
If schema is a Pydantic class then _DictOrPydantic is the Pydanticclass.
If schema is a dict then _DictOrPydantic is a dict.
If schema is a dict then _DictOrPydantic is a dict.
Example: Function-calling, Pydantic schema (method=”function_calling”, include_raw=False):from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    '''An answer to the user question along with justification for the answer.'''
    answer: str
    justification: str
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = llm.with_structured_output(AnswerWithJustification)
structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
# -> AnswerWithJustification(
#     answer='They weigh the same',
#     justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'
# )
Example: Function-calling, Pydantic schema (method=”function_calling”, include_raw=True):from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel
class AnswerWithJustification(BaseModel):
    '''An answer to the user question along with justification for the answer.'''
    answer: str
    justification: str
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = llm.with_structured_output(AnswerWithJustification, include_raw=True)
structured_llm.invoke("What weighs more a pound of bricks or a pound of feathers")
# -> {