How do I type the return of a runnable? #28980
Replies: 1 comment 3 replies
-
Hi @avalatea! I'm here to help you with any bugs, questions, or contributions you have. Let me know how I can assist you. To type the return of a from typing import TypeVar, Generic, Dict
from langchain_core.runnables.base import Runnable
# Define type variables for input and output types
InputType = TypeVar('InputType')
OutputType = TypeVar('OutputType')
# Create a generic Runnable class with specified input and output types
class TypedRunnable(Runnable, Generic[InputType, OutputType]):
def __init__(self, input_type: InputType, output_type: OutputType):
self.input_type = input_type
self.output_type = output_type
def invoke(self, input_data: InputType) -> OutputType:
# Example implementation
return self.output_type
# Example function returning a TypedRunnable
def create_qa_chain(query: str) -> TypedRunnable[Dict[str, str], str]:
# Here, the input is a dictionary and the output is a string
return TypedRunnable(input_type={"question": query}, output_type="answer")
# Usage
qa_chain = create_qa_chain("What is the capital of France?")
result = qa_chain.invoke({"question": "What is the capital of France?"})
print(result) # Output: "answer" In this example, To continue talking to Dosu, mention @dosu. Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Other |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
A function can return a runnable. For example:
def create_qa_chain(query: str) -> Runnable
However, it is hard to tell what kind of runnable it is. Does it accept an int? A string? A dict? And what does it return? Runnable should work like the Callable typing. How do I do this? Give me an example (that I can run) to check that it works.
Beta Was this translation helpful? Give feedback.
All reactions