CultriX commited on
Commit
c3cdef4
·
verified ·
1 Parent(s): defabe4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -59
app.py CHANGED
@@ -1,64 +1,128 @@
 
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
+ import asyncio
2
  import gradio as gr
3
+ from autogen.runtime_logging import start, stop
4
+ from autogen_agentchat.agents import AssistantAgent
5
+ from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
6
+ from autogen_agentchat.teams import RoundRobinGroupChat
7
+ from autogen_ext.models.openai import OpenAIChatCompletionClient
8
+ from autogen_agentchat.base import TaskResult
9
+
10
+ # Configuration
11
+ LOG_FILE = "team_runtime.log"
12
+
13
+ def create_llm_config(api_key):
14
+ return {
15
+ "model": "gpt-4o",
16
+ "api_key": api_key,
17
+ "cache_seed": None
18
+ }
19
+
20
+ # Create the team with primary and critic agents
21
+ def create_team(llm_config, primary_system_message, critic_system_message):
22
+ model_client = OpenAIChatCompletionClient(**llm_config)
23
+
24
+ primary_agent = AssistantAgent(
25
+ "primary",
26
+ model_client=model_client,
27
+ system_message=primary_system_message,
28
+ )
29
+
30
+ critic_agent = AssistantAgent(
31
+ "critic",
32
+ model_client=model_client,
33
+ system_message=critic_system_message
34
+ )
35
+
36
+ # Set termination conditions (10-message cap OR "APPROVE" detected)
37
+ max_message_termination = MaxMessageTermination(max_messages=10)
38
+ text_termination = TextMentionTermination("APPROVE")
39
+ combined_termination = max_message_termination | text_termination
40
+
41
+ team = RoundRobinGroupChat([primary_agent, critic_agent], termination_condition=combined_termination)
42
+ return team, model_client
43
+
44
+ # Function to stream the task through the workflow
45
+ async def async_stream_task(task_message, api_key, primary_system_message, critic_system_message):
46
+ # Start logging
47
+ logging_session_id = start(logger_type="file", config={"filename": LOG_FILE})
48
+ print(f"Logging session ID: {logging_session_id}")
49
+
50
+ llm_config = create_llm_config(api_key)
51
+ team, model_client = create_team(llm_config, primary_system_message, critic_system_message)
52
+ documentation_triggered = False # Track if documentation agent was triggered
53
+ final_output = None # Store the final approved output
54
+
55
+ try:
56
+ async for message in team.run_stream(task=task_message):
57
+ if hasattr(message, "source") and hasattr(message, "content"):
58
+ # Handle critic's approval
59
+ if message.source == "critic" and "APPROVE" in message.content:
60
+ print("Critic approved the response. Handing off to Documentation Agent...")
61
+ documentation_triggered = True
62
+ final_output = task_message # Capture the final approved output
63
+ break
64
+ yield message.source, message.content
65
+
66
+ # Trigger Documentation Agent if approved
67
+ if documentation_triggered and final_output:
68
+ documentation_agent = AssistantAgent(
69
+ "documentation",
70
+ model_client=model_client,
71
+ system_message="You are a documentation assistant. Write a short and concise '--help' message for the provided code.",
72
+ )
73
+ doc_task = f"Generate a '--help' message for the following code:\n\n{final_output}"
74
+ async for doc_message in documentation_agent.run_stream(task=doc_task):
75
+ if isinstance(doc_message, TaskResult):
76
+ # Extract messages from TaskResult
77
+ for msg in doc_message.messages:
78
+ yield msg.source, msg.content
79
+ else:
80
+ yield doc_message.source, doc_message.content
81
+
82
+ finally:
83
+ # Stop logging
84
+ stop()
85
+
86
+ # Gradio interface function
87
+ async def chat_interface(api_key, primary_system_message, critic_system_message, task_message):
88
+ primary_messages = []
89
+ critic_messages = []
90
+ documentation_messages = []
91
+
92
+ # Append new messages while streaming
93
+ async for source, output in async_stream_task(task_message, api_key, primary_system_message, critic_system_message):
94
+ if source == "primary":
95
+ primary_messages.append(output)
96
+ elif source == "critic":
97
+ critic_messages.append(output)
98
+ elif source == "documentation":
99
+ documentation_messages.append(output)
100
+
101
+ # Return all outputs
102
+ yield (
103
+ "\n".join(primary_messages),
104
+ "\n".join(critic_messages),
105
+ "\n".join(documentation_messages),
106
+ )
107
+
108
+ # Gradio interface
109
+ iface = gr.Interface(
110
+ fn=chat_interface,
111
+ inputs=[
112
+ gr.Textbox(label="OpenAI API Key", type="password", placeholder="Enter your OpenAI API Key"),
113
+ gr.Textbox(label="Primary Agent System Message", placeholder="Enter the system message for the primary agent", value="You are a creative assistant focused on producing high-quality code."),
114
+ gr.Textbox(label="Critic Agent System Message", placeholder="Enter the system message for the critic agent", value="Critic. You are a helpful assistant highly skilled in evaluating the quality of a given code or response. Provide constructive feedback and respond with 'APPROVE' once the feedback is addressed."),
115
+ gr.Textbox(label="Task Message", placeholder="Enter your task message"),
116
  ],
117
+ outputs=[
118
+ gr.Textbox(label="Primary Assistant Messages"),
119
+ gr.Textbox(label="Critic Messages"),
120
+ gr.Textbox(label="Documentation Messages"),
121
+ ],
122
+ title="Team Workflow with Documentation Agent and Hard Cap",
123
+ description="Collaborative workflow between Primary, Critic, and Documentation agents with a hard cap on messages."
124
  )
125
 
126
+ # Launch the app
127
  if __name__ == "__main__":
128
+ iface.launch(share=True)