Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add pt-br assistant with assistant switcher #954

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions cookbook/llms/groq/research/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import streamlit as st
from phi.tools.tavily import TavilyTools

from assistant import get_research_assistant # type: ignore
# Import assistants
from assistant import get_research_assistant as get_research_assistant_en # type: ignore
from assistant_pt_br import get_research_assistant as get_research_assistant_pt_br # type: ignore

st.set_page_config(
page_title="Research Assistant",
Expand All @@ -10,7 +12,6 @@
st.title("Research Assistant powered by Groq")
st.markdown("##### :orange_heart: built using [phidata](https://github.com/phidatahq/phidata)")


def main() -> None:
# Get model
llm_model = st.sidebar.selectbox(
Expand All @@ -24,6 +25,18 @@ def main() -> None:
st.session_state["llm_model"] = llm_model
st.rerun()

# Get assistant language
assistant_language = st.sidebar.selectbox(
"Select Assistant Language", options=["English", "Portuguese"]
)
# Set assistant language in session state
if "assistant_language" not in st.session_state:
st.session_state["assistant_language"] = assistant_language
# Restart the assistant if language has changed
elif st.session_state["assistant_language"] != assistant_language:
st.session_state["assistant_language"] = assistant_language
st.rerun()

# Get topic for report
input_topic = st.text_input(
":female-scientist: Enter a topic",
Expand All @@ -49,7 +62,12 @@ def main() -> None:

if "topic" in st.session_state:
report_topic = st.session_state["topic"]
research_assistant = get_research_assistant(model=llm_model)

if st.session_state["assistant_language"] == "English":
research_assistant = get_research_assistant_en(model=llm_model)
else:
research_assistant = get_research_assistant_pt_br(model=llm_model)

tavily_search_results = None

with st.status("Searching Web", expanded=True) as status:
Expand All @@ -75,5 +93,4 @@ def main() -> None:
if st.sidebar.button("Restart"):
st.rerun()


main()
59 changes: 59 additions & 0 deletions cookbook/llms/groq/research/assistant_pt_br.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from textwrap import dedent
from phi.llm.groq import Groq
from phi.assistant import Assistant


def get_research_assistant(
model: str = "llama3-70b-8192",
debug_mode: bool = True,
) -> Assistant:
"""Get a Groq Research Assistant."""

return Assistant(
name="groq_research_assistant",
llm=Groq(model=model),
description="Você é um editor sênior do NYT com a tarefa de escrever um relatório digno de uma reportagem de capa do NYT, que será entregue amanhã.",
instructions=[
"Você receberá um tópico e resultados de pesquisa de pesquisadores juniores.",
"Leia atentamente os resultados e gere um relatório final digno de uma reportagem de capa do NYT.",
"Torne seu relatório envolvente, informativo e bem estruturado.",
"Seu relatório deve seguir o formato fornecido abaixo.",
"Lembre-se: você está escrevendo para o New York Times, então a qualidade do relatório é importante.",
"O relatório deve ser na lingua {Portugues}, mesmo que a estrutura e a pergunta seja em outro idioma",
],
add_to_system_prompt=dedent("""
<report_format>
## Título

- **Visão geral** Breve introdução ao tema.
- **Importância** Por que este tópico é significativo agora?

### Seção 1
- **Detalhe 1**
- **Detalhe 2**
- **Detalhe 3**

### Seção 2
- **Detalhe 1**
- **Detalhe 2**
- **Detalhe 3**

### Seção 3
- **Detalhe 1**
- **Detalhe 2**
- **Detalhe 3**

## Conclusão
- **Resumo do relatório:** Recapitulação das principais conclusões do relatório.
- **Implicações:** O que essas descobertas significam para o futuro.

## Referências
- [Reference 1](Link to Source)
- [Reference 2](Link to Source)
</report_format>
"""),
# This setting tells the LLM to format messages in markdown
markdown=True,
add_datetime_to_instructions=True,
debug_mode=debug_mode,
)
33 changes: 27 additions & 6 deletions cookbook/llms/groq/video_summary/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import streamlit as st
from phi.tools.youtube_tools import YouTubeTools

from assistant import get_chunk_summarizer, get_video_summarizer # type: ignore
# Import assistants
from assistant import get_chunk_summarizer as get_chunk_summarizer_en, get_video_summarizer as get_video_summarizer_en # type: ignore
from assistant_pt_br import get_chunk_summarizer as get_chunk_summarizer_pt_br, get_video_summarizer as get_video_summarizer_pt_br # type: ignore

st.set_page_config(
page_title="Youtube Video Summaries",
Expand All @@ -10,7 +12,6 @@
st.title("Youtube Video Summaries powered by Groq")
st.markdown("##### :orange_heart: built using [phidata](https://github.com/phidatahq/phidata)")


def main() -> None:
# Get model
llm_model = st.sidebar.selectbox(
Expand All @@ -24,6 +25,18 @@ def main() -> None:
st.session_state["llm_model"] = llm_model
st.rerun()

# Get assistant language
assistant_language = st.sidebar.selectbox(
"Select Assistant Language", options=["English", "Portuguese"]
)
# Set assistant language in session state
if "assistant_language" not in st.session_state:
st.session_state["assistant_language"] = assistant_language
# Restart the assistant if language has changed
elif st.session_state["assistant_language"] != assistant_language:
st.session_state["assistant_language"] = assistant_language
st.rerun()

# Get chunker limit
chunker_limit = st.sidebar.slider(
":heart_on_fire: Words in chunk",
Expand All @@ -36,6 +49,10 @@ def main() -> None:

# Get video url
video_url = st.sidebar.text_input(":video_camera: Video URL")
# Get video language
video_language = st.sidebar.selectbox(
"Select the video language", options=["en", "pt"]
)
# Button to generate report
generate_report = st.sidebar.button("Generate Summary")
if generate_report:
Expand All @@ -53,9 +70,15 @@ def main() -> None:

if "youtube_url" in st.session_state:
_url = st.session_state["youtube_url"]
youtube_tools = YouTubeTools(languages=["en"])
youtube_tools = YouTubeTools(languages=[video_language])
video_captions = None
video_summarizer = get_video_summarizer(model=llm_model)

if assistant_language == "English":
video_summarizer = get_video_summarizer_en(model=llm_model)
chunk_summarizer = get_chunk_summarizer_en(model=llm_model)
else:
video_summarizer = get_video_summarizer_pt_br(model=llm_model)
chunk_summarizer = get_chunk_summarizer_pt_br(model=llm_model)

with st.status("Parsing Video", expanded=False) as status:
with st.container():
Expand Down Expand Up @@ -92,7 +115,6 @@ def main() -> None:
with st.status(f"Summarizing chunk: {i+1}", expanded=False) as status:
chunk_summary = ""
chunk_container = st.empty()
chunk_summarizer = get_chunk_summarizer(model=llm_model)
chunk_info = f"Video data: {video_data}\n\n"
chunk_info += f"{chunks[i]}\n\n"
for delta in chunk_summarizer.run(chunk_info):
Expand Down Expand Up @@ -132,5 +154,4 @@ def main() -> None:
if st.sidebar.button("Restart"):
st.rerun()


main()
94 changes: 94 additions & 0 deletions cookbook/llms/groq/video_summary/assistant_pt_br.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from textwrap import dedent
from phi.llm.groq import Groq
from phi.assistant import Assistant


def get_chunk_summarizer(
model: str = "llama3-70b-8192",
debug_mode: bool = True,
) -> Assistant:
"""Obtenha um assistente de pesquisa Groq."""

return Assistant(
name="groq_youtube_pre_processor",
llm=Groq(model=model),
description="Você é um repórter sênior do NYT Brasil encarregado de resumir um vídeo do YouTube.",
instructions=[
"Você receberá uma transcrição do vídeo do YouTube.",
"Leia atentamente a transcrição e prepare um relatório detalhado com os principais fatos e detalhes.",
"Forneça o máximo de detalhes e fatos possível no resumo.",
"Seu relatório será usado para gerar um relatório final digno do New York Times.",
"Dê títulos relevantes às seções e forneça detalhes/fatos/processos em cada seção.",
"LEMBRE-SE: você está escrevendo para o New York Times, então a qualidade do relatório é importante.",
"Certifique-se de que seu relatório esteja formatado corretamente e siga o <report_format> fornecido abaixo."
"O relatório deve ser na lingua {Portugues}, mesmo que a estrutura e a pergunta seja em outro idioma",
],
add_to_system_prompt=dedent("""
<report_format>
### Visão Geral
{forneça uma visão geral do vídeo}

### Seção 1
{forneça detalhes/fatos/processos nesta seção}

... mais seções conforme necessário...

### Conclusões
{forneça conclusões principais do vídeo}
</report_format>
"""),
# Esta configuração diz ao LLM para formatar mensagens em markdown
markdown=True,
add_datetime_to_instructions=True,
debug_mode=debug_mode,
)


def get_video_summarizer(
model: str = "llama3-70b-8192",
debug_mode: bool = True,
) -> Assistant:
"""Consiga um assistente de pesquisa da Groq."""

return Assistant(
name="groq_video_summarizer",
llm=Groq(model=model),
description="Você é um repórter sênior do NYT Brasil encarregado de escrever um resumo de um vídeo do YouTube.",
instructions=[
"Você receberá:"
" 1. Link do vídeo do YouTube e informações sobre o vídeo."
" 2. Sumários pré-processados de pesquisadores juniores."
"Processe cuidadosamente as informações e pense sobre os conteúdos",
"Em seguida, gere um relatório final digno do New York Times no formato <report_format> fornecido abaixo.",
"Faça seu relatório envolvente, informativo e bem estruturado.",
"Divida o relatório em seções e forneça conclusões importantes no final.",
"Certifique-se de que o título seja um link markdown para o vídeo.",
"Dê títulos relevantes às seções e forneça detalhes/fatos/processos em cada seção."
"LEMBRE-SE: você está escrevendo para o New York Times, então a qualidade do relatório é importante."
],
add_to_system_prompt=dedent("""
<report_format>
## Título do Vídeo com Link
[este é o link markdown para o vídeo]

### Visão Geral
{dê uma breve introdução do vídeo e por que o usuário deveria ler este relatório}
{torne esta seção envolvente e crie um gancho para o leitor}

### Seção 1
{divida o relatório em seções}
{forneça detalhes/fatos/processos nesta seção}

... mais seções conforme necessário...

### Conclusões
{forneça conclusões principais do vídeo}

Relatório gerado em: {Data do Mês, Ano (hh:mm AM/PM)}
</report_format>
"""),
# Esta configuração diz ao LLM para formatar mensagens em markdown
markdown=True,
add_datetime_to_instructions=True,
debug_mode=debug_mode,
)