Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#https://python.langchain.com/docs/how_to/functions/
|
2 |
+
import gradio as gr
|
3 |
+
from langchain_openai import ChatOpenAI
|
4 |
+
from langchain_core.prompts import ChatPromptTemplate
|
5 |
+
from langchain_core.runnables import RunnableLambda
|
6 |
+
|
7 |
+
def word_counter(text):
|
8 |
+
return len(text.split())
|
9 |
+
|
10 |
+
def process_with_function(text, api_key):
|
11 |
+
try:
|
12 |
+
# Initialize the model
|
13 |
+
model = ChatOpenAI(
|
14 |
+
openai_api_key=api_key,
|
15 |
+
model="gpt-3.5-turbo"
|
16 |
+
)
|
17 |
+
|
18 |
+
# Create prompt template
|
19 |
+
prompt = ChatPromptTemplate.from_template("Write a short story about {topic}")
|
20 |
+
|
21 |
+
# Create chain with custom function
|
22 |
+
chain = (
|
23 |
+
prompt
|
24 |
+
| model
|
25 |
+
| RunnableLambda(lambda x: {
|
26 |
+
"story": x.content,
|
27 |
+
"word_count": word_counter(x.content)
|
28 |
+
})
|
29 |
+
)
|
30 |
+
|
31 |
+
# Get result
|
32 |
+
result = chain.invoke({"topic": text})
|
33 |
+
|
34 |
+
return f"""
|
35 |
+
Story: {result['story']}
|
36 |
+
|
37 |
+
Word Count: {result['word_count']} words
|
38 |
+
"""
|
39 |
+
|
40 |
+
except Exception as e:
|
41 |
+
return f"Error: {str(e)}"
|
42 |
+
|
43 |
+
# Create Gradio interface
|
44 |
+
demo = gr.Interface(
|
45 |
+
fn=process_with_function,
|
46 |
+
inputs=[
|
47 |
+
gr.Textbox(label="Story Topic", placeholder="Enter a topic..."),
|
48 |
+
gr.Textbox(label="OpenAI API Key", type="password")
|
49 |
+
],
|
50 |
+
outputs=gr.Textbox(label="Story with Analysis", lines=8),
|
51 |
+
title="LangChain Functions Demo",
|
52 |
+
description="Generates a story and counts its words using RunnableLambda"
|
53 |
+
)
|
54 |
+
|
55 |
+
if __name__ == "__main__":
|
56 |
+
demo.launch()
|