DexterSptizu's picture
Create app.py
ea967b2 verified
#https://python.langchain.com/docs/how_to/binding/
import gradio as gr
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
def process_with_binding(text, stop_word, api_key):
try:
# Initialize the model
model = ChatOpenAI(
openai_api_key=api_key,
model="gpt-4o-mini"
)
# Create prompt template
prompt = ChatPromptTemplate.from_template(
"Write a story about {text}. Make it detailed."
)
# Create chain with binding
chain = prompt | model.bind(stop=stop_word)
# Get response
response = chain.invoke({"text": text})
return response.content
except Exception as e:
return f"Error: {str(e)}"
# Create Gradio interface
demo = gr.Interface(
fn=process_with_binding,
inputs=[
gr.Textbox(label="Topic for story", placeholder="Enter a topic..."),
gr.Textbox(label="Stop Word", placeholder="Enter a word to stop generation"),
gr.Textbox(label="OpenAI API Key", type="password")
],
outputs=gr.Textbox(label="Generated Story"),
title="LangChain Binding Demo",
description="Generate a story that stops at a specific word"
)
if __name__ == "__main__":
demo.launch()