Skip to content

Commit d5ee25c

Browse files
committed
Updates:
- Significant imporvement on tool-detection mechanis. Add the ability of re-evaluation. - Add a few shot examples. - Refactor tools handler class. - Update assistant example in cookbook.
1 parent 9b13523 commit d5ee25c

File tree

7 files changed

+5882
-150
lines changed

7 files changed

+5882
-150
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# GroqCall.ai - Lightning-Fast LLM Function Calls
22

33
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1q3is7qynCsx4s7FBznCfTMnokbKWIv1F?usp=sharing)
4-
[![Version](https://img.shields.io/badge/version-0.0.2-blue.svg)](https://github.com/unclecode/groqcall)
4+
[![Version](https://img.shields.io/badge/version-0.0.4-blue.svg)](https://github.com/unclecode/groqcall)
55
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
66

77
GroqCall is a proxy server that enables lightning-fast function calls for Groq's Language Processing Unit (LPU) and other AI providers. It simplifies the creation of AI assistants by offering a wide range of built-in functions hosted on the cloud.

app/libs/tools_handler.py

+223-115
Large diffs are not rendered by default.

app/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,13 @@ async def index(request: Request):
5858
# Add an get endpoint simple return the evrsion of the app
5959
@app.get("/version")
6060
async def version():
61-
return {"version": "0.0.3"}
61+
return {"version": "0.0.4"}
6262

6363

6464
if __name__ == "__main__":
6565
import uvicorn
6666

6767
# uvicorn.run("main:app", host=os.getenv("HOST"), port=int(os.getenv('PORT')), workers=1, reload=True)
6868
uvicorn.run(
69-
"main:app", host=os.getenv("HOST"), port=int(os.getenv("PORT")), workers=1
69+
"main:app", host=os.getenv("HOST"), port=int(os.getenv("PORT")), workers=1, reload=False
7070
)

app/prompts.py

+319-16
Large diffs are not rendered by default.

app/utils.py

+7-11
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,13 @@ def create_logger(logger_name: str, log_path: str = ".logs/access.log", show_on_
3030
return logger
3131

3232

33-
def get_tool_call_response(completion, unresolved_tol_calls, resolved_responses):
33+
def get_tool_call_response(tool_calls_result, unresolved_tol_calls, resolved_responses):
34+
last_completion = tool_calls_result["last_completion"]
3435
tool_response = {
35-
"id": "chatcmpl-" + completion.id,
36+
"id": "chatcmpl-" + last_completion.id if last_completion else None,
3637
"object": "chat.completion",
37-
"created": completion.created,
38-
"model": completion.model,
38+
"created": last_completion.created if last_completion else None,
39+
"model": last_completion.model if last_completion else None,
3940
"choices": [
4041
{
4142
"index": 0,
@@ -49,14 +50,9 @@ def get_tool_call_response(completion, unresolved_tol_calls, resolved_responses)
4950
}
5051
],
5152
"resolved": resolved_responses,
52-
"usage": {
53-
"prompt_tokens": completion.usage.prompt_tokens,
54-
"completion_tokens": completion.usage.completion_tokens,
55-
"total_tokens": completion.usage.total_tokens,
56-
},
57-
"system_fingerprint": completion.system_fingerprint,
53+
"usage": tool_calls_result["usage"],
54+
"system_fingerprint": last_completion.system_fingerprint if last_completion else None,
5855
}
59-
6056
return tool_response
6157

6258
def describe(prompt: str, image_url_or_base64 : str, **kwargs) -> str:

cookbook/ai_assistant_custome_tools.py

+42-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
import os
2+
import os, json
33
from typing import Optional, List
44
from phi.llm.openai.like import OpenAILike
55
from phi.assistant import Assistant
@@ -10,6 +10,8 @@
1010
from phi.tools.email import EmailTools
1111
from phi.utils.log import logger
1212
from phi.tools.email import EmailTools
13+
from phi.knowledge.base import AssistantKnowledge
14+
from phi.knowledge.base import Document
1315
from resources import vector_db
1416
from rich.prompt import Prompt
1517
from dotenv import load_dotenv
@@ -18,6 +20,32 @@
1820
# To run this example, first make sure to follow the instructions below:
1921
# 1. Install the phidata: pip install phidata
2022
# 2. Run the following command to start a docker, with pgvector db running: phi start resources.py
23+
# 3. Download the sample of JSON knowledge base from the same folder of this file: cinemax.json
24+
25+
class CinemaSerachDB(Toolkit):
26+
def __init__(
27+
self,
28+
knowledge_base : Optional[AssistantKnowledge] = None,
29+
num_documents: int = None
30+
):
31+
super().__init__(name="get_available_slots")
32+
self.knowledge_base = knowledge_base
33+
self.num_documents = num_documents
34+
self.register(self.get_available_slots)
35+
36+
def get_available_slots(self, movie_slot_query: str ) -> str:
37+
"""Use this function to search the Cinemax database of available movies, show time, and date.
38+
39+
:param query: The query to search the Cinemax database of available movies, show time, and date.
40+
:return: A string containing the response to the query.
41+
"""
42+
relevant_docs: List[Document] = self.knowledge_base.search(query=movie_slot_query, num_documents=self.num_documents)
43+
if len(relevant_docs) == 0:
44+
return None
45+
46+
return json.dumps([doc.to_dict() for doc in relevant_docs], indent=2)
47+
48+
2149

2250
class CinemaTools(Toolkit):
2351
def __init__(
@@ -29,7 +57,6 @@ def __init__(
2957
self.register(self.book_cinema_ticket)
3058

3159
def book_cinema_ticket(self, movie_name: str, date: Optional[str] = None, time: Optional[str] = None, user_email: Optional[str] = None) -> str:
32-
# """Books a cinema ticket for the given movie, date, and time, and sends an email to the user.
3360
"""Use this function ONLY for booking a ticket, when all info is available (movie name, date, time and suer email). Do NOT use this function when user asks for movie details and other things
3461
3562
Args:
@@ -118,12 +145,22 @@ def cinemax_assistant(new: bool = False, user: str = "user"):
118145
run_id=run_id,
119146
user_id="test_user",
120147
llm=my_groq,
121-
knowledge_base=kb,
148+
# knowledge_base=kb, Since I created my own tool CinemaSerachDB
122149
storage=storage,
123150
use_tools=True,
124-
add_chat_history_to_messages=True,
125-
tools=[CinemaTools(EmailTools("YOUR_EMAIL_ADDRESS", "SENDER_NAME", "SENDER_EMAIL", os.environ['email_pass_key'] ))], show_tool_calls=True, markdown=True
151+
tools=[
152+
CinemaSerachDB(knowledge_base=kb, num_documents=5),
153+
CinemaTools(EmailTools("YOUR_EMAIL_ADDRESS", "SENDER_NAME", "SENDER_EMAIL", os.environ['email_pass_key'] ))
154+
], show_tool_calls=True, markdown=True,
155+
add_chat_history_to_messages=True, # Inject history in every prompt
156+
add_datetime_to_instructions=True,
157+
limit_tool_access=True,
158+
extra_instructions="",
159+
output_model= None, # Pydantic
160+
prevent_prompt_injection=True,
161+
add_references_to_prompt=False, # It searches in the kb and add it to every prompt
126162
# add_references_to_prompt=True,
163+
add_to_system_prompt="\n\nRemember:As a Cinemax agent, your responsibilities include: \n\n1. Assisting individuals in locating their preferred movies using the provided database information. \n2. Facilitating ticket booking through the tools at your disposal. \n3. If critical information is missing and the registration system returns an error, generate a polite, humanized version of the error message and request the necessary additional information from users. \n4. When interacting with users, never disclose that you are an AI model unable to perform specific functions or activate certain features. \n5. When users inquire about movie showtimes, available movies, or related details, utilize your tools to access data from the knowledge base, rather than relying on your own knowledge. However, you may provide plot information about specific movies in a concise and succinct manner, ensuring responses are not excessively lengthy. \n6.When engaging in a discussion with users about films and proposing movies based on their preferences and the available options, it would be beneficial to list the available dates and times tailored to the user's interests and conversation history. This approach would simplify the booking process for the user. If the user has already specified a date, it is essential to remember and adhere to it, avoiding the suggestion of alternative dates."
127164
)
128165
assistant.knowledge_base.load(recreate=False)
129166

0 commit comments

Comments
 (0)