|
import re
|
|
from typing import List, Optional
|
|
from pydantic import BaseModel
|
|
from schemas import OpenAIChatMessage
|
|
import os
|
|
import requests
|
|
import json
|
|
|
|
from utils.pipelines.main import (
|
|
get_last_user_message,
|
|
add_or_update_system_message,
|
|
get_tools_specs,
|
|
)
|
|
|
|
|
|
class Pipeline:
|
|
class Valves(BaseModel):
|
|
|
|
|
|
pipelines: List[str] = []
|
|
|
|
|
|
|
|
|
|
priority: int = 0
|
|
|
|
|
|
OPENAI_API_BASE_URL: str
|
|
OPENAI_API_KEY: str
|
|
TASK_MODEL: str
|
|
TEMPLATE: str
|
|
|
|
def __init__(self):
|
|
|
|
|
|
self.type = "filter"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
self.name = "Function Calling Blueprint"
|
|
|
|
|
|
self.valves = self.Valves(
|
|
**{
|
|
"pipelines": ["*"],
|
|
"OPENAI_API_BASE_URL": os.getenv(
|
|
"OPENAI_API_BASE_URL", "https://api.openai.com/v1"
|
|
),
|
|
"OPENAI_API_KEY": os.getenv("OPENAI_API_KEY", "YOUR_OPENAI_API_KEY"),
|
|
"TASK_MODEL": os.getenv("TASK_MODEL", "gpt-3.5-turbo"),
|
|
"TEMPLATE": """Use the following context as your learned knowledge, inside <context></context> XML tags.
|
|
<context>
|
|
{{CONTEXT}}
|
|
</context>
|
|
|
|
When answer to user:
|
|
- If you don't know, just say that you don't know.
|
|
- If you don't know when you are not sure, ask for clarification.
|
|
Avoid mentioning that you obtained the information from the context.
|
|
And answer according to the language of the user's question.""",
|
|
}
|
|
)
|
|
|
|
async def on_startup(self):
|
|
|
|
print(f"on_startup:{__name__}")
|
|
pass
|
|
|
|
async def on_shutdown(self):
|
|
|
|
print(f"on_shutdown:{__name__}")
|
|
pass
|
|
|
|
async def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
|
|
|
|
if body.get("title", False):
|
|
return body
|
|
|
|
print(f"pipe:{__name__}")
|
|
print(user)
|
|
|
|
|
|
user_message = get_last_user_message(body["messages"])
|
|
|
|
|
|
tools_specs = get_tools_specs(self.tools)
|
|
|
|
fc_system_prompt = (
|
|
f"Tools: {json.dumps(tools_specs, indent=2)}"
|
|
+ """
|
|
If a function tool doesn't match the query, return an empty string. Else, pick a function tool, fill in the parameters from the function tool's schema, and return it in the format { "name": "functionName", "parameters": { "key": "value" } }. Only pick a function if the user asks. Only return the object.
|
|
Do not return any other text.
|
|
Ensure that the model returns the correct function format regardless of the user's language.
|
|
"""
|
|
)
|
|
|
|
r = None
|
|
try:
|
|
|
|
r = requests.post(
|
|
url=f"{self.valves.OPENAI_API_BASE_URL}/chat/completions",
|
|
json={
|
|
"model": self.valves.TASK_MODEL,
|
|
"messages": [
|
|
{
|
|
"role": "system",
|
|
"content": fc_system_prompt,
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": "History:\n"
|
|
+ "\n".join(
|
|
[
|
|
f"{message['role']}: {message['content']}"
|
|
for message in body["messages"][::-1][:4]
|
|
]
|
|
)
|
|
+ f"Query: {user_message}",
|
|
},
|
|
],
|
|
|
|
|
|
},
|
|
headers={
|
|
"Authorization": f"Bearer {self.valves.OPENAI_API_KEY}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
stream=False,
|
|
)
|
|
r.raise_for_status()
|
|
|
|
response = r.json()
|
|
content = response["choices"][0]["message"]["content"]
|
|
|
|
|
|
if content != "":
|
|
print(content)
|
|
content = re.sub(r"```json", "", content)
|
|
content = re.sub(r"```", "", content)
|
|
result = json.loads(content)
|
|
|
|
|
|
|
|
if "name" in result:
|
|
function = getattr(self.tools, result["name"])
|
|
function_result = None
|
|
try:
|
|
function_result = function(**result["parameters"])
|
|
except Exception as e:
|
|
print(e)
|
|
|
|
|
|
if function_result:
|
|
system_prompt = self.valves.TEMPLATE.replace(
|
|
"{{CONTEXT}}", function_result
|
|
)
|
|
|
|
|
|
messages = add_or_update_system_message(
|
|
system_prompt, body["messages"]
|
|
)
|
|
|
|
|
|
return {**body, "messages": messages}
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
if r:
|
|
try:
|
|
print(r.json())
|
|
except:
|
|
pass
|
|
|
|
return body
|
|
|