dina1 commited on
Commit
6b09ebf
·
verified ·
1 Parent(s): 0dd9d34

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -49
app.py CHANGED
@@ -1,64 +1,116 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
 
 
59
  ],
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ # app.py
2
+ import os
3
+ from typing import Dict, TypedDict, Annotated, Sequence
4
  import gradio as gr
5
+ from langgraph.graph import END, StateGraph
6
+ from langchain_core.messages import AIMessage
7
+ import google.generativeai as genai
8
+ from langsmith import Client
9
+ from langchain_core.tracers.context import tracing_v2_enabled
10
 
11
+ # Configuration - use environment variables for secrets
12
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
13
+ LANGSMITH_API_KEY = os.getenv("LANGSMITH_API_KEY")
 
14
 
15
+ # Setting up APIs
16
+ if GEMINI_API_KEY:
17
+ genai.configure(api_key=GEMINI_API_KEY)
18
 
19
+ if LANGSMITH_API_KEY:
20
+ os.environ["LANGCHAIN_TRACING_V2"] = "true"
21
+ os.environ["LANGCHAIN_API_KEY"] = LANGSMITH_API_KEY
22
+ os.environ["LANGCHAIN_PROJECT"] = "Gemini-Multi-Agent-HF"
23
+ os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
24
+ client = Client()
 
 
 
25
 
26
+ # I use my free tier model
27
+ gemini_model = genai.GenerativeModel('gemini-1.5-flash')
 
 
 
28
 
29
+ class AgentState(TypedDict):
30
+ messages: Annotated[Sequence[AIMessage], lambda x, y: x + y]
31
+ user_query: str
32
 
33
+ def research_agent(state: AgentState) -> Dict:
34
+ user_query = state['user_query']
35
+ prompt = f"""You are a research assistant. Conduct research on: {user_query}
36
+ Provide:
37
+ - 3 key findings
38
+ - 2 reliable sources
39
+ - Potential applications
40
+ Keep response concise (1-2 paragraphs)."""
41
+
42
+ try:
43
+ response = gemini_model.generate_content(prompt)
44
+ return {"messages": [AIMessage(content=f"RESEARCH REPORT:\n{response.text}")]}
45
+ except Exception as e:
46
+ return {"messages": [AIMessage(content=f"Research failed: {str(e)}")]}
47
 
48
+ def writing_agent(state: AgentState) -> Dict:
49
+ messages = state['messages']
50
+ research_report = next(m.content for m in messages if "RESEARCH REPORT" in m.content)
51
+ prompt = f"""Write a short article (3 paragraphs max) about:
52
+ Topic: {state['user_query']}
53
+ Research: {research_report}
54
+ Include:
55
+ - Introduction
56
+ - Key points
57
+ - Conclusion"""
58
+
59
+ try:
60
+ response = gemini_model.generate_content(prompt)
61
+ return {"messages": [AIMessage(content=f"ARTICLE DRAFT:\n{response.text}")]}
62
+ except Exception as e:
63
+ return {"messages": [AIMessage(content=f"Writing failed: {str(e)}")]}
64
 
65
+ def editing_agent(state: AgentState) -> Dict:
66
+ draft = next(m.content for m in state['messages'] if "ARTICLE DRAFT" in m.content)
67
+ prompt = f"""Improve this draft (keep under 300 words):
68
+ {draft}
69
+ Make it:
70
+ - More engaging
71
+ - Better structured
72
+ - Easier to read"""
73
+
74
+ try:
75
+ response = gemini_model.generate_content(prompt)
76
+ return {"messages": [AIMessage(content=f"FINAL OUTPUT:\n{response.text}")]}
77
+ except Exception as e:
78
+ return {"messages": [AIMessage(content=f"Editing failed: {str(e)}")]}
79
 
80
+ def create_workflow():
81
+ workflow = StateGraph(AgentState)
82
+ workflow.add_node("researcher", research_agent)
83
+ workflow.add_node("writer", writing_agent)
84
+ workflow.add_node("editor", editing_agent)
85
+ workflow.add_edge("researcher", "writer")
86
+ workflow.add_edge("writer", "editor")
87
+ workflow.add_edge("editor", END)
88
+ workflow.set_entry_point("researcher")
89
+ return workflow.compile()
90
 
91
+ app = create_workflow()
92
+
93
+ def process_input(user_input):
94
+ try:
95
+ result = app.invoke({"messages": [], "user_query": user_input})
96
+ final_output = next(m.content for m in result['messages'] if "FINAL OUTPUT" in m.content)
97
+ return final_output.split("FINAL OUTPUT:")[1].strip()
98
+ except Exception as e:
99
+ return f"Error: {str(e)}"
100
+
101
+ demo = gr.Interface(
102
+ fn=process_input,
103
+ inputs=gr.Textbox(label="Your question", placeholder="Ask me anything..."),
104
+ outputs=gr.Textbox(label="Generated Article", lines=10),
105
+ title="🧠 AI Research Assistant",
106
+ description="A multi-agent system that researches topics and writes articles using Gemini 1.5 Flash",
107
+ examples=[
108
+ ["Explain quantum computing simply"],
109
+ ["What are the health benefits of meditation?"],
110
+ ["How do solar panels work?"]
111
  ],
112
+ allow_flagging="never"
113
  )
114
 
 
115
  if __name__ == "__main__":
116
+ demo.launch()