Skip to content

Commit

Permalink
Add cookbooks
Browse files Browse the repository at this point in the history
  • Loading branch information
ashpreetbedi committed Jan 26, 2024
1 parent 2e0c9c6 commit 6f44620
Show file tree
Hide file tree
Showing 17 changed files with 274 additions and 1 deletion.
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ Please run this script before submitting a pull request.
2. Create a new directory in `phi/vectordb` with the name of the vector database.
3. Implement the `VectorDb` interface in `phi/vectordb/<your_db>/<your_db>.py`.
4. Import your `VectorDb` implementation in `phi/vectordb/<your_db>/__init__.py`.
5. Add a recipe for using your `VectorDb` in `cookbook/<your_db>/<your_db>.py`.
5. Add a recipe for using your `VectorDb` in `cookbook/<your_db>/assistant.py`.
6. Format and validate your code by running `./scripts/format.sh`.
6. Submit a pull request.

## 📚 Resources
Expand Down
Empty file added cookbook/__init__.py
Empty file.
25 changes: 25 additions & 0 deletions cookbook/auto/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## Autonomous Assistant

1. Run pgvector

```shell
phi start cookbook/auto/resources.py -y
```

2. Install libraries

```shell
pip install -U pgvector pypdf psycopg sqlalchemy
```

3. Run RAG Assistant

```shell
python cookbook/auto/auto_assistant.py
```

4. Turn off pgvector

```shell
phi stop cookbook/auto/resources.py -y
```
Empty file added cookbook/auto/__init__.py
Empty file.
20 changes: 20 additions & 0 deletions cookbook/auto/auto_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from phi.assistant import Assistant
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector

from .resources import vector_db

knowledge_base = PDFUrlKnowledgeBase(
urls=["https://www.family-action.org.uk/content/uploads/2019/07/meals-more-recipes.pdf"],
vector_db=PgVector(collection="recipes", db_url=vector_db.get_db_connection_local()),
)
knowledge_base.load(recreate=False)

assistant = Assistant(
knowledge_base=knowledge_base,
use_tools=True,
show_tool_calls=True,
)

assistant.print_response("How do I make chicken tikka salad?")
assistant.print_response("What was my last question?")
13 changes: 13 additions & 0 deletions cookbook/auto/resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from phi.docker.app.postgres import PgVectorDb
from phi.docker.resources import DockerResources

# -*- PgVector running on port 5432:5432
vector_db = PgVectorDb(
pg_user="ai",
pg_password="ai",
pg_database="ai",
debug_mode=True,
)

# -*- DockerResources
dev_docker_resources = DockerResources(apps=[vector_db])
18 changes: 18 additions & 0 deletions cookbook/data_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import json
from phi.assistant.duckdb import DuckDbAssistant

duckdb_assistant = DuckDbAssistant(
semantic_model=json.dumps(
{
"tables": [
{
"name": "movies",
"description": "Contains information about movies from IMDB.",
"path": "https://phidata-public.s3.amazonaws.com/demo_data/IMDB-Movie-Data.csv",
}
]
}
),
)

duckdb_assistant.print_response("What is the average rating of movies? Show me the SQL.")
23 changes: 23 additions & 0 deletions cookbook/movie_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import List
from pydantic import BaseModel, Field
from rich.pretty import pprint
from phi.assistant import Assistant


class MovieScript(BaseModel):
setting: str = Field(..., description="Provide a nice setting for a blockbuster movie.")
ending: str = Field(..., description="Ending of the movie. If not available, provide a happy ending.")
genre: str = Field(
..., description="Genre of the movie. If not available, select action, thriller or romantic comedy."
)
name: str = Field(..., description="Give a name to this movie")
characters: List[str] = Field(..., description="Name of characters for this movie.")
storyline: str = Field(..., description="3 sentence storyline for the movie. Make it exciting!")


movie_assistant = Assistant(
description="You help people write movie ideas.",
output_model=MovieScript,
)

pprint(movie_assistant.run("New York"))
15 changes: 15 additions & 0 deletions cookbook/python_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from phi.assistant.python import PythonAssistant
from phi.file.local.csv import CsvFile

python_assistant = PythonAssistant(
files=[
CsvFile(
path="https://phidata-public.s3.amazonaws.com/demo_data/IMDB-Movie-Data.csv",
description="Contains information about movies from IMDB.",
)
],
pip_install=True,
show_tool_calls=True,
)

