Jofthomas HF staff commited on
Commit
680f625
·
verified ·
1 Parent(s): 478d83b

upload LLama-Index notebooks

Browse files
unit2/llama-index/agents.ipynb ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "vscode": {
7
+ "languageId": "plaintext"
8
+ }
9
+ },
10
+ "source": [
11
+ "# Agents in LlamaIndex\n",
12
+ "\n",
13
+ "This notebook is part of the [Hugging Face Agents Course](https://www.hf.co/learn/agents-course), a free Course from beginner to expert, where you learn to build Agents.\n",
14
+ "\n",
15
+ "![Agents course share](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png)\n",
16
+ "\n",
17
+ "## Let's install the dependencies\n",
18
+ "\n",
19
+ "We will install the dependencies for this unit."
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": 43,
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "!pip install llama-index datasets llama-index-callbacks-arize-phoenix llama-index-vector-stores-chroma llama-index-llms-huggingface-api -U -q"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "And, let's log in to Hugging Face to use serverless Inference APIs."
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "from huggingface_hub import login\n",
45
+ "\n",
46
+ "login()"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "markdown",
51
+ "metadata": {
52
+ "vscode": {
53
+ "languageId": "plaintext"
54
+ }
55
+ },
56
+ "source": [
57
+ "## Initialising agents\n",
58
+ "\n",
59
+ "Let's start by initialising an agent. We will use the basic `AgentWorkflow` class to create an agent."
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "metadata": {},
66
+ "outputs": [],
67
+ "source": [
68
+ "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
69
+ "from llama_index.core.agent.workflow import AgentWorkflow, ToolCallResult, AgentStream\n",
70
+ "\n",
71
+ "\n",
72
+ "def add(a: int, b: int) -> int:\n",
73
+ " \"\"\"Add two numbers\"\"\"\n",
74
+ " return a + b\n",
75
+ "\n",
76
+ "\n",
77
+ "def subtract(a: int, b: int) -> int:\n",
78
+ " \"\"\"Subtract two numbers\"\"\"\n",
79
+ " return a - b\n",
80
+ "\n",
81
+ "\n",
82
+ "def multiply(a: int, b: int) -> int:\n",
83
+ " \"\"\"Multiply two numbers\"\"\"\n",
84
+ " return a * b\n",
85
+ "\n",
86
+ "\n",
87
+ "def divide(a: int, b: int) -> int:\n",
88
+ " \"\"\"Divide two numbers\"\"\"\n",
89
+ " return a / b\n",
90
+ "\n",
91
+ "\n",
92
+ "llm = HuggingFaceInferenceAPI(model_name=\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n",
93
+ "\n",
94
+ "agent = AgentWorkflow.from_tools_or_functions(\n",
95
+ " tools_or_functions=[subtract, multiply, divide, add],\n",
96
+ " llm=llm,\n",
97
+ " system_prompt=\"You are a math agent that can add, subtract, multiply, and divide numbers using provided tools.\",\n",
98
+ ")"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "markdown",
103
+ "metadata": {},
104
+ "source": [
105
+ "Then, we can run the agent and get the response and reasoning behind the tool calls."
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": null,
111
+ "metadata": {},
112
+ "outputs": [],
113
+ "source": [
114
+ "handler = agent.run(\"What is (2 + 2) * 2?\")\n",
115
+ "async for ev in handler.stream_events():\n",
116
+ " if isinstance(ev, ToolCallResult):\n",
117
+ " print(\"\")\n",
118
+ " print(\"Called tool: \", ev.tool_name, ev.tool_kwargs, \"=>\", ev.tool_output)\n",
119
+ " elif isinstance(ev, AgentStream): # showing the thought process\n",
120
+ " print(ev.delta, end=\"\", flush=True)\n",
121
+ "\n",
122
+ "resp = await handler\n",
123
+ "resp"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "markdown",
128
+ "metadata": {},
129
+ "source": [
130
+ "In a similar fashion, we can pass state and context to the agent.\n"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": 27,
136
+ "metadata": {},
137
+ "outputs": [
138
+ {
139
+ "data": {
140
+ "text/plain": [
141
+ "AgentOutput(response=ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, additional_kwargs={}, blocks=[TextBlock(block_type='text', text='Your name is Bob.')]), tool_calls=[], raw={'id': 'chatcmpl-B5sDHfGpSwsVyzvMVH8EWokYwdIKT', 'choices': [{'delta': {'content': None, 'function_call': None, 'refusal': None, 'role': None, 'tool_calls': None}, 'finish_reason': 'stop', 'index': 0, 'logprobs': None}], 'created': 1740739735, 'model': 'gpt-4o-2024-08-06', 'object': 'chat.completion.chunk', 'service_tier': 'default', 'system_fingerprint': 'fp_eb9dce56a8', 'usage': None}, current_agent_name='Agent')"
142
+ ]
143
+ },
144
+ "execution_count": 27,
145
+ "metadata": {},
146
+ "output_type": "execute_result"
147
+ }
148
+ ],
149
+ "source": [
150
+ "from llama_index.core.workflow import Context\n",
151
+ "\n",
152
+ "ctx = Context(agent)\n",
153
+ "\n",
154
+ "response = await agent.run(\"My name is Bob.\", ctx=ctx)\n",
155
+ "response = await agent.run(\"What was my name again?\", ctx=ctx)\n",
156
+ "response"
157
+ ]
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "## Creating RAG Agents with QueryEngineTools\n",
164
+ "\n",
165
+ "Let's now re-use the `QueryEngine` we defined in the [previous unit on tools](/tools.ipynb) and convert it into a `QueryEngineTool`. We will pass it to the `AgentWorkflow` class to create a RAG agent."
166
+ ]
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "execution_count": 46,
171
+ "metadata": {},
172
+ "outputs": [],
173
+ "source": [
174
+ "import chromadb\n",
175
+ "\n",
176
+ "from llama_index.core import VectorStoreIndex\n",
177
+ "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
178
+ "from llama_index.embeddings.huggingface_api import HuggingFaceInferenceAPIEmbedding\n",
179
+ "from llama_index.core.tools import QueryEngineTool\n",
180
+ "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
181
+ "\n",
182
+ "# Create a vector store\n",
183
+ "db = chromadb.PersistentClient(path=\"./alfred_chroma_db\")\n",
184
+ "chroma_collection = db.get_or_create_collection(\"alfred\")\n",
185
+ "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
186
+ "\n",
187
+ "# Create a query engine\n",
188
+ "embed_model = HuggingFaceInferenceAPIEmbedding(model_name=\"BAAI/bge-small-en-v1.5\")\n",
189
+ "llm = HuggingFaceInferenceAPI(model_name=\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n",
190
+ "index = VectorStoreIndex.from_vector_store(\n",
191
+ " vector_store=vector_store, embed_model=embed_model\n",
192
+ ")\n",
193
+ "query_engine = index.as_query_engine(llm=llm)\n",
194
+ "query_engine_tool = QueryEngineTool.from_defaults(\n",
195
+ " query_engine=query_engine,\n",
196
+ " name=\"personas\",\n",
197
+ " description=\"descriptions for various types of personas\",\n",
198
+ " return_direct=False,\n",
199
+ ")\n",
200
+ "\n",
201
+ "# Create a RAG agent\n",
202
+ "query_engine_agent = AgentWorkflow.from_tools_or_functions(\n",
203
+ " tools_or_functions=[query_engine_tool],\n",
204
+ " llm=llm,\n",
205
+ " system_prompt=\"You are a helpful assistant that has access to a database containing persona descriptions. \",\n",
206
+ ")"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "markdown",
211
+ "metadata": {},
212
+ "source": [
213
+ "And, we can once more get the response and reasoning behind the tool calls."
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": null,
219
+ "metadata": {},
220
+ "outputs": [],
221
+ "source": [
222
+ "handler = query_engine_agent.run(\n",
223
+ " \"Search the database for 'science fiction' and return some persona descriptions.\"\n",
224
+ ")\n",
225
+ "async for ev in handler.stream_events():\n",
226
+ " if isinstance(ev, ToolCallResult):\n",
227
+ " print(\"\")\n",
228
+ " print(\"Called tool: \", ev.tool_name, ev.tool_kwargs, \"=>\", ev.tool_output)\n",
229
+ " elif isinstance(ev, AgentStream): # showing the thought process\n",
230
+ " print(ev.delta, end=\"\", flush=True)\n",
231
+ "\n",
232
+ "resp = await handler\n",
233
+ "resp"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "markdown",
238
+ "metadata": {},
239
+ "source": [
240
+ "## Creating multi-agent systems\n",
241
+ "\n",
242
+ "We can also create multi-agent systems by passing multiple agents to the `AgentWorkflow` class."
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "execution_count": null,
248
+ "metadata": {},
249
+ "outputs": [],
250
+ "source": [
251
+ "from llama_index.core.agent.workflow import (\n",
252
+ " AgentWorkflow,\n",
253
+ " ReActAgent,\n",
254
+ ")\n",
255
+ "\n",
256
+ "\n",
257
+ "# Define some tools\n",
258
+ "def add(a: int, b: int) -> int:\n",
259
+ " \"\"\"Add two numbers.\"\"\"\n",
260
+ " return a + b\n",
261
+ "\n",
262
+ "\n",
263
+ "def subtract(a: int, b: int) -> int:\n",
264
+ " \"\"\"Subtract two numbers.\"\"\"\n",
265
+ " return a - b\n",
266
+ "\n",
267
+ "\n",
268
+ "# Create agent configs\n",
269
+ "# NOTE: we can use FunctionAgent or ReActAgent here.\n",
270
+ "# FunctionAgent works for LLMs with a function calling API.\n",
271
+ "# ReActAgent works for any LLM.\n",
272
+ "calculator_agent = ReActAgent(\n",
273
+ " name=\"calculator\",\n",
274
+ " description=\"Performs basic arithmetic operations\",\n",
275
+ " system_prompt=\"You are a calculator assistant. Use your tools for any math operation.\",\n",
276
+ " tools=[add, subtract],\n",
277
+ " llm=llm,\n",
278
+ ")\n",
279
+ "\n",
280
+ "query_agent = ReActAgent(\n",
281
+ " name=\"info_lookup\",\n",
282
+ " description=\"Looks up information about XYZ\",\n",
283
+ " system_prompt=\"Use your tool to query a RAG system to answer information about XYZ\",\n",
284
+ " tools=[query_engine_tool],\n",
285
+ " llm=llm,\n",
286
+ ")\n",
287
+ "\n",
288
+ "# Create and run the workflow\n",
289
+ "agent = AgentWorkflow(agents=[calculator_agent, query_agent], root_agent=\"calculator\")\n",
290
+ "\n",
291
+ "# Run the system\n",
292
+ "handler = agent.run(user_msg=\"Can you add 5 and 3?\")"
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "execution_count": null,
298
+ "metadata": {},
299
+ "outputs": [],
300
+ "source": [
301
+ "async for ev in handler.stream_events():\n",
302
+ " if isinstance(ev, ToolCallResult):\n",
303
+ " print(\"\")\n",
304
+ " print(\"Called tool: \", ev.tool_name, ev.tool_kwargs, \"=>\", ev.tool_output)\n",
305
+ " elif isinstance(ev, AgentStream): # showing the thought process\n",
306
+ " print(ev.delta, end=\"\", flush=True)\n",
307
+ "\n",
308
+ "resp = await handler\n",
309
+ "resp"
310
+ ]
311
+ }
312
+ ],
313
+ "metadata": {
314
+ "kernelspec": {
315
+ "display_name": ".venv",
316
+ "language": "python",
317
+ "name": "python3"
318
+ },
319
+ "language_info": {
320
+ "codemirror_mode": {
321
+ "name": "ipython",
322
+ "version": 3
323
+ },
324
+ "file_extension": ".py",
325
+ "mimetype": "text/x-python",
326
+ "name": "python",
327
+ "nbconvert_exporter": "python",
328
+ "pygments_lexer": "ipython3",
329
+ "version": "3.11.11"
330
+ }
331
+ },
332
+ "nbformat": 4,
333
+ "nbformat_minor": 2
334
+ }
unit2/llama-index/components.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
unit2/llama-index/tools.ipynb ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Tools in LlamaIndex\n",
8
+ "\n",
9
+ "\n",
10
+ "This notebook is part of the [Hugging Face Agents Course](https://www.hf.co/learn/agents-course), a free Course from beginner to expert, where you learn to build Agents.\n",
11
+ "\n",
12
+ "![Agents course share](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png)\n",
13
+ "\n",
14
+ "## Let's install the dependencies\n",
15
+ "\n",
16
+ "We will install the dependencies for this unit."
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": 1,
22
+ "metadata": {},
23
+ "outputs": [],
24
+ "source": [
25
+ "!pip install llama-index datasets llama-index-callbacks-arize-phoenix llama-index-vector-stores-chroma llama-index-llms-huggingface-api -U -q"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "markdown",
30
+ "metadata": {},
31
+ "source": [
32
+ "And, let's log in to Hugging Face to use serverless Inference APIs."
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": null,
38
+ "metadata": {},
39
+ "outputs": [],
40
+ "source": [
41
+ "from huggingface_hub import login\n",
42
+ "\n",
43
+ "login()"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "## Creating a FunctionTool\n",
51
+ "\n",
52
+ "Let's create a basic `FunctionTool` and call it."
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": 4,
58
+ "metadata": {},
59
+ "outputs": [],
60
+ "source": [
61
+ "from llama_index.core.tools import FunctionTool\n",
62
+ "\n",
63
+ "\n",
64
+ "def get_weather(location: str) -> str:\n",
65
+ " \"\"\"Useful for getting the weather for a given location.\"\"\"\n",
66
+ " print(f\"Getting weather for {location}\")\n",
67
+ " return f\"The weather in {location} is sunny\"\n",
68
+ "\n",
69
+ "\n",
70
+ "tool = FunctionTool.from_defaults(\n",
71
+ " get_weather,\n",
72
+ " name=\"my_weather_tool\",\n",
73
+ " description=\"Useful for getting the weather for a given location.\",\n",
74
+ ")\n",
75
+ "tool.call(\"New York\")"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "markdown",
80
+ "metadata": {},
81
+ "source": [
82
+ "## Creating a QueryEngineTool\n",
83
+ "\n",
84
+ "Let's now re-use the `QueryEngine` we defined in the [previous unit on tools](/tools.ipynb) and convert it into a `QueryEngineTool`. "
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": 8,
90
+ "metadata": {},
91
+ "outputs": [
92
+ {
93
+ "data": {
94
+ "text/plain": [
95
+ "ToolOutput(content=' As an anthropologist, I am intrigued by the potential implications of AI on the future of work and society. My research focuses on the cultural and social aspects of technological advancements, and I believe it is essential to understand how AI will shape the lives of Cypriot people and the broader society. I am particularly interested in exploring how AI will impact traditional industries, such as agriculture and tourism, and how it will affect the skills and knowledge required for future employment. As someone who has spent extensive time in Cyprus, I am well-positioned to investigate the unique cultural and historical context of the island and how it will influence the adoption and impact of AI. My research will not only provide valuable insights into the future of work but also contribute to the development of policies and strategies that support the well-being of Cypriot citizens and the broader society. \\n\\nAs an environmental historian or urban planner, I am more focused on the ecological and sustainability aspects of AI, particularly in the context of urban planning and conservation. I believe that AI has the potential to significantly impact the built environment and the natural world, and I am eager to explore how it can be used to create more sustainable and resilient cities. My research will focus on the intersection of AI, urban planning, and environmental conservation, and I', tool_name='some useful name', raw_input={'input': 'Responds about research on the impact of AI on the future of work and society?'}, raw_output=Response(response=' As an anthropologist, I am intrigued by the potential implications of AI on the future of work and society. My research focuses on the cultural and social aspects of technological advancements, and I believe it is essential to understand how AI will shape the lives of Cypriot people and the broader society. I am particularly interested in exploring how AI will impact traditional industries, such as agriculture and tourism, and how it will affect the skills and knowledge required for future employment. As someone who has spent extensive time in Cyprus, I am well-positioned to investigate the unique cultural and historical context of the island and how it will influence the adoption and impact of AI. My research will not only provide valuable insights into the future of work but also contribute to the development of policies and strategies that support the well-being of Cypriot citizens and the broader society. \\n\\nAs an environmental historian or urban planner, I am more focused on the ecological and sustainability aspects of AI, particularly in the context of urban planning and conservation. I believe that AI has the potential to significantly impact the built environment and the natural world, and I am eager to explore how it can be used to create more sustainable and resilient cities. My research will focus on the intersection of AI, urban planning, and environmental conservation, and I', source_nodes=[NodeWithScore(node=TextNode(id_='f0ea24d2-4ed3-4575-a41f-740a3fa8b521', embedding=None, metadata={'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1.txt', 'file_name': 'persona_1.txt', 'file_type': 'text/plain', 'file_size': 266, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={<NodeRelationship.SOURCE: '1'>: RelatedNodeInfo(node_id='d5db5bf4-daac-41e5-b5aa-271e8305da25', node_type='4', metadata={'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1.txt', 'file_name': 'persona_1.txt', 'file_type': 'text/plain', 'file_size': 266, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}, hash='e6c87149a97bf9e5dbdf33922a4e5023c6b72550ca0b63472bd5d25103b28e99')}, metadata_template='{key}: {value}', metadata_separator='\\n', text='An anthropologist or a cultural expert interested in the intricacies of Cypriot culture, history, and society, particularly someone who has spent considerable time researching and living in Cyprus to gain a deep understanding of its people, customs, and way of life.', mimetype='text/plain', start_char_idx=0, end_char_idx=266, metadata_seperator='\\n', text_template='{metadata_str}\\n\\n{content}'), score=0.3761845613489774), NodeWithScore(node=TextNode(id_='cebcd676-3180-4cda-be99-d535babc1b96', embedding=None, metadata={'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1004.txt', 'file_name': 'persona_1004.txt', 'file_type': 'text/plain', 'file_size': 160, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={<NodeRelationship.SOURCE: '1'>: RelatedNodeInfo(node_id='1347651d-7fc8-42d4-865c-a0151a534a1b', node_type='4', metadata={'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1004.txt', 'file_name': 'persona_1004.txt', 'file_type': 'text/plain', 'file_size': 160, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}, hash='19628b0ae4a0f0ebd63b75e13df7d9183f42e8bb84358fdc2c9049c016c4b67d')}, metadata_template='{key}: {value}', metadata_separator='\\n', text='An environmental historian or urban planner focused on ecological conservation and sustainability, likely working in local government or a related organization.', mimetype='text/plain', start_char_idx=0, end_char_idx=160, metadata_seperator='\\n', text_template='{metadata_str}\\n\\n{content}'), score=0.3733060058493167)], metadata={'f0ea24d2-4ed3-4575-a41f-740a3fa8b521': {'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1.txt', 'file_name': 'persona_1.txt', 'file_type': 'text/plain', 'file_size': 266, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}, 'cebcd676-3180-4cda-be99-d535babc1b96': {'file_path': '/Users/davidberenstein/Documents/programming/huggingface/agents-course/notebooks/unit2/llama-index/data/persona_1004.txt', 'file_name': 'persona_1004.txt', 'file_type': 'text/plain', 'file_size': 160, 'creation_date': '2025-02-27', 'last_modified_date': '2025-02-27'}}), is_error=False)"
96
+ ]
97
+ },
98
+ "execution_count": 8,
99
+ "metadata": {},
100
+ "output_type": "execute_result"
101
+ }
102
+ ],
103
+ "source": [
104
+ "import chromadb\n",
105
+ "\n",
106
+ "from llama_index.core import VectorStoreIndex\n",
107
+ "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
108
+ "from llama_index.embeddings.huggingface_api import HuggingFaceInferenceAPIEmbedding\n",
109
+ "from llama_index.core.tools import QueryEngineTool\n",
110
+ "from llama_index.vector_stores.chroma import ChromaVectorStore\n",
111
+ "\n",
112
+ "db = chromadb.PersistentClient(path=\"./alfred_chroma_db\")\n",
113
+ "chroma_collection = db.get_or_create_collection(\"alfred\")\n",
114
+ "vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
115
+ "embed_model = HuggingFaceInferenceAPIEmbedding(model_name=\"BAAI/bge-small-en-v1.5\")\n",
116
+ "llm = HuggingFaceInferenceAPI(model_name=\"meta-llama/Llama-3.2-3B-Instruct\")\n",
117
+ "index = VectorStoreIndex.from_vector_store(\n",
118
+ " vector_store=vector_store, embed_model=embed_model\n",
119
+ ")\n",
120
+ "query_engine = index.as_query_engine(llm=llm)\n",
121
+ "tool = QueryEngineTool.from_defaults(\n",
122
+ " query_engine=query_engine,\n",
123
+ " name=\"some useful name\",\n",
124
+ " description=\"some useful description\",\n",
125
+ ")\n",
126
+ "await tool.acall(\n",
127
+ " \"Responds about research on the impact of AI on the future of work and society?\"\n",
128
+ ")"
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "markdown",
133
+ "metadata": {},
134
+ "source": [
135
+ "## Creating Toolspecs\n",
136
+ "\n",
137
+ "Let's create a `ToolSpec` from the `GmailToolSpec` from the LlamaHub and convert it to a list of tools. "
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "execution_count": 14,
143
+ "metadata": {},
144
+ "outputs": [
145
+ {
146
+ "data": {
147
+ "text/plain": [
148
+ "[<llama_index.core.tools.function_tool.FunctionTool at 0x15d638410>,\n",
149
+ " <llama_index.core.tools.function_tool.FunctionTool at 0x15d64a190>,\n",
150
+ " <llama_index.core.tools.function_tool.FunctionTool at 0x159cf8050>,\n",
151
+ " <llama_index.core.tools.function_tool.FunctionTool at 0x15d65b150>,\n",
152
+ " <llama_index.core.tools.function_tool.FunctionTool at 0x15cef6990>,\n",
153
+ " <llama_index.core.tools.function_tool.FunctionTool at 0x15d642b10>]"
154
+ ]
155
+ },
156
+ "execution_count": 14,
157
+ "metadata": {},
158
+ "output_type": "execute_result"
159
+ }
160
+ ],
161
+ "source": [
162
+ "from llama_index.tools.google import GmailToolSpec\n",
163
+ "\n",
164
+ "tool_spec = GmailToolSpec()\n",
165
+ "tool_spec_list = tool_spec.to_tool_list()\n",
166
+ "tool_spec_list"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "markdown",
171
+ "metadata": {},
172
+ "source": [
173
+ "To get a more detailed view of the tools, we can take a look at the `metadata` of each tool."
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "execution_count": 15,
179
+ "metadata": {},
180
+ "outputs": [
181
+ {
182
+ "data": {
183
+ "text/plain": [
184
+ "[('load_data',\n",
185
+ " \"load_data() -> List[llama_index.core.schema.Document]\\nLoad emails from the user's account.\"),\n",
186
+ " ('search_messages',\n",
187
+ " \"search_messages(query: str, max_results: Optional[int] = None)\\nSearches email messages given a query string and the maximum number\\n of results requested by the user\\n Returns: List of relevant message objects up to the maximum number of results.\\n\\n Args:\\n query[str]: The user's query\\n max_results (Optional[int]): The maximum number of search results\\n to return.\\n \"),\n",
188
+ " ('create_draft',\n",
189
+ " \"create_draft(to: Optional[List[str]] = None, subject: Optional[str] = None, message: Optional[str] = None) -> str\\nCreate and insert a draft email.\\n Print the returned draft's message and id.\\n Returns: Draft object, including draft id and message meta data.\\n\\n Args:\\n to (Optional[str]): The email addresses to send the message to\\n subject (Optional[str]): The subject for the event\\n message (Optional[str]): The message for the event\\n \"),\n",
190
+ " ('update_draft',\n",
191
+ " \"update_draft(to: Optional[List[str]] = None, subject: Optional[str] = None, message: Optional[str] = None, draft_id: str = None) -> str\\nUpdate a draft email.\\n Print the returned draft's message and id.\\n This function is required to be passed a draft_id that is obtained when creating messages\\n Returns: Draft object, including draft id and message meta data.\\n\\n Args:\\n to (Optional[str]): The email addresses to send the message to\\n subject (Optional[str]): The subject for the event\\n message (Optional[str]): The message for the event\\n draft_id (str): the id of the draft to be updated\\n \"),\n",
192
+ " ('get_draft',\n",
193
+ " \"get_draft(draft_id: str = None) -> str\\nGet a draft email.\\n Print the returned draft's message and id.\\n Returns: Draft object, including draft id and message meta data.\\n\\n Args:\\n draft_id (str): the id of the draft to be updated\\n \"),\n",
194
+ " ('send_draft',\n",
195
+ " \"send_draft(draft_id: str = None) -> str\\nSends a draft email.\\n Print the returned draft's message and id.\\n Returns: Draft object, including draft id and message meta data.\\n\\n Args:\\n draft_id (str): the id of the draft to be updated\\n \")]"
196
+ ]
197
+ },
198
+ "execution_count": 15,
199
+ "metadata": {},
200
+ "output_type": "execute_result"
201
+ }
202
+ ],
203
+ "source": [
204
+ "[(tool.metadata.name, tool.metadata.description) for tool in tool_spec_list]"
205
+ ]
206
+ }
207
+ ],
208
+ "metadata": {
209
+ "kernelspec": {
210
+ "display_name": ".venv",
211
+ "language": "python",
212
+ "name": "python3"
213
+ },
214
+ "language_info": {
215
+ "codemirror_mode": {
216
+ "name": "ipython",
217
+ "version": 3
218
+ },
219
+ "file_extension": ".py",
220
+ "mimetype": "text/x-python",
221
+ "name": "python",
222
+ "nbconvert_exporter": "python",
223
+ "pygments_lexer": "ipython3",
224
+ "version": "3.11.11"
225
+ }
226
+ },
227
+ "nbformat": 4,
228
+ "nbformat_minor": 2
229
+ }
unit2/llama-index/workflows.ipynb ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Workflows in LlamaIndex\n",
8
+ "\n",
9
+ "\n",
10
+ "This notebook is part of the [Hugging Face Agents Course](https://www.hf.co/learn/agents-course), a free Course from beginner to expert, where you learn to build Agents.\n",
11
+ "\n",
12
+ "![Agents course share](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png)\n",
13
+ "\n",
14
+ "## Let's install the dependencies\n",
15
+ "\n",
16
+ "We will install the dependencies for this unit."
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": 11,
22
+ "metadata": {},
23
+ "outputs": [],
24
+ "source": [
25
+ "!pip install llama-index datasets llama-index-callbacks-arize-phoenix llama-index-vector-stores-chroma llama-index-utils-workflow llama-index-llms-huggingface-api pyvis -U -q"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "markdown",
30
+ "metadata": {},
31
+ "source": [
32
+ "And, let's log in to Hugging Face to use serverless Inference APIs."
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "execution_count": null,
38
+ "metadata": {},
39
+ "outputs": [],
40
+ "source": [
41
+ "from huggingface_hub import login\n",
42
+ "\n",
43
+ "login()"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {},
49
+ "source": [
50
+ "## Basic Workflow Creation\n",
51
+ "\n",
52
+ "We can start by creating a simple workflow. We use the `StartEvent` and `StopEvent` classes to define the start and stop of the workflow."
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": 3,
58
+ "metadata": {},
59
+ "outputs": [
60
+ {
61
+ "data": {
62
+ "text/plain": [
63
+ "'Hello, world!'"
64
+ ]
65
+ },
66
+ "execution_count": 3,
67
+ "metadata": {},
68
+ "output_type": "execute_result"
69
+ }
70
+ ],
71
+ "source": [
72
+ "from llama_index.core.workflow import StartEvent, StopEvent, Workflow, step\n",
73
+ "\n",
74
+ "\n",
75
+ "class MyWorkflow(Workflow):\n",
76
+ " @step\n",
77
+ " async def my_step(self, ev: StartEvent) -> StopEvent:\n",
78
+ " # do something here\n",
79
+ " return StopEvent(result=\"Hello, world!\")\n",
80
+ "\n",
81
+ "\n",
82
+ "w = MyWorkflow(timeout=10, verbose=False)\n",
83
+ "result = await w.run()\n",
84
+ "result"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "markdown",
89
+ "metadata": {},
90
+ "source": [
91
+ "## Connecting Multiple Steps\n",
92
+ "\n",
93
+ "We can also create multi-step workflows. Here we pass the event information between steps. Note that we can use type hinting to specify the event type and the flow of the workflow."
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": 4,
99
+ "metadata": {},
100
+ "outputs": [
101
+ {
102
+ "data": {
103
+ "text/plain": [
104
+ "'Finished processing: Step 1 complete'"
105
+ ]
106
+ },
107
+ "execution_count": 4,
108
+ "metadata": {},
109
+ "output_type": "execute_result"
110
+ }
111
+ ],
112
+ "source": [
113
+ "from llama_index.core.workflow import Event\n",
114
+ "\n",
115
+ "\n",
116
+ "class ProcessingEvent(Event):\n",
117
+ " intermediate_result: str\n",
118
+ "\n",
119
+ "\n",
120
+ "class MultiStepWorkflow(Workflow):\n",
121
+ " @step\n",
122
+ " async def step_one(self, ev: StartEvent) -> ProcessingEvent:\n",
123
+ " # Process initial data\n",
124
+ " return ProcessingEvent(intermediate_result=\"Step 1 complete\")\n",
125
+ "\n",
126
+ " @step\n",
127
+ " async def step_two(self, ev: ProcessingEvent) -> StopEvent:\n",
128
+ " # Use the intermediate result\n",
129
+ " final_result = f\"Finished processing: {ev.intermediate_result}\"\n",
130
+ " return StopEvent(result=final_result)\n",
131
+ "\n",
132
+ "\n",
133
+ "w = MultiStepWorkflow(timeout=10, verbose=False)\n",
134
+ "result = await w.run()\n",
135
+ "result"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "markdown",
140
+ "metadata": {},
141
+ "source": [
142
+ "## Loops and Branches\n",
143
+ "\n",
144
+ "We can also use type hinting to create branches and loops. Note that we can use the `|` operator to specify that the step can return multiple types."
145
+ ]
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "execution_count": 28,
150
+ "metadata": {},
151
+ "outputs": [
152
+ {
153
+ "name": "stdout",
154
+ "output_type": "stream",
155
+ "text": [
156
+ "Good thing happened\n"
157
+ ]
158
+ },
159
+ {
160
+ "data": {
161
+ "text/plain": [
162
+ "'Finished processing: First step complete.'"
163
+ ]
164
+ },
165
+ "execution_count": 28,
166
+ "metadata": {},
167
+ "output_type": "execute_result"
168
+ }
169
+ ],
170
+ "source": [
171
+ "from llama_index.core.workflow import Event\n",
172
+ "import random\n",
173
+ "\n",
174
+ "\n",
175
+ "class ProcessingEvent(Event):\n",
176
+ " intermediate_result: str\n",
177
+ "\n",
178
+ "\n",
179
+ "class LoopEvent(Event):\n",
180
+ " loop_output: str\n",
181
+ "\n",
182
+ "\n",
183
+ "class MultiStepWorkflow(Workflow):\n",
184
+ " @step\n",
185
+ " async def step_one(self, ev: StartEvent) -> ProcessingEvent | LoopEvent:\n",
186
+ " if random.randint(0, 1) == 0:\n",
187
+ " print(\"Bad thing happened\")\n",
188
+ " return LoopEvent(loop_output=\"Back to step one.\")\n",
189
+ " else:\n",
190
+ " print(\"Good thing happened\")\n",
191
+ " return ProcessingEvent(intermediate_result=\"First step complete.\")\n",
192
+ "\n",
193
+ " @step\n",
194
+ " async def step_two(self, ev: ProcessingEvent | LoopEvent) -> StopEvent:\n",
195
+ " # Use the intermediate result\n",
196
+ " final_result = f\"Finished processing: {ev.intermediate_result}\"\n",
197
+ " return StopEvent(result=final_result)\n",
198
+ "\n",
199
+ "\n",
200
+ "w = MultiStepWorkflow(verbose=False)\n",
201
+ "result = await w.run()\n",
202
+ "result"
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "markdown",
207
+ "metadata": {},
208
+ "source": [
209
+ "## Drawing Workflows\n",
210
+ "\n",
211
+ "We can also draw workflows using the `draw_all_possible_flows` function.\n"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 24,
217
+ "metadata": {},
218
+ "outputs": [
219
+ {
220
+ "name": "stdout",
221
+ "output_type": "stream",
222
+ "text": [
223
+ "<class 'NoneType'>\n",
224
+ "<class '__main__.ProcessingEvent'>\n",
225
+ "<class '__main__.LoopEvent'>\n",
226
+ "<class 'llama_index.core.workflow.events.StopEvent'>\n",
227
+ "workflow_all_flows.html\n"
228
+ ]
229
+ }
230
+ ],
231
+ "source": [
232
+ "from llama_index.utils.workflow import draw_all_possible_flows\n",
233
+ "\n",
234
+ "draw_all_possible_flows(w)"
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "markdown",
239
+ "metadata": {},
240
+ "source": [
241
+ "![drawing](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/workflow-draw.png)"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "markdown",
246
+ "metadata": {},
247
+ "source": [
248
+ "### State Management\n",
249
+ "\n",
250
+ "Instead of passing the event information between steps, we can use the `Context` type hint to pass information between steps. \n",
251
+ "This might be useful for long running workflows, where you want to store information between steps."
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 25,
257
+ "metadata": {},
258
+ "outputs": [
259
+ {
260
+ "name": "stdout",
261
+ "output_type": "stream",
262
+ "text": [
263
+ "Query: What is the capital of France?\n"
264
+ ]
265
+ },
266
+ {
267
+ "data": {
268
+ "text/plain": [
269
+ "'Finished processing: Step 1 complete'"
270
+ ]
271
+ },
272
+ "execution_count": 25,
273
+ "metadata": {},
274
+ "output_type": "execute_result"
275
+ }
276
+ ],
277
+ "source": [
278
+ "from llama_index.core.workflow import Event, Context\n",
279
+ "from llama_index.core.agent.workflow import ReActAgent\n",
280
+ "\n",
281
+ "\n",
282
+ "class ProcessingEvent(Event):\n",
283
+ " intermediate_result: str\n",
284
+ "\n",
285
+ "\n",
286
+ "class MultiStepWorkflow(Workflow):\n",
287
+ " @step\n",
288
+ " async def step_one(self, ev: StartEvent, ctx: Context) -> ProcessingEvent:\n",
289
+ " # Process initial data\n",
290
+ " await ctx.set(\"query\", \"What is the capital of France?\")\n",
291
+ " return ProcessingEvent(intermediate_result=\"Step 1 complete\")\n",
292
+ "\n",
293
+ " @step\n",
294
+ " async def step_two(self, ev: ProcessingEvent, ctx: Context) -> StopEvent:\n",
295
+ " # Use the intermediate result\n",
296
+ " query = await ctx.get(\"query\")\n",
297
+ " print(f\"Query: {query}\")\n",
298
+ " final_result = f\"Finished processing: {ev.intermediate_result}\"\n",
299
+ " return StopEvent(result=final_result)\n",
300
+ "\n",
301
+ "\n",
302
+ "w = MultiStepWorkflow(timeout=10, verbose=False)\n",
303
+ "result = await w.run()\n",
304
+ "result"
305
+ ]
306
+ },
307
+ {
308
+ "cell_type": "markdown",
309
+ "metadata": {},
310
+ "source": [
311
+ "## Multi-Agent Workflows\n",
312
+ "\n",
313
+ "We can also create multi-agent workflows. Here we define two agents, one that multiplies two integers and one that adds two integers."
314
+ ]
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "execution_count": null,
319
+ "metadata": {},
320
+ "outputs": [
321
+ {
322
+ "data": {
323
+ "text/plain": [
324
+ "AgentOutput(response=ChatMessage(role=<MessageRole.ASSISTANT: 'assistant'>, additional_kwargs={}, blocks=[TextBlock(block_type='text', text='I have handed off the request to an agent who can help you with adding 5 and 3. Please wait for their response.')]), tool_calls=[ToolCallResult(tool_name='handoff', tool_kwargs={'to_agent': 'addition_agent', 'reason': 'Add 5 and 3'}, tool_id='call_F97vcIcsvZjfAAOBzzIifW3y', tool_output=ToolOutput(content='Agent addition_agent is now handling the request due to the following reason: Add 5 and 3.\\nPlease continue with the current request.', tool_name='handoff', raw_input={'args': (), 'kwargs': {'to_agent': 'addition_agent', 'reason': 'Add 5 and 3'}}, raw_output='Agent addition_agent is now handling the request due to the following reason: Add 5 and 3.\\nPlease continue with the current request.', is_error=False), return_direct=True), ToolCallResult(tool_name='handoff', tool_kwargs={'to_agent': 'addition_agent', 'reason': 'Add 5 and 3'}, tool_id='call_jf49ktFRs09xYdOsnApAk2zz', tool_output=ToolOutput(content='Agent addition_agent is now handling the request due to the following reason: Add 5 and 3.\\nPlease continue with the current request.', tool_name='handoff', raw_input={'args': (), 'kwargs': {'to_agent': 'addition_agent', 'reason': 'Add 5 and 3'}}, raw_output='Agent addition_agent is now handling the request due to the following reason: Add 5 and 3.\\nPlease continue with the current request.', is_error=False), return_direct=True)], raw={'id': 'chatcmpl-B6Cy54VQkvlG3VOrmdzCzgwcJmVOc', 'choices': [{'delta': {'content': None, 'function_call': None, 'refusal': None, 'role': None, 'tool_calls': None}, 'finish_reason': 'stop', 'index': 0, 'logprobs': None}], 'created': 1740819517, 'model': 'gpt-3.5-turbo-0125', 'object': 'chat.completion.chunk', 'service_tier': 'default', 'system_fingerprint': None, 'usage': None}, current_agent_name='addition_agent')"
325
+ ]
326
+ },
327
+ "execution_count": 33,
328
+ "metadata": {},
329
+ "output_type": "execute_result"
330
+ }
331
+ ],
332
+ "source": [
333
+ "from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI\n",
334
+ "\n",
335
+ "# Define some tools\n",
336
+ "def add(a: int, b: int) -> int:\n",
337
+ " \"\"\"Add two numbers.\"\"\"\n",
338
+ " return a + b\n",
339
+ "\n",
340
+ "def multiply(a: int, b: int) -> int:\n",
341
+ " \"\"\"Multiply two numbers.\"\"\"\n",
342
+ " return a * b\n",
343
+ "\n",
344
+ "llm = HuggingFaceInferenceAPI(model_name=\"Qwen/Qwen2.5-Coder-32B-Instruct\")\n",
345
+ "\n",
346
+ "# we can pass functions directly without FunctionTool -- the fn/docstring are parsed for the name/description\n",
347
+ "multiply_agent = ReActAgent(\n",
348
+ " name=\"multiply_agent\",\n",
349
+ " description=\"Is able to multiply two integers\",\n",
350
+ " system_prompt=\"A helpful assistant that can use a tool to multiply numbers.\",\n",
351
+ " tools=[multiply], \n",
352
+ " llm=llm,\n",
353
+ ")\n",
354
+ "\n",
355
+ "addition_agent = ReActAgent(\n",
356
+ " name=\"add_agent\",\n",
357
+ " description=\"Is able to add two integers\",\n",
358
+ " system_prompt=\"A helpful assistant that can use a tool to add numbers.\",\n",
359
+ " tools=[add], \n",
360
+ " llm=llm,\n",
361
+ ")\n",
362
+ "\n",
363
+ "# Create the workflow\n",
364
+ "workflow = AgentWorkflow(\n",
365
+ " agents=[multiply_agent, addition_agent],\n",
366
+ " root_agent=\"multiply_agent\"\n",
367
+ ")\n",
368
+ "\n",
369
+ "# Run the system\n",
370
+ "response = await workflow.run(user_msg=\"Can you add 5 and 3?\")"
371
+ ]
372
+ }
373
+ ],
374
+ "metadata": {
375
+ "kernelspec": {
376
+ "display_name": ".venv",
377
+ "language": "python",
378
+ "name": "python3"
379
+ },
380
+ "language_info": {
381
+ "codemirror_mode": {
382
+ "name": "ipython",
383
+ "version": 3
384
+ },
385
+ "file_extension": ".py",
386
+ "mimetype": "text/x-python",
387
+ "name": "python",
388
+ "nbconvert_exporter": "python",
389
+ "pygments_lexer": "ipython3",
390
+ "version": "3.11.11"
391
+ }
392
+ },
393
+ "nbformat": 4,
394
+ "nbformat_minor": 2
395
+ }