Fake LLM#

This fake LLM can be useful for mocking LLM calls during testing. It’s extended from langchain’s own FakeLLM, but that one is not available for use outside of the langchain project.

[1]:
from langchain_contrib.llms.testing import FakeLLM

llm = FakeLLM()
llm("Dummy prompt")
[1]:
'foo'

Custom responses#

You can specify custom responses for exact prompt matches by specifying mapped_responses:

[2]:
llm = FakeLLM(mapped_responses={"Exact prompt": "Custom response"})
llm("Exact prompt")
[2]:
'Custom response'
[3]:
llm("A different prompt")
[3]:
'foo'

In practice, prompts can get really complicated really fast. As such, you can also specify responses to simply be returned in order by specifying sequenced_responses instead:

[4]:
llm = FakeLLM(sequenced_responses=["One", "Two", "Three"])
llm("Count")
[4]:
'One'
[5]:
llm("Count")
[5]:
'Two'
[6]:
llm("Count")
[6]:
'Three'
[7]:
llm("Count")
[7]:
'foo'

Enforcing stops#

If you want to make sure your stop logic is working properly, you can also test for that by setting check_stops to True. This will now raise if you forgot to call the LLM with a stop:

[8]:
llm = FakeLLM(check_stops=True, mapped_responses={"Can't stop": "Won't stop."})
try:
    llm("Can't stop")
except AssertionError as e:
    print(e)
Stop has not been set

This will also raise if you call the LLM with the wrong stop.

[9]:
try:
    llm("Can't stop", stop=["!"])
except AssertionError as e:
    print(e)
Output 'Won't stop.' does not end in ['!']

You will need to call the LLM with the right stop for the right response to be returned.

[10]:
llm("Can't stop", stop=["."])
[10]:
"Won't stop"