python_assistant.print_response("What is the average rating of movies?")
25 changes: 25 additions & 0 deletions cookbook/rag/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## RAG Assistant

1. Run pgvector

```shell
phi start cookbook/rag/resources.py -y
```

2. Install libraries

```shell
pip install -U pgvector pypdf psycopg sqlalchemy
```

3. Run RAG Assistant

```shell
python cookbook/rag/rag_assistant.py
```

4. Turn off pgvector

```shell
phi stop cookbook/rag/resources.py -y
```
Empty file added cookbook/rag/__init__.py
Empty file.
18 changes: 18 additions & 0 deletions cookbook/rag/rag_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from phi.assistant import Assistant
from phi.knowledge.pdf import PDFUrlKnowledgeBase
from phi.vectordb.pgvector import PgVector

from .resources import vector_db

knowledge_base = PDFUrlKnowledgeBase(
urls=["https://www.family-action.org.uk/content/uploads/2019/07/meals-more-recipes.pdf"],
vector_db=PgVector(collection="recipes", db_url=vector_db.get_db_connection_local()),
)
knowledge_base.load(recreate=False)

assistant = Assistant(
knowledge_base=knowledge_base,
add_references_to_prompt=True,
)

assistant.print_response("How do I make chicken tikka salad?")
13 changes: 13 additions & 0 deletions cookbook/rag/resources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from phi.docker.app.postgres import PgVectorDb
from phi.docker.resources import DockerResources

# -*- PgVector running on port 5432:5432
vector_db = PgVectorDb(
pg_user="ai",
pg_password="ai",
pg_database="ai",
debug_mode=True,
)

# -*- DockerResources
dev_docker_resources = DockerResources(apps=[vector_db])
4 changes: 4 additions & 0 deletions cookbook/simple_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from phi.assistant import Assistant

assistant = Assistant(description="You help people with their health and fitness goals.")
assistant.print_response("Share a quick healthy breakfast recipe.")
31 changes: 31 additions & 0 deletions cookbook/story_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from phi.llm.openai import OpenAIChat
from phi.task.llm import LLMTask
from phi.assistant import Assistant
from pydantic import BaseModel, Field


class StoryTheme(BaseModel):
setting: str = Field(
...,
description="This is the context of the story. If not available, provide a random setting.",
)
genre: str = Field(..., description="This is the genre of the story. If not provided, select horror.")


get_story_theme = LLMTask(
system_prompt="Generate a theme for a story.",
output_model=StoryTheme,
show_output=False,
)

write_story = LLMTask(
llm=OpenAIChat(model="gpt-4"),
system_prompt="Write a 2 sentence story for a given theme. It should be less than 30 words.",
)

give_story_a_name = LLMTask(
system_prompt="Give this story a 2 word name. Format output as `Name: {name}`. Don't surround with quotes.",
)

story_assistant = Assistant(tasks=[get_story_theme, write_story, give_story_a_name])
story_assistant.cli_app(user="Theme")
33 changes: 33 additions & 0 deletions cookbook/trending_on_hn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import json
import httpx

from phi.assistant import Assistant


def get_top_hackernews_stories(num_stories: int = 10) -> str:
"""Use this function to get top stories from Hacker News.
Args:
num_stories (int): Number of stories to return. Defaults to 10.
Returns:
str: JSON string of top stories.
"""

# Fetch top story IDs
response = httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json")
story_ids = response.json()

# Fetch story details
stories = []
for story_id in story_ids[:num_stories]:
story_response = httpx.get(f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json")
story = story_response.json()
if "text" in story:
story.pop("text", None)
stories.append(story)
return json.dumps(stories)


assistant = Assistant(tools=[get_top_hackernews_stories], show_tool_calls=True)
assistant.print_response("Summarize the top stories on hackernews?")
34 changes: 34 additions & 0 deletions cookbook/vision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from phi.assistant import Assistant
from phi.llm.openai import OpenAIChat


assistant = Assistant(llm=OpenAIChat(model="gpt-4-vision-preview"))

# Single Image
assistant.print_response(
[
{"type": "text", "text": "What's in this image, describe in 1 sentence"},
{
"type": "image_url",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
]
)

# Multiple Images
assistant.print_response(
[
{
"type": "text",
"text": "Is there any difference between these. Describe them in 1 sentence.",
},
{
"type": "image_url",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
{
"type": "image_url",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
]
)

0 comments on commit 6f44620

Please sign in to comment.