How to make the new variables input available via query method? #394
Replies: 6 comments 12 replies
-
HI @xiechengmude, This is mostly an LCEL issue. To debug break things into smaller chunks and inspect the input and output schemas of your chains. Try to follow the examples here and modify them: Check how |
Beta Was this translation helpful? Give feedback.
-
Here's a self contained example: import re
from pathlib import Path
from typing import Callable, Union
import uvicorn
from fastapi import FastAPI, HTTPException
from langchain.chat_models import ChatOpenAI
from langchain.memory import FileChatMessageHistory
from langchain.prompts import PromptTemplate
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langserve import add_routes
def _is_valid_identifier(value: str) -> bool:
"""Check if the session ID is in a valid format."""
# Use a regular expression to match the allowed characters
valid_characters = re.compile(r"^[a-zA-Z0-9-_]+$")
return bool(valid_characters.match(value))
def create_session_factory(
base_dir: Union[str, Path],
) -> Callable[[str], BaseChatMessageHistory]:
"""Create a session ID factory that creates session IDs from a base dir.
Args:
base_dir: Base directory to use for storing the chat histories.
Returns:
A session ID factory that creates session IDs from a base path.
"""
base_dir_ = Path(base_dir) if isinstance(base_dir, str) else base_dir
if not base_dir_.exists():
base_dir_.mkdir(parents=True)
def get_chat_history(session_id: str) -> FileChatMessageHistory:
"""Get a chat history from a session ID."""
if not _is_valid_identifier(session_id):
raise HTTPException(
status_code=400,
detail=f"Session ID `{session_id}` is not in a valid format. "
"Session ID must only contain alphanumeric characters, "
"hyphens, and underscores.",
)
file_path = base_dir_ / f"{session_id}.json"
return FileChatMessageHistory(str(file_path))
return get_chat_history
llm = ChatOpenAI()
prompt = ChatPromptTemplate.from_messages([
("system", "You're an assistant. Answer the question to the best of your ability "
"based on the conversation, the lesson {lesson} and the affection number {affection}."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
])
app = FastAPI()
chain = prompt | llm
chain_with_history = RunnableWithMessageHistory(
chain,
create_session_factory("./chats"),
input_messages_key="question",
history_messages_key="history",
verbose=True,
)
chain.invoke(
{
"lesson": "Math Lesson",
"affection": 66,
"question": "what's the important to learn math well?",
'history': []
},
)
chain_with_history.invoke(
{
"lesson": "Math Lesson",
"affection": 66,
"question": "what's the important to learn math well?",
},
{
'configurable': {
'session_id': 'some_random_id3',
}
}
) |
Beta Was this translation helpful? Give feedback.
-
hanks for your detailed reply.
|
Beta Was this translation helpful? Give feedback.
-
Could you show me the right way to query ? |
Beta Was this translation helpful? Give feedback.
-
Invoke code work, but the curl type is not. why? |
Beta Was this translation helpful? Give feedback.
-
Alright, thats the whole thing I need.
|
Beta Was this translation helpful? Give feedback.
-
Question:
If I create the new varialbels: input_variables=["history", "input","lession", "affection"],
and setting like the below code.
I cant make the right query via the swagger docs from langserve. Whats the problem here?
Thank you !
Beta Was this translation helpful? Give feedback.
All reactions