1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LangChain WebBaseLoader の USER_AGENT 警告を消す方法

Last updated at Posted at 2024-06-23

LangChain WebBaseLoader を使ったら以下の警告が出ました。あくまでも警告なので基本的には実害ないのですが、気になってどうすべきかを調べ、考えました。

USER_AGENT environment variable not set, consider setting it to identify your requests.

結論

インポート前にUserAgentを設定する。

現象

環境

Python 3.12.2, langchain-community 0.2.5 を使っています。

警告出力箇所

インポートするだけで警告出ます。

from langchain_community.document_loaders import WebBaseLoader

影響

詳しく確認していませんが、サイトの中にはUserAgentの値で出力ページのハンドリングしているものもあると聞きます。そのため、未設定だと取得されるコンテンツが安定しない場合もあるかもしれません。

原因

まずは現象について。
web_base.py にあるget_user_agentを呼んで

web_base.py
default_header_template = {
    "User-Agent": get_user_agent(),
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*"
    ";q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Referer": "https://www.google.com/",
    "DNT": "1",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
}

user_agent.py で環境変数USER_AGENTから値を取得できなかった場合に警告を出力。

user_agent.py
def get_user_agent() -> str:
    """Get user agent from environment variable."""
    env_user_agent = os.environ.get("USER_AGENT")
    if not env_user_agent:
        log.warning(
            "USER_AGENT environment variable not set, "
            "consider setting it to identify your requests."
        )
        return "DefaultLangchainUserAgent"
    return env_user_agent

参考までにスタック情報。

Stack
File "/Users/Yohei/Documents/Applications/python/langchian-tutorial/.venv/lib/python3.12/site-packages/langchain_community/document_loaders/__init__.py", line 720, in __getattr__
    module = importlib.import_module(_module_lookup[name])
  File "/Users/Yohei/.pyenv/versions/3.12.2/lib/python3.12/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/Users/Yohei/Documents/Applications/python/langchian-tutorial/.venv/lib/python3.12/site-packages/langchain_community/document_loaders/web_base.py", line 18, in <module>
    "User-Agent": get_user_agent(),

対応

Python Package Install

fake_useragent をインストール。私が試したときはバージョン 1.5.1 でした。

コード

WebBaseLoaderをインポート前に環境変数に設定。一般的なChromにしておきます。これで警告出ません。あまり美しくありませんが。。。

import os

from fake_useragent import UserAgent

os.environ['USER_AGENT'] = UserAgent().chrome

from langchain_community.document_loaders import WebBaseLoader

あとは、python-dotenvなどを使って自動で環境変数に固定値を入れておいて、クラスのインスタンス化で正しい値を設定。こっちの方がコードはすっきりします。

from fake_useragent import UserAgent

WebBaseLoader(urls, header_template={
      'User-Agent': UserAgent().chrome,
        })
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?