File size: 1,563 Bytes
2c44103 cac17d7 2c44103 |
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 46 47 48 49 50 51 52 53 54 55 56 57 |
#https://python.langchain.com/docs/how_to/functions/
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:
# Initialize the model
model = ChatOpenAI(
openai_api_key=api_key,
model="gpt-4o-mini"
)
# Create prompt template
prompt = ChatPromptTemplate.from_template("Write a short story about {topic}")
# Create chain with custom function
chain = (
prompt
| model
| RunnableLambda(lambda x: {
"story": x.content,
"word_count": word_counter(x.content)
})
)
# Get result
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)}"
# Create Gradio interface
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()
|