This course is framework agnostic because we want to focus on the concepts of AI agents and avoid getting bogged down in the specifics of a particular framework.
Also, we want students to be able to use the concepts they learn in this course in their own projects, in any framework.
Therefore, for this Unit 1, we will use a dummy agent library and simple severless API, which will be our LLM engine.
In reality, you would not use these in production, but they will serve as a good starting point for understanding how agents work.
But, after this section, you’ll create a simple Agent using smolagents
And in the following Units we will also use other AI Agent libraries like LangGraph
, LangChain
, and LlamaIndex
.
To keep things simple we will use a simple Python function as a Tool and Agent.
We will use built in python packages like datetime
and os
so that you can try it out in any environment.
You can find the notebook here. If you want to run the code.
In the Hugging Face ecosystem, there is a convenient feature called Serverless API that allows you to test some models. This uses shared endpoints between multiple users to compute some requests. This is convenient to test some models.
import os
from huggingface_hub import InferenceClient
## You need a token, this can be set in the "settings" tab under "secret". Make sure to call it "HF_TOKEN"
os.environ["HF_TOKEN"]="hf_xxxxxxxxxxxxxx"
client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
output = client.text_generation(
"The capital of france is",
max_new_tokens=100,
)
print(output)
output:
Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris.
As seen in the LLM section, if we just do decoding, the model will only stop when it predicts an EOS token and this does not happen here because we forgot to add the special tokens of this model.
If we now add the special tokens related to the Llama-3.2-3B-Instruct model that we’re using, the behavior changes and now produces the expected EOS.
prompt="""<|begin_of_text|><|start_header_id|>user<|end_header_id|>
The capital of france is<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
output = client.text_generation(
prompt,
max_new_tokens=100,
)
print(output)
output:
The capital of France is Paris.
Manually adding special tokens is equivalent to using the “chat” method:
output = client.chat.completions.create(
messages=[
{"role": "user", "content": "The capital of france is"},
],
stream=False,
max_tokens=1024,
)
output:
Paris.
The chat method is the RECOMMENDED method to use in order to ensure a smooth transition between models but since this notebook is only educationnal, we will keep using the “text_generation” method to understand the details.
In the previous sections, we saw that the core of an agent library is to append information in the system prompt.
This system prompt is a bit more complex than the one we saw earlier, but it already contains:
Answer the following questions as best you can. You have access to the following tools:
get_weather: Get the current weather in a given location
The way you use the tools is by specifying a json blob.
Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).
The only values that should be in the "action" field are:
get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}}
example use :
{{
"action": "get_weather",
"action_input": {"location": "New York"}
}}
ALWAYS use the following format:
Question: the input question you must answer
Thought: you should always think about one action to take. Only one action at a time in this format:
Action:
$JSON_BLOB (inside markdown cell)
Observation: the result of the action. This Observation is unique, complete, and the source of truth.
... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.)
Youb must always end your output with the following format:
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer.
Since we are running the “text_generation”, we need to add the right special tokens.
prompt=f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
{SYSTEM_PROMPT}
<|eot_id|><|start_header_id|>user<|end_header_id|>
What's the weather in London ?
<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""
This is equivalent to the following code that happens inside the chat method :
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "What's the weather in London ?"},
]
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B-Instruct")
tokenizer.apply_chat_template(messages, tokenize=False,add_generation_prompt=True)
The prompt now is :
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Answer the following questions as best you can. You have access to the following tools:
get_weather: Get the current weather in a given location
The way you use the tools is by specifying a json blob.
Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).
The only values that should be in the "action" field are:
get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}}
example use :
{{
"action": "get_weather",
"action_input": {"location": "New York"}
}}
ALWAYS use the following format:
Question: the input question you must answer
Thought: you should always think about one action to take. Only one action at a time in this format:
Action:
$JSON_BLOB (inside markdown cell)
Observation: the result of the action. This Observation is unique, complete, and the source of truth.
... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.)
Youb must always end your output with the following format:
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer.
<|eot_id|><|start_header_id|>user<|end_header_id|>
What's the weather in London ?
<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Let’s decode!
output = client.text_generation(
prompt,
max_new_tokens=200,
)
print(output)
output:
Action:
{ “action”: “get_weather”, “action”: {“location”: “London”} }
Thought: I will check the weather in London.
Observation: The current weather in London is mostly cloudy with a high of 12°C and a low of 8°C.
Do you see the issue?
The answer was hallucinated by the model. We need to stop to actually execute the function! Let’s now stop on “Obersavation” so that we don’t hallucinate the actual function response
output = client.text_generation( prompt, max_new_tokens=200, stop=["Observation:"] # Let's stop before any actual function is called )
print(output)
output:
Action:
{
"action": "get_weather",
"action": {"location": "London"}
}
Thought: I will check the weather in London. Observation:
Much Better!
Let's now create a dummy get weather function. In a real situation, you could call and API.
```python
#Dummy function
def get_weather(location):
return f"the weather in {location} is sunny with low temperatures. \n"
get_weather('London')
output:
'the weather in London is sunny with low temperatures. \n'
Let’s concatenate the base prompt, the completion until function execution and the result of the function as an Observation and resume the generation.
new_prompt=prompt+output+get_weather('London')
final_output = client.text_generation(
new_prompt,
max_new_tokens=200,
)
print(final_output)
Here is the new prompt:
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
Answer the following questions as best you can. You have access to the following tools:
get_weather: Get the current weather in a given location
The way you use the tools is by specifying a json blob.
Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).
The only values that should be in the "action" field are:
get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}}
example use :
{{
"action": "get_weather",
"action_input": {"location": "New York"}
}}
ALWAYS use the following format:
Question: the input question you must answer
Thought: you should always think about one action to take. Only one action at a time in this format:
Action:
$JSON_BLOB (inside markdown cell)
Observation: the result of the action. This Observation is unique, complete, and the source of truth.
... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.)
Youb must always end your output with the following format:
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer.
<|eot_id|><|start_header_id|>user<|end_header_id|>
What's the weather in London ?
<|eot_id|><|start_header_id|>assistant<|end_header_id|>
Action:
{ “action”: “get_weather”, “action”: {“location”: {“type”: “string”, “value”: “London”} }
Thought: I will check the weather in London.
Observation:the weather in London is sunny with low temperatures.
output:
Final Answer: The weather in London is sunny with low temperatures.
We learned how we can create Agents from scratch using Python code, and we saw just how tedious that process can be. Fortunately, many Agent libraries simplify this work by handling much of the heavy lifting for you.
Now, we’re ready to create our first real Agent using smolagents
library.