freddyaboulton HF staff commited on
Commit
9f6641f
1 Parent(s): df9d3ae

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +63 -0
utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gradio import ChatMessage
2
+ from transformers.agents import ReactCodeAgent, agent_types
3
+ from typing import Generator
4
+
5
+
6
+ def pull_message(step_log: dict):
7
+ if step_log.get("rationale"):
8
+ yield ChatMessage(
9
+ role="assistant", content=step_log["rationale"]
10
+ )
11
+ if step_log.get("tool_call"):
12
+ used_code = step_log["tool_call"]["tool_name"] == "code interpreter"
13
+ content = step_log["tool_call"]["tool_arguments"]
14
+ if used_code:
15
+ content = f"```py\n{content}\n```"
16
+ yield ChatMessage(
17
+ role="assistant",
18
+ metadata={"title": f"🛠️ Used tool {step_log['tool_call']['tool_name']}"},
19
+ content=content,
20
+ )
21
+ if step_log.get("observation"):
22
+ yield ChatMessage(
23
+ role="assistant", content=f"```\n{step_log['observation']}\n```"
24
+ )
25
+ if step_log.get("error"):
26
+ yield ChatMessage(
27
+ role="assistant",
28
+ content=str(step_log["error"]),
29
+ metadata={"title": "💥 Error"},
30
+ )
31
+
32
+
33
+ def stream_from_transformers_agent(
34
+ agent: ReactCodeAgent, prompt: str
35
+ ) -> Generator[ChatMessage, None, ChatMessage | None]:
36
+ """Runs an agent with the given prompt and streams the messages from the agent as ChatMessages."""
37
+
38
+ class Output:
39
+ output: agent_types.AgentType | str = None
40
+
41
+ for step_log in agent.run(prompt, stream=True):
42
+ if isinstance(step_log, dict):
43
+ for message in pull_message(step_log):
44
+ print("message", message)
45
+ yield message
46
+
47
+
48
+ Output.output = step_log
49
+ if isinstance(Output.output, agent_types.AgentText):
50
+ yield ChatMessage(
51
+ role="assistant", content=f"**Final answer:**\n```\n{Output.output.to_string()}\n```")
52
+ elif isinstance(Output.output, agent_types.AgentImage):
53
+ yield ChatMessage(
54
+ role="assistant",
55
+ content={"path": Output.output.to_string(), "mime_type": "image/png"},
56
+ )
57
+ elif isinstance(Output.output, agent_types.AgentAudio):
58
+ yield ChatMessage(
59
+ role="assistant",
60
+ content={"path": Output.output.to_string(), "mime_type": "audio/wav"},
61
+ )
62
+ else:
63
+ return ChatMessage(role="assistant", content=Output.output)