|
|
|
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: |
|
|
|
model = ChatOpenAI( |
|
openai_api_key=api_key, |
|
model="gpt-4o-mini" |
|
) |
|
|
|
|
|
prompt = ChatPromptTemplate.from_template( |
|
"Write a story about {text}. Make it detailed." |
|
) |
|
|
|
|
|
chain = prompt | model.bind(stop=stop_word) |
|
|
|
|
|
response = chain.invoke({"text": text}) |
|
|
|
return response.content |
|
|
|
except Exception as e: |
|
return f"Error: {str(e)}" |
|
|
|
|
|
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() |
|
|