Day 19 – Some Basic R&D

Finally got started on some proper AI R&D today focusing on my journey into the world of Python. It’s clear Python will play a big part in my longer term plans.

Today I started out looking at :

  • Making an API server in Python
  • Using Pydantic for data validation
  • Using Crawl4AI which is a library that indexes websites into markdown files.
  • The basics of PydanticAI for building AI agents

This will form the basis of the first low hanging fruit AI tool that I have in mind.

Beyond that:

  • Another potential warm lead
  • A long conversation about using AI with Amazon fulfillments
  • Got my initial business model pricing and offering to a place I’m happy to start from
  • Setup my appointment calendar (cal is open source!)

Random Notes

Every Virtual Agent is going to need to be able to crawl websites. Luckily we don’t need to reinvent the wheel and can use:

https://crawl4ai.com

Today’s R&D looks at https://ai.pydantic.dev/

PydanticAI is a Python agent framework designed to make it less painful to build production grade applications with Generative AI.

Pydantic Data Validation

PydanticAI is built upon Pydantic – which is a data validation library. Here’s an example:

from datetime import datetime
from pydantic import BaseModel, PositiveInt, ValidationError


class User(BaseModel):
    id: int
    name: str = 'John Doe'
    signup_ts: datetime | None
    tastes: dict[str, PositiveInt]


external_data = {'id': 'not an int', 'tastes': {}}  

try:
    User(**external_data)  
except ValidationError as e:
    print(e.errors())
    """
    [
        {
            'type': 'int_parsing',
            'loc': ('id',),
            'msg': 'Input should be a valid integer, unable to parse string as an integer',
            'input': 'not an int',
            'url': 'https://errors.pydantic.dev/2/v/int_parsing',
        },
        {
            'type': 'missing',
            'loc': ('signup_ts',),
            'msg': 'Field required',
            'input': {'id': 'not an int', 'tastes': {}},
            'url': 'https://errors.pydantic.dev/2/v/missing',
        },
    ]
    """

Having not used it before, looking at the syntax I really liked several things about it:

  1. It’s really easy to set the validation, since you just do it in the class definition
  2. When you attempt to set properties of the object to something that fails the validation, you get all the validation stuff you need nice and simple

Python Crash Course

Creating a virtual environment

python3 -m venv directory_name

This creates, amongst other things, a bin dir, which you source in order to tell your terminal to use this python environment rather than your global systems one

source bin/activate

Make sure VSCode uses the correct one. Cmd + Shift + p … Select Interpreter … and then choose the correct one (you will see your directory_name in there)

Then I wanted to see what it takes to setup a simple web server

pip3 install fastapi uvicorn

Then some basic web server code

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, Pythonic World!"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

@app.post("/items/")
def create_item(name: str, description: str = None):
    return {"name": name, "description": description}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="localhost", port=8000)

You can then use this in a browser at port 8000

http://localhost:8000/items/12?q=hello

After getting confused by Google Clouds console I opted for OpenAIs API and topped up. You can integrate with:

from openai import OpenAI

client = OpenAI(
  api_key="YOUR_API_KEY"
)

completion = client.chat.completions.create(
  model="gpt-4o-mini",
  store=True,
  messages=[
    {"role": "user", "content": "write a haiku about ai"}
  ]
)

print(completion.choices[0].message);

And that will pump out a response. So easy to use.

It’s clear that I am going to need to learn more about python3 in order to make my own advanced virtual agent

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *