Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#https://python.langchain.com/docs/how_to/configure/
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from langchain_openai import ChatOpenAI
|
| 4 |
+
from langchain_core.prompts import PromptTemplate
|
| 5 |
+
from langchain_core.runnables import ConfigurableField
|
| 6 |
+
|
| 7 |
+
def process_with_config(topic, temperature, mode, api_key):
|
| 8 |
+
try:
|
| 9 |
+
# Initialize configurable model
|
| 10 |
+
model = ChatOpenAI(temperature=0).configurable_fields(
|
| 11 |
+
temperature=ConfigurableField(
|
| 12 |
+
id="llm_temperature",
|
| 13 |
+
name="LLM Temperature",
|
| 14 |
+
description="Temperature for response generation"
|
| 15 |
+
)
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Create configurable prompt
|
| 19 |
+
prompt = PromptTemplate.from_template(
|
| 20 |
+
"Tell me a {mode} about {topic}"
|
| 21 |
+
).configurable_alternatives(
|
| 22 |
+
ConfigurableField(id="prompt"),
|
| 23 |
+
default_key="joke",
|
| 24 |
+
poem=PromptTemplate.from_template("Write a poem about {topic}")
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Create chain
|
| 28 |
+
chain = prompt | model
|
| 29 |
+
|
| 30 |
+
# Configure and run
|
| 31 |
+
response = chain.with_config(
|
| 32 |
+
configurable={
|
| 33 |
+
"llm_temperature": float(temperature),
|
| 34 |
+
"prompt": mode
|
| 35 |
+
}
|
| 36 |
+
).invoke({"topic": topic})
|
| 37 |
+
|
| 38 |
+
return response.content
|
| 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_config,
|
| 46 |
+
inputs=[
|
| 47 |
+
gr.Textbox(label="Topic", placeholder="Enter a topic..."),
|
| 48 |
+
gr.Slider(0, 1, value=0.5, label="Temperature"),
|
| 49 |
+
gr.Radio(["joke", "poem"], label="Mode", value="joke"),
|
| 50 |
+
gr.Textbox(label="OpenAI API Key", type="password")
|
| 51 |
+
],
|
| 52 |
+
outputs=gr.Textbox(label="Generated Response"),
|
| 53 |
+
title="LangChain Configuration Demo",
|
| 54 |
+
description="Generate content with configurable temperature and mode"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
demo.launch()
|