srush HF staff commited on
Commit
55b1220
1 Parent(s): fbbc116

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # + tags=["hide_inp"]
2
+
3
+ desc = """
4
+ ### Agent
5
+
6
+ Chain that executes different tools based on model decisions. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/srush/MiniChain/blob/master/examples/bash.ipynb)
7
+
8
+ (Adapted from LangChain )
9
+ """
10
+ # -
11
+
12
+ # $
13
+
14
+ from minichain import Id, prompt, OpenAI, show, transform, Mock, Break
15
+ from gradio_tools.tools import StableDiffusionTool, ImageCaptioningTool, ImageToMusicTool
16
+
17
+
18
+ # class ImageCaptioningTool:
19
+ # def run(self, inp):
20
+ # return "This is a picture of a smiling huggingface logo."
21
+
22
+ # description = "Image Captioning"
23
+
24
+ tools = [StableDiffusionTool(), ImageCaptioningTool(), ImageToMusicTool()]
25
+
26
+
27
+ @prompt(OpenAI(stop=["Observation:"]),
28
+ template_file="agent.pmpt.tpl")
29
+ def agent(model, query, history):
30
+ return model(dict(tools=[(str(tool.__class__.__name__), tool.description)
31
+ for tool in tools],
32
+ input=query,
33
+ agent_scratchpad=history
34
+ ))
35
+ @transform()
36
+ def tool_parse(out):
37
+ lines = out.split("\n")
38
+ if lines[0].split("?")[-1].strip() == "Yes":
39
+ tool = lines[1].split(":", 1)[-1].strip()
40
+ command = lines[2].split(":", 1)[-1].strip()
41
+ return tool, command
42
+ else:
43
+ return Break()
44
+
45
+ @prompt(tools)
46
+ def tool_use(model, usage):
47
+ selector, command = usage
48
+ for i, tool in enumerate(tools):
49
+ if selector == tool.__class__.__name__:
50
+ return model(command, tool_num=i)
51
+ return ("",)
52
+
53
+ @transform()
54
+ def append(history, new, observation):
55
+ return history + "\n" + new + "Observation: " + observation
56
+
57
+ def run(query):
58
+ history = ""
59
+ observations = []
60
+ for i in range(3):
61
+ select_input = agent(query, history)
62
+ observations.append(tool_use(tool_parse(select_input)))
63
+ history = append(history, select_input, observations[i])
64
+
65
+ return observations[-1]
66
+
67
+ # $
68
+
69
+ gradio = show(run,
70
+ subprompts=[agent, tool_use] * 3,
71
+ examples=[
72
+ "I would please like a photo of a dog riding a skateboard. "
73
+ "Please caption this image and create a song for it.",
74
+ 'Use an image generator tool to draw a cat.',
75
+ 'Caption the image https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.png from the internet'],
76
+ out_type="markdown",
77
+ description=desc,
78
+ show_advanced=False
79
+ )
80
+ if __name__ == "__main__":
81
+ gradio.queue().launch()
82
+