mirror of
https://github.com/hwchase17/langchain.git
synced 2025-04-27 11:41:51 +00:00
```python """python scripts/update_mypy_ruff.py""" import glob import tomllib from pathlib import Path import toml import subprocess import re ROOT_DIR = Path(__file__).parents[1] def main(): for path in glob.glob(str(ROOT_DIR / "libs/**/pyproject.toml"), recursive=True): print(path) with open(path, "rb") as f: pyproject = tomllib.load(f) try: pyproject["tool"]["poetry"]["group"]["typing"]["dependencies"]["mypy"] = ( "^1.10" ) pyproject["tool"]["poetry"]["group"]["lint"]["dependencies"]["ruff"] = ( "^0.5" ) except KeyError: continue with open(path, "w") as f: toml.dump(pyproject, f) cwd = "/".join(path.split("/")[:-1]) completed = subprocess.run( "poetry lock --no-update; poetry install --with typing; poetry run mypy . --no-color", cwd=cwd, shell=True, capture_output=True, text=True, ) logs = completed.stdout.split("\n") to_ignore = {} for l in logs: if re.match("^(.*)\:(\d+)\: error:.*\[(.*)\]", l): path, line_no, error_type = re.match( "^(.*)\:(\d+)\: error:.*\[(.*)\]", l ).groups() if (path, line_no) in to_ignore: to_ignore[(path, line_no)].append(error_type) else: to_ignore[(path, line_no)] = [error_type] print(len(to_ignore)) for (error_path, line_no), error_types in to_ignore.items(): all_errors = ", ".join(error_types) full_path = f"{cwd}/{error_path}" try: with open(full_path, "r") as f: file_lines = f.readlines() except FileNotFoundError: continue file_lines[int(line_no) - 1] = ( file_lines[int(line_no) - 1][:-1] + f" # type: ignore[{all_errors}]\n" ) with open(full_path, "w") as f: f.write("".join(file_lines)) subprocess.run( "poetry run ruff format .; poetry run ruff --select I --fix .", cwd=cwd, shell=True, capture_output=True, text=True, ) if __name__ == "__main__": main() ```
97 lines
3.2 KiB
Python
97 lines
3.2 KiB
Python
"""Utilities for chat loaders."""
|
|
|
|
from copy import deepcopy
|
|
from typing import Iterable, Iterator, List
|
|
|
|
from langchain_core.chat_sessions import ChatSession
|
|
from langchain_core.messages import AIMessage, BaseMessage
|
|
|
|
|
|
def merge_chat_runs_in_session(
|
|
chat_session: ChatSession, delimiter: str = "\n\n"
|
|
) -> ChatSession:
|
|
"""Merge chat runs together in a chat session.
|
|
|
|
A chat run is a sequence of messages from the same sender.
|
|
|
|
Args:
|
|
chat_session: A chat session.
|
|
|
|
Returns:
|
|
A chat session with merged chat runs.
|
|
"""
|
|
messages: List[BaseMessage] = []
|
|
for message in chat_session["messages"]:
|
|
if not isinstance(message.content, str):
|
|
raise ValueError(
|
|
"Chat Loaders only support messages with content type string, "
|
|
f"got {message.content}"
|
|
)
|
|
if not messages:
|
|
messages.append(deepcopy(message))
|
|
elif (
|
|
isinstance(message, type(messages[-1]))
|
|
and messages[-1].additional_kwargs.get("sender") is not None
|
|
and messages[-1].additional_kwargs["sender"]
|
|
== message.additional_kwargs.get("sender")
|
|
):
|
|
if not isinstance(messages[-1].content, str):
|
|
raise ValueError(
|
|
"Chat Loaders only support messages with content type string, "
|
|
f"got {messages[-1].content}"
|
|
)
|
|
messages[-1].content = (
|
|
messages[-1].content + delimiter + message.content
|
|
).strip()
|
|
messages[-1].additional_kwargs.get("events", []).extend(
|
|
message.additional_kwargs.get("events") or []
|
|
)
|
|
else:
|
|
messages.append(deepcopy(message))
|
|
return ChatSession(messages=messages)
|
|
|
|
|
|
def merge_chat_runs(chat_sessions: Iterable[ChatSession]) -> Iterator[ChatSession]:
|
|
"""Merge chat runs together.
|
|
|
|
A chat run is a sequence of messages from the same sender.
|
|
|
|
Args:
|
|
chat_sessions: A list of chat sessions.
|
|
|
|
Returns:
|
|
A list of chat sessions with merged chat runs.
|
|
"""
|
|
for chat_session in chat_sessions:
|
|
yield merge_chat_runs_in_session(chat_session)
|
|
|
|
|
|
def map_ai_messages_in_session(chat_sessions: ChatSession, sender: str) -> ChatSession:
|
|
"""Convert messages from the specified 'sender' to AI messages.
|
|
|
|
This is useful for fine-tuning the AI to adapt to your voice.
|
|
"""
|
|
messages = []
|
|
num_converted = 0
|
|
for message in chat_sessions["messages"]:
|
|
if message.additional_kwargs.get("sender") == sender:
|
|
message = AIMessage(
|
|
content=message.content,
|
|
additional_kwargs=message.additional_kwargs.copy(),
|
|
example=getattr(message, "example", None), # type: ignore[arg-type]
|
|
)
|
|
num_converted += 1
|
|
messages.append(message)
|
|
return ChatSession(messages=messages)
|
|
|
|
|
|
def map_ai_messages(
|
|
chat_sessions: Iterable[ChatSession], sender: str
|
|
) -> Iterator[ChatSession]:
|
|
"""Convert messages from the specified 'sender' to AI messages.
|
|
|
|
This is useful for fine-tuning the AI to adapt to your voice.
|
|
"""
|
|
for chat_session in chat_sessions:
|
|
yield map_ai_messages_in_session(chat_session, sender)
|