🦜️🔗LangChain : モジュール : モデル I/O – 言語モデル : LLM : 非同期 API / カスタム LLM / フェイク LLM (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 08/24/2023
* 本ページは、LangChain の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Modules : Model I/O : Language models : Async API
- Modules : Model I/O : Language models : Custom LLM
- Modules : Model I/O : Language models : Fake LLM
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
🦜️🔗 LangChain : モジュール : モデル I/O – 言語モデル : LLM : 非同期 API
非同期 API
LangChain は asyncio ライブラリを活用して LLM の非同期サポートを提供します。
非同期サポートは複数の LLM を同時に呼び出すために特に有用です、これらの呼び出しはネットワークに依存している (network-bound) からです。現在、OpenAI, PromptLayerOpenAI, ChatOpenAI, Anthropic と Cohere がサポートされていますが、他の LLM 用の非同期サポートはロードマップ上にあります。
OpenAI LLM を非同期に呼び出すために agenerate メソッドを使用できます。
import time
import asyncio
from langchain.llms import OpenAI
def generate_serially():
llm = OpenAI(temperature=0.9)
for _ in range(10):
resp = llm.generate(["Hello, how are you?"])
print(resp.generations[0][0].text)
async def async_generate(llm):
resp = await llm.agenerate(["Hello, how are you?"])
print(resp.generations[0][0].text)
async def generate_concurrently():
llm = OpenAI(temperature=0.9)
tasks = [async_generate(llm) for _ in range(10)]
await asyncio.gather(*tasks)
s = time.perf_counter()
# If running this outside of Jupyter, use asyncio.run(generate_concurrently())
await generate_concurrently()
elapsed = time.perf_counter() - s
print("\033[1m" + f"Concurrent executed in {elapsed:0.2f} seconds." + "\033[0m")
s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print("\033[1m" + f"Serial executed in {elapsed:0.2f} seconds." + "\033[0m")
API リファレンス
- OpenAI from langchain.llms
I'm doing well, thank you. How about you? I'm doing well, thank you. How about you? I'm doing well, how about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about yourself? I'm doing well, thank you! How about you? I'm doing well, thank you. How about you? I'm doing well, thank you! How about you? I'm doing well, thank you. How about you? Concurrent executed in 1.39 seconds. I'm doing well, thank you. How about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about yourself? I'm doing well, thanks for asking. How about you? I'm doing well, thanks! How about you? I'm doing well, thank you. How about you? I'm doing well, thank you. How about yourself? I'm doing well, thanks for asking. How about you? Serial executed in 5.77 seconds.
🦜️🔗 LangChain : モジュール : モデル I/O – 言語モデル : LLM : カスタム LLM
カスタム LLM
このノートブックは、貴方自身の LLM や LangChain でサポートされるものとは別のラッパーを使用したい場合に、カスタム LLM ラッパーを作成する方法を調べます。
カスタム LLM が実装する必要がある一つだけの必須のものがあります :
- 文字列、オプションで幾つかの停止単語 (stop words) を受け取り、文字列を返す _call メソッド。
実装できる 2 つめのオプションがあります :
- _identifying_params プロパティ、これはこのクラスのプリンティングを支援するために使用されます。辞書を返す必要があります。
入力の最初の N 文字を返すだけの非常に単純なカスタム LLM を実装しましょう。
from typing import Any, List, Mapping, Optional
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
API リファレンス :
- CallbackManagerForLLMRun from langchain.callbacks.manager
- LLM from langchain.llms.base
class CustomLLM(LLM):
n: int
@property
def _llm_type(self) -> str:
return "custom"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
if stop is not None:
raise ValueError("stop kwargs are not permitted.")
return prompt[: self.n]
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {"n": self.n}
これでこれを任意の他の LMM として使用できます。
llm = CustomLLM(n=10)
llm("This is a foobar thing")
'This is a '
LLM をプリントしてそのカスタムプリントを確認することもできます。
print(llm)
CustomLLM Params: {'n': 10}
🦜️🔗 LangChain : モジュール : モデル I/O – 言語モデル : LLM : フェイク LLM
フェイク LLM
テストのために使用できる fake LLM クラスを公開しています。これは LLM への呼び出しを模造し (mock out) LLM が特定の方法で応答する場合何が起きるかをシミュレートすることを可能にします。
このノートブックではこれの使用方法を調べます。
FakeLLM をエージェントで使用してこれを始めます。
from langchain.llms.fake import FakeListLLM
API リファレンス :
- FakeListLLM from langchain.llms.fake
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
API リファレンス :
- load_tools from langchain.agents
- initialize_agent from langchain.agents
- AgentType from langchain.agents
tools = load_tools(["python_repl"])
responses = ["Action: Python REPL\nAction Input: print(2 + 2)", "Final Answer: 4"]
llm = FakeListLLM(responses=responses)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run("whats 2 + 2")
> Entering new AgentExecutor chain... Action: Python REPL Action Input: print(2 + 2) Observation: 4 Thought:Final Answer: 4 > Finished chain. '4'
以上