|
|
|
import gradio as gr |
|
from langchain_openai import ChatOpenAI |
|
from langchain_core.prompts import ChatPromptTemplate |
|
from langchain_core.runnables import RunnableLambda |
|
|
|
def word_counter(text): |
|
return len(text.split()) |
|
|
|
def process_with_function(text, api_key): |
|
try: |
|
|
|
model = ChatOpenAI( |
|
openai_api_key=api_key, |
|
model="gpt-4o-mini" |
|
) |
|
|
|
|
|
prompt = ChatPromptTemplate.from_template("Write a short story about {topic}") |
|
|
|
|
|
chain = ( |
|
prompt |
|
| model |
|
| RunnableLambda(lambda x: { |
|
"story": x.content, |
|
"word_count": word_counter(x.content) |
|
}) |
|
) |
|
|
|
|
|
result = chain.invoke({"topic": text}) |
|
|
|
return f""" |
|
Story: {result['story']} |
|
|
|
Word Count: {result['word_count']} words |
|
""" |
|
|
|
except Exception as e: |
|
return f"Error: {str(e)}" |
|
|
|
|
|
demo = gr.Interface( |
|
fn=process_with_function, |
|
inputs=[ |
|
gr.Textbox(label="Story Topic", placeholder="Enter a topic..."), |
|
gr.Textbox(label="OpenAI API Key", type="password") |
|
], |
|
outputs=gr.Textbox(label="Story with Analysis", lines=8), |
|
title="LangChain Functions Demo", |
|
description="Generates a story and counts its words using RunnableLambda" |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|