File size: 1,333 Bytes
ea967b2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
#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()
|