* OpenAi Template - TextCompletion

* Open AI python templates

* Removed assistant and minor refactoring
This commit is contained in:
Gavin Aguiar 2024-09-10 21:50:12 -05:00 коммит произвёл GitHub
Родитель 54992b3ce2
Коммит 7232a51ab6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
28 изменённых файлов: 1923 добавлений и 0 удалений

Просмотреть файл

@ -182,6 +182,11 @@
<file src="..\..\..\Functions.Templates\Templates-v2\ServiceBusQueueTrigger-Python\*.*" target="templates-v2\ServiceBusQueueTrigger-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\ServiceBusTopicTrigger-Python\*.*" target="templates-v2\ServiceBusTopicTrigger-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\CosmosDbTrigger-Python\*.*" target="templates-v2\CosmosDbTrigger-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\OpenAI-TextCompletion-Python\*.*" target="templates-v2\OpenAI-TextCompletion-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\OpenAI-Chat-Python\*.*" target="templates-v2\OpenAI-Chat-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\OpenAI-Embeddings-Python\*.*" target="templates-v2\OpenAI-Embeddings-Python"/>
<file src="..\..\..\Functions.Templates\Templates-v2\OpenAI-RAG-Python\*.*" target="templates-v2\OpenAI-RAG-Python"/>
<!-- Templates v2 -->
<file src="..\..\..\Functions.Templates\templates\DaprPublishOutputBinding-JavaScript\**" target="templates\DaprPublishOutputBinding-JavaScript" />

Просмотреть файл

@ -98,6 +98,34 @@
"label": "$blobTrigger_connection_label",
"help": "$blobTrigger_connection_help"
},
{
"id": "rag-connection",
"name": "rag-connection",
"value": "string",
"label": "$rag_connection_label",
"help": "$rag_connection_help"
},
{
"id": "rag-collection-name",
"name": "rag-collection-name",
"value": "string",
"label": "$rag_collection_name_label",
"help": "$rag_collection_name_help"
},
{
"id": "embedding-model-name",
"name": "embedding-model-name",
"value": "string",
"label": "$embeddings_model_name_label",
"help": "$embeddings_model_name_help"
},
{
"id": "chat-model-name",
"name": "chat-model-name",
"value": "string",
"label": "$chat_model_name_label",
"help": "$chat_model_name_help"
},
{
"id": "cosmosDBTrigger-connection",
"name": "cosmosDBTrigger-connection",

Просмотреть файл

@ -1720,9 +1720,33 @@ function app.</value>
<data name="blobTrigger_connection_label" xml:space="preserve">
<value>Storage account connection</value>
</data>
<data name="rag_connection_label" xml:space="preserve">
<value>Connection string for RAG storage</value>
</data>
<data name="blobTrigger_connection_help" xml:space="preserve">
<value>The name of the app setting containing your storage account connection string</value>
</data>
<data name="rag_connection_help" xml:space="preserve">
<value>The name of the app setting containing your RAG connection string</value>
</data>
<data name="rag_collection_name_label" xml:space="preserve">
<value>Collection name for RAG function</value>
</data>
<data name="rag_collection_name_help" xml:space="preserve">
<value>The name of the app setting containing the name of the collection</value>
</data>
<data name="embedding_model_name_label" xml:space="preserve">
<value>Embedding model name</value>
</data>
<data name="embedding_model_name_help" xml:space="preserve">
<value>The name of the app setting containing the name of the embedding model</value>
</data>
<data name="chat_model_name_label" xml:space="preserve">
<value>Chat model name</value>
</data>
<data name="chat_model_name_help" xml:space="preserve">
<value>The name of the app setting containing the name of the chat model</value>
</data>
<data name="EventHubTrigger_name" xml:space="preserve">
<value>Event Hub trigger</value>
</data>

Просмотреть файл

@ -0,0 +1,14 @@
# Register this blueprint by adding the following line of code
# to your entry point file.
# app.register_functions($(BLUEPRINT_FILENAME))
#
# Please refer to https://aka.ms/azure-functions-python-blueprints
import azure.functions as func
import logging
from azure.cosmos import CosmosClient
from azure.cosmos import PartitionKey
import os
$(BLUEPRINT_FILENAME) = func.Blueprint()

Просмотреть файл

@ -0,0 +1,121 @@
todo_manager = CreateTodoManager()
@$(BLUEPRINT_FILENAME).function_name("CreateAssistant")
@$(BLUEPRINT_FILENAME).route(route="assistants/{assistantId}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_create_output(arg_name="requests")
def create_assistant(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
assistantId = req.route_params.get("assistantId")
instructions = """
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
"""
create_request = {
"id": assistantId,
"instructions": instructions
}
requests.set(json.dumps(create_request))
response_json = {"assistantId": assistantId}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="$(BLUEPRINT_FILENAME)lication/json")
@$(BLUEPRINT_FILENAME).function_name("PostUserQuery")
@$(BLUEPRINT_FILENAME).route(route="assistants/{assistantId}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_post_input(arg_name="state", id="{assistantId}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")
@$(BLUEPRINT_FILENAME).function_name("GetChatState")
@$(BLUEPRINT_FILENAME).route(route="assistants/{assistantId}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_query_input(arg_name="state", id="{assistantId}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="$(BLUEPRINT_FILENAME)lication/json")
@$(BLUEPRINT_FILENAME).function_name("AddTodo")
@$(BLUEPRINT_FILENAME).assistant_skill_trigger(arg_name="taskDescription", function_description="Create a new todo task")
def add_todo(taskDescription: str) -> None:
if not taskDescription:
raise ValueError("Task description cannot be empty")
logging.info(f"Adding todo: {taskDescription}")
todo_id = str(uuid.uuid4())[0:6]
todo_manager.add_todo(TodoItem(id=todo_id, task=taskDescription))
return
@$(BLUEPRINT_FILENAME).function_name("GetTodos")
@$(BLUEPRINT_FILENAME).assistant_skill_trigger(arg_name="inputIgnored", function_description="Fetch the list of previously created todo tasks")
def get_todos(inputIgnored: str) -> str:
logging.info("Fetching list of todos")
results = todo_manager.get_todos()
return json.dumps(results)
class TodoItem:
def __init__(self, id, task):
self.id = id
self.task = task
class ITodoManager(metaclass=abc.ABCMeta):
@abc.abstractmethod
def add_todo(self, todo: TodoItem):
raise NotImplementedError()
@abc.abstractmethod
def get_todos(self):
raise NotImplementedError()
class InMemoryTodoManager(ITodoManager):
def __init__(self):
self.todos = []
def add_todo(self, todo: TodoItem):
self.todos.append(todo)
def get_todos(self):
return [item.__dict__ for item in self.todos]
class CosmosDbTodoManager(ITodoManager):
def __init__(self, cosmos_client: CosmosClient):
self.cosmos_client = cosmos_client
cosmos_database_name = os.environ.get("CosmosDatabaseName")
cosmos_container_name = os.environ.get("CosmosContainerName")
if not cosmos_database_name or not cosmos_container_name:
raise ValueError("CosmosDatabaseName and CosmosContainerName must be set as environment variables or in local.settings.json")
self.database = self.cosmos_client.create_database_if_not_exists(cosmos_database_name)
self.container = self.database.create_container_if_not_exists(id=cosmos_container_name, partition_key=PartitionKey(path="/id"))
def add_todo(self, todo: TodoItem):
logging.info(
f"Adding todo ID = {todo.id} to container '{self.container.id}'.")
self.container.create_item(todo.__dict__)
def get_todos(self):
logging.info(
f"Getting all todos from container '{self.container.id}'.")
results = [item for item in self.container.query_items(
"SELECT * FROM c", enable_cross_partition_query=True)]
logging.info(
f"Found {len(results)} todos in container '{self.container.id}'.")
return results
def CreateTodoManager() -> ITodoManager:
if not os.environ.get("CosmosDbConnectionString"):
return InMemoryTodoManager()
else:
cosmos_client = CosmosClient.from_connection_string(
os.environ["CosmosDbConnectionString"])
return CosmosDbTodoManager(cosmos_client)

Просмотреть файл

@ -0,0 +1,127 @@
import azure.functions as func
import json
app = func.FunctionApp()
todo_manager = CreateTodoManager()
@app.function_name("CreateAssistant")
@app.route(route="assistants/{assistantId}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_create_output(arg_name="requests")
def create_assistant(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
assistantId = req.route_params.get("assistantId")
instructions = """
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
"""
create_request = {
"id": assistantId,
"instructions": instructions
}
requests.set(json.dumps(create_request))
response_json = {"assistantId": assistantId}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="application/json")
@app.function_name("PostUserQuery")
@app.route(route="assistants/{assistantId}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_post_input(arg_name="state", id="{assistantId}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")
@app.function_name("GetChatState")
@app.route(route="assistants/{assistantId}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_query_input(arg_name="state", id="{assistantId}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="application/json")
@app.function_name("AddTodo")
@app.assistant_skill_trigger(arg_name="taskDescription", function_description="Create a new todo task")
def add_todo(taskDescription: str) -> None:
if not taskDescription:
raise ValueError("Task description cannot be empty")
logging.info(f"Adding todo: {taskDescription}")
todo_id = str(uuid.uuid4())[0:6]
todo_manager.add_todo(TodoItem(id=todo_id, task=taskDescription))
return
@app.function_name("GetTodos")
@app.assistant_skill_trigger(arg_name="inputIgnored", function_description="Fetch the list of previously created todo tasks")
def get_todos(inputIgnored: str) -> str:
logging.info("Fetching list of todos")
results = todo_manager.get_todos()
return json.dumps(results)
from azure.cosmos import CosmosClient
from azure.cosmos import PartitionKey
class TodoItem:
def __init__(self, id, task):
self.id = id
self.task = task
class ITodoManager(metaclass=abc.ABCMeta):
@abc.abstractmethod
def add_todo(self, todo: TodoItem):
raise NotImplementedError()
@abc.abstractmethod
def get_todos(self):
raise NotImplementedError()
class InMemoryTodoManager(ITodoManager):
def __init__(self):
self.todos = []
def add_todo(self, todo: TodoItem):
self.todos.append(todo)
def get_todos(self):
return [item.__dict__ for item in self.todos]
class CosmosDbTodoManager(ITodoManager):
def __init__(self, cosmos_client: CosmosClient):
self.cosmos_client = cosmos_client
cosmos_database_name = os.environ.get("CosmosDatabaseName")
cosmos_container_name = os.environ.get("CosmosContainerName")
if not cosmos_database_name or not cosmos_container_name:
raise ValueError("CosmosDatabaseName and CosmosContainerName must be set as environment variables or in local.settings.json")
self.database = self.cosmos_client.create_database_if_not_exists(cosmos_database_name)
self.container = self.database.create_container_if_not_exists(id=cosmos_container_name, partition_key=PartitionKey(path="/id"))
def add_todo(self, todo: TodoItem):
logging.info(
f"Adding todo ID = {todo.id} to container '{self.container.id}'.")
self.container.create_item(todo.__dict__)
def get_todos(self):
logging.info(
f"Getting all todos from container '{self.container.id}'.")
results = [item for item in self.container.query_items(
"SELECT * FROM c", enable_cross_partition_query=True)]
logging.info(
f"Found {len(results)} todos in container '{self.container.id}'.")
return results
def CreateTodoManager() -> ITodoManager:
if not os.environ.get("CosmosDbConnectionString"):
return InMemoryTodoManager()
else:
cosmos_client = CosmosClient.from_connection_string(
os.environ["CosmosDbConnectionString"])
return CosmosDbTodoManager(cosmos_client)

Просмотреть файл

@ -0,0 +1,123 @@
todo_manager = CreateTodoManager()
@app.function_name("CreateAssistant")
@app.route(route="assistants/{assistantId}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_create_output(arg_name="requests")
def create_assistant(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
assistantId = req.route_params.get("assistantId")
instructions = """
Don't make assumptions about what values to plug into functions.
Ask for clarification if a user request is ambiguous.
"""
create_request = {
"id": assistantId,
"instructions": instructions
}
requests.set(json.dumps(create_request))
response_json = {"assistantId": assistantId}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="application/json")
@app.function_name("PostUserQuery")
@app.route(route="assistants/{assistantId}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_post_input(arg_name="state", id="{assistantId}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")
@app.function_name("GetChatState")
@app.route(route="assistants/{assistantId}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_query_input(arg_name="state", id="{assistantId}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="application/json")
@app.function_name("AddTodo")
@app.assistant_skill_trigger(arg_name="taskDescription", function_description="Create a new todo task")
def add_todo(taskDescription: str) -> None:
if not taskDescription:
raise ValueError("Task description cannot be empty")
logging.info(f"Adding todo: {taskDescription}")
todo_id = str(uuid.uuid4())[0:6]
todo_manager.add_todo(TodoItem(id=todo_id, task=taskDescription))
return
@app.function_name("GetTodos")
@app.assistant_skill_trigger(arg_name="inputIgnored", function_description="Fetch the list of previously created todo tasks")
def get_todos(inputIgnored: str) -> str:
logging.info("Fetching list of todos")
results = todo_manager.get_todos()
return json.dumps(results)
from azure.cosmos import CosmosClient
from azure.cosmos import PartitionKey
class TodoItem:
def __init__(self, id, task):
self.id = id
self.task = task
class ITodoManager(metaclass=abc.ABCMeta):
@abc.abstractmethod
def add_todo(self, todo: TodoItem):
raise NotImplementedError()
@abc.abstractmethod
def get_todos(self):
raise NotImplementedError()
class InMemoryTodoManager(ITodoManager):
def __init__(self):
self.todos = []
def add_todo(self, todo: TodoItem):
self.todos.append(todo)
def get_todos(self):
return [item.__dict__ for item in self.todos]
class CosmosDbTodoManager(ITodoManager):
def __init__(self, cosmos_client: CosmosClient):
self.cosmos_client = cosmos_client
cosmos_database_name = os.environ.get("CosmosDatabaseName")
cosmos_container_name = os.environ.get("CosmosContainerName")
if not cosmos_database_name or not cosmos_container_name:
raise ValueError("CosmosDatabaseName and CosmosContainerName must be set as environment variables or in local.settings.json")
self.database = self.cosmos_client.create_database_if_not_exists(cosmos_database_name)
self.container = self.database.create_container_if_not_exists(id=cosmos_container_name, partition_key=PartitionKey(path="/id"))
def add_todo(self, todo: TodoItem):
logging.info(
f"Adding todo ID = {todo.id} to container '{self.container.id}'.")
self.container.create_item(todo.__dict__)
def get_todos(self):
logging.info(
f"Getting all todos from container '{self.container.id}'.")
results = [item for item in self.container.query_items(
"SELECT * FROM c", enable_cross_partition_query=True)]
logging.info(
f"Found {len(results)} todos in container '{self.container.id}'.")
return results
def CreateTodoManager() -> ITodoManager:
if not os.environ.get("CosmosDbConnectionString"):
return InMemoryTodoManager()
else:
cosmos_client = CosmosClient.from_connection_string(
os.environ["CosmosDbConnectionString"])
return CosmosDbTodoManager(cosmos_client)

Просмотреть файл

@ -0,0 +1,207 @@
{
"author": "Gavin Aguiar",
"name": "Assistant Binding",
"description": "Template to add an assistant to your project",
"programmingModel": "v2",
"language": "python",
"jobs": [
{
"name": "Create New Project",
"type": "CreateNewApp",
"inputs": [
{
"assignTo": "$(APP_FILENAME)",
"paramId": "app-fileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionApp",
"writeFile_FunctionApp" ]
},
{
"name": "Add chat function to an existing file",
"type": "AppendToFile",
"inputs": [
{
"assignTo": "$(SELECTED_FILEPATH)",
"paramId": "app-selectedFileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionBody",
"appendFileContent_FunctionApp"
]
},
{
"name": "Create New Blueprint file",
"type": "CreateNewBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-fileName",
"defaultValue": "blueprint.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintFile",
"writeFile_BlueprintFile",
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
},
{
"name": "Add function to the Blueprint",
"type": "AppendToBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-existingFileName",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
}
],
"actions": [
{
"name": "readFileContent_FunctionApp",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_APP_CONTENT)",
"filePath": "function_app.py"
},
{
"name": "writeFile_FunctionApp",
"type": "WriteToFile",
"source": "$(FUNCTION_APP_CONTENT)",
"filePath": "$(APP_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the function app",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_FunctionBody",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_BODY_CONTENT)",
"filePath": "function_body.py"
},
{
"name": "appendFileContent_FunctionApp",
"type": "AppendToFile",
"createIfNotExists": false,
"source": "$(FUNCTION_BODY_CONTENT)",
"filePath": "$(SELECTED_FILEPATH)",
"continueOnError": false,
"errorText": "Unable to create httpTrigger function",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_BlueprintBody",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "blueprint_body.py"
},
{
"name": "readFileContent_BlueprintFile",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_CONTENT)",
"filePath": "blueprint.py"
},
{
"name": "appendFileContent_BlueprintBody",
"type": "AppendToFile",
"source": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the Blueprint",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "writeFile_BlueprintFile",
"type": "WriteToFile",
"source": "$(BLUEPRINT_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create blueprint",
"replaceTokens": true,
"FileExtension": ".py"
}
]
}

Просмотреть файл

@ -0,0 +1,11 @@
# Register this blueprint by adding the following line of code
# to your entry point file.
# app.register_functions($(BLUEPRINT_FILENAME))
#
# Please refer to https://aka.ms/azure-functions-python-blueprints
import azure.functions as func
import logging
$(BLUEPRINT_FILENAME) = func.Blueprint()

Просмотреть файл

@ -0,0 +1,34 @@
@$(BLUEPRINT_FILENAME).function_name("CreateChatBot")
@$(BLUEPRINT_FILENAME).route(route="chats/{chatID}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_create_output(arg_name="requests")
def create_chat_bot(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
chatID = req.route_params.get("chatID")
input_json = req.get_json()
logging.info(
f"Creating chat ${chatID} from input parameters ${json.dumps(input_json)}")
create_request = {
"id": chatID,
"instructions": input_json.get("instructions")
}
requests.set(json.dumps(create_request))
response_json = {"chatId": chatID}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="$(BLUEPRINT_FILENAME)lication/json")
@$(BLUEPRINT_FILENAME).function_name("GetChatState")
@$(BLUEPRINT_FILENAME).route(route="chats/{chatID}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_query_input(arg_name="state", id="{chatID}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="$(BLUEPRINT_FILENAME)lication/json")
@$(BLUEPRINT_FILENAME).function_name("PostUserResponse")
@$(BLUEPRINT_FILENAME).route(route="chats/{chatID}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).assistant_post_input(arg_name="state", id="{chatID}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")

Просмотреть файл

@ -0,0 +1,41 @@
import json
import logging
import azure.functions as func
app = func.FunctionApp()
@app.function_name("CreateChatBot")
@app.route(route="chats/{chatID}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_create_output(arg_name="requests")
def create_chat_bot(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
chatID = req.route_params.get("chatID")
input_json = req.get_json()
logging.info(
f"Creating chat ${chatID} from input parameters ${json.dumps(input_json)}")
create_request = {
"id": chatID,
"instructions": input_json.get("instructions")
}
requests.set(json.dumps(create_request))
response_json = {"chatId": chatID}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="application/json")
@app.function_name("GetChatState")
@app.route(route="chats/{chatID}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_query_input(arg_name="state", id="{chatID}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="application/json")
@app.function_name("PostUserResponse")
@app.route(route="chats/{chatID}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_post_input(arg_name="state", id="{chatID}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")

Просмотреть файл

@ -0,0 +1,34 @@
@app.function_name("CreateChatBot")
@app.route(route="chats/{chatID}", methods=["PUT"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_create_output(arg_name="requests")
def create_chat_bot(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
chatID = req.route_params.get("chatID")
input_json = req.get_json()
logging.info(
f"Creating chat ${chatID} from input parameters ${json.dumps(input_json)}")
create_request = {
"id": chatID,
"instructions": input_json.get("instructions")
}
requests.set(json.dumps(create_request))
response_json = {"chatId": chatID}
return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="application/json")
@app.function_name("GetChatState")
@app.route(route="chats/{chatID}", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_query_input(arg_name="state", id="{chatID}", timestamp_utc="{Query.timestampUTC}")
def get_chat_state(req: func.HttpRequest, state: str) -> func.HttpResponse:
return func.HttpResponse(state, status_code=200, mimetype="application/json")
@app.function_name("PostUserResponse")
@app.route(route="chats/{chatID}", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.assistant_post_input(arg_name="state", id="{chatID}", user_message="{Query.message}", model="$(CHAT_MODEL_NAME)")
def post_user_response(req: func.HttpRequest, state: str) -> func.HttpResponse:
# Parse the JSON string into a dictionary
data = json.loads(state)
# Extract the content of the recentMessage
recent_message_content = data['recentMessages'][0]['content']
return func.HttpResponse(recent_message_content, status_code=200, mimetype="text/plain")

Просмотреть файл

@ -0,0 +1,207 @@
{
"author": "Gavin Aguiar",
"name": "OpenAI Chat Binding",
"description": "Template to add chat function",
"programmingModel": "v2",
"language": "python",
"jobs": [
{
"name": "Create New Project with Chat function",
"type": "CreateNewApp",
"inputs": [
{
"assignTo": "$(APP_FILENAME)",
"paramId": "app-fileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionApp",
"writeFile_FunctionApp" ]
},
{
"name": "Add chat function to an existing file",
"type": "AppendToFile",
"inputs": [
{
"assignTo": "$(SELECTED_FILEPATH)",
"paramId": "app-selectedFileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionBody",
"appendFileContent_FunctionApp"
]
},
{
"name": "Create New Blueprint file",
"type": "CreateNewBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-fileName",
"defaultValue": "blueprint.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintFile",
"writeFile_BlueprintFile",
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
},
{
"name": "Add chat function to the Blueprint",
"type": "AppendToBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-existingFileName",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
}
],
"actions": [
{
"name": "readFileContent_FunctionApp",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_APP_CONTENT)",
"filePath": "function_app.py"
},
{
"name": "writeFile_FunctionApp",
"type": "WriteToFile",
"source": "$(FUNCTION_APP_CONTENT)",
"filePath": "$(APP_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the function app",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_FunctionBody",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_BODY_CONTENT)",
"filePath": "function_body.py"
},
{
"name": "appendFileContent_FunctionApp",
"type": "AppendToFile",
"createIfNotExists": false,
"source": "$(FUNCTION_BODY_CONTENT)",
"filePath": "$(SELECTED_FILEPATH)",
"continueOnError": false,
"errorText": "Unable to create httpTrigger function",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_BlueprintBody",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "blueprint_body.py"
},
{
"name": "readFileContent_BlueprintFile",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_CONTENT)",
"filePath": "blueprint.py"
},
{
"name": "appendFileContent_BlueprintBody",
"type": "AppendToFile",
"source": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the Blueprint",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "writeFile_BlueprintFile",
"type": "WriteToFile",
"source": "$(BLUEPRINT_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create blueprint",
"replaceTokens": true,
"FileExtension": ".py"
}
]
}

Просмотреть файл

@ -0,0 +1,12 @@
# Register this blueprint by adding the following line of code
# to your entry point file.
# app.register_functions($(BLUEPRINT_FILENAME))
#
# Please refer to https://aka.ms/azure-functions-python-blueprints
import azure.functions as func
import logging
import json
$(BLUEPRINT_FILENAME) = func.Blueprint()

Просмотреть файл

@ -0,0 +1,13 @@
@$(BLUEPRINT_FILENAME).function_name("GenerateEmbeddingsHttpRequest")
@$(BLUEPRINT_FILENAME).route(route="$(FUNCTION_NAME_INPUT)", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT)
@$(BLUEPRINT_FILENAME).embeddings_input(arg_name="embeddings", input="{rawText}", input_type="rawText", model="$(EMBEDDING_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, embeddings: str) -> func.HttpResponse:
user_message = req.get_json()
embeddings_json = json.loads(embeddings)
embeddings_request = {
"raw_text": user_message.get("RawText"),
"file_path": user_message.get("FilePath")
}
logging.info(f'Received {embeddings_json.get("count")} embedding(s) for input text '
f'containing {len(embeddings_request.get("raw_text"))} characters.')
return func.HttpResponse(status_code=200)

Просмотреть файл

@ -0,0 +1,20 @@
import json
import logging
import azure.functions as func
app = func.FunctionApp()
@app.route(route="$(FUNCTION_NAME_INPUT)", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.embeddings_input(arg_name="embeddings", input="{rawText}", input_type="rawText", model="$(EMBEDDING_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, embeddings: str) -> func.HttpResponse:
import json
user_message = req.get_json()
embeddings_json = json.loads(embeddings)
embeddings_request = {
"raw_text": user_message.get("RawText"),
"file_path": user_message.get("FilePath")
}
logging.info(f'Received {embeddings_json.get("count")} embedding(s) for input text '
f'containing {len(embeddings_request.get("raw_text"))} characters.')
return func.HttpResponse(status_code=200)

Просмотреть файл

@ -0,0 +1,12 @@
@app.route(route="$(FUNCTION_NAME_INPUT)", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.embeddings_input(arg_name="embeddings", input="{rawText}", input_type="rawText", model="$(EMBEDDING_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, embeddings: str) -> func.HttpResponse:
user_message = req.get_json()
embeddings_json = json.loads(embeddings)
embeddings_request = {
"raw_text": user_message.get("RawText"),
"file_path": user_message.get("FilePath")
}
logging.info(f'Received {embeddings_json.get("count")} embedding(s) for input text '
f'containing {len(embeddings_request.get("raw_text"))} characters.')
return func.HttpResponse(status_code=200)

Просмотреть файл

@ -0,0 +1,230 @@
{
"author": "Gavin Aguiar",
"name": "Open AI Embeddings Binding",
"description": "Template to create an Embeddings binding function",
"programmingModel": "v2",
"language": "python",
"jobs": [
{
"name": "Create New Project with Embeddings function",
"type": "CreateNewApp",
"inputs": [
{
"assignTo": "$(APP_FILENAME)",
"paramId": "app-fileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "generate_embeddings_http_request"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
}
],
"actions": [
"readFileContent_FunctionApp",
"writeFile_FunctionApp" ]
},
{
"name": "Add embeddings binding function to an existing file",
"type": "AppendToFile",
"inputs": [
{
"assignTo": "$(SELECTED_FILEPATH)",
"paramId": "app-selectedFileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"defaultValue": "generate_embeddings_http_request"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
}
],
"actions": [
"readFileContent_FunctionBody",
"appendFileContent_FunctionApp"
]
},
{
"name": "Create New Blueprint file",
"type": "CreateNewBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-fileName",
"defaultValue": "blueprint.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "generate_embeddings_http_request"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
}
],
"actions": [
"readFileContent_BlueprintFile",
"writeFile_BlueprintFile",
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
},
{
"name": "Add embeddings function to the Blueprint",
"type": "AppendToBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-existingFileName",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "generate_embeddings_http_request"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
}
],
"actions": [
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
}
],
"actions": [
{
"name": "readFileContent_FunctionApp",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_APP_CONTENT)",
"filePath": "function_app.py"
},
{
"name": "writeFile_FunctionApp",
"type": "WriteToFile",
"source": "$(FUNCTION_APP_CONTENT)",
"filePath": "$(APP_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the function app",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_FunctionBody",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_BODY_CONTENT)",
"filePath": "function_body.py"
},
{
"name": "appendFileContent_FunctionApp",
"type": "AppendToFile",
"createIfNotExists": false,
"source": "$(FUNCTION_BODY_CONTENT)",
"filePath": "$(SELECTED_FILEPATH)",
"continueOnError": false,
"errorText": "Unable to create httpTrigger function",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_BlueprintBody",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "blueprint_body.py"
},
{
"name": "readFileContent_BlueprintFile",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_CONTENT)",
"filePath": "blueprint.py"
},
{
"name": "appendFileContent_BlueprintBody",
"type": "AppendToFile",
"source": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the Blueprint",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "writeFile_BlueprintFile",
"type": "WriteToFile",
"source": "$(BLUEPRINT_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create blueprint",
"replaceTokens": true,
"FileExtension": ".py"
}
]
}

Просмотреть файл

@ -0,0 +1,11 @@
# Register this blueprint by adding the following line of code
# to your entry point file.
# app.register_functions($(BLUEPRINT_FILENAME))
#
# Please refer to https://aka.ms/azure-functions-python-blueprints
import azure.functions as func
import logging
$(BLUEPRINT_FILENAME) = func.Blueprint()

Просмотреть файл

@ -0,0 +1,34 @@
# Add searchProvider to host.json.
# For samples code refer: https://github.com/Azure/azure-functions-openai-extension/tree/main/samples/rag-aisearch
@$(BLUEPRINT_FILENAME).route(route="injest_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).embeddings_store_output(arg_name="requests", input="{url}", input_type="url", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", model="$(EMBEDDING_MODEL_NAME)")
def ingest_file(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
import json
import os
user_message = req.get_json()
if not user_message:
return func.HttpResponse(json.dumps({"message": "No message provided"}), status_code=400, mimetype="application/json")
file_name_with_extension = os.path.basename(user_message["Url"])
title = os.path.splitext(file_name_with_extension)[0]
create_request = {
"title": title
}
requests.set(json.dumps(create_request))
response_json = {
"status": "success",
"title": title
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")
@$(BLUEPRINT_FILENAME).route(route="prompt_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).semantic_search_input(arg_name="result", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", query="{Prompt}", embeddings_model="$(EMBEDDING_MODEL_NAME)", chat_model="$(CHAT_MODEL_NAME)")
def prompt_file(req: func.HttpRequest, result: str) -> func.HttpResponse:
import json
result_json = json.loads(result)
response_json = {
"content": result_json.get("Response"),
"content_type": "text/plain"
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")

Просмотреть файл

@ -0,0 +1,37 @@
import json
import os
import azure.functions as func
app = func.FunctionApp()
@app.route(route="injest_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.embeddings_store_output(arg_name="requests", input="{url}", input_type="url", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", model="$(EMBEDDING_MODEL_NAME)")
def ingest_file(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
import json
user_message = req.get_json()
if not user_message:
return func.HttpResponse(json.dumps({"message": "No message provided"}), status_code=400, mimetype="application/json")
file_name_with_extension = os.path.basename(user_message["Url"])
title = os.path.splitext(file_name_with_extension)[0]
create_request = {
"title": title
}
requests.set(json.dumps(create_request))
response_json = {
"status": "success",
"title": title
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")
@app.route(route="prompt_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.semantic_search_input(arg_name="result", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", query="{Prompt}", embeddings_model="$(EMBEDDING_MODEL_NAME)", chat_model="$(CHAT_MODEL_NAME)")
def prompt_file(req: func.HttpRequest, result: str) -> func.HttpResponse:
import json
result_json = json.loads(result)
response_json = {
"content": result_json.get("Response"),
"content_type": "text/plain"
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")

Просмотреть файл

@ -0,0 +1,33 @@
# Add searchProvider to host.json.
# For samples code refer: https://github.com/Azure/azure-functions-openai-extension/tree/main/samples/rag-aisearch
@app.route(route="injest_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.embeddings_store_output(arg_name="requests", input="{url}", input_type="url", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", model="$(EMBEDDING_MODEL_NAME)")
def ingest_file(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
import json
import os
user_message = req.get_json()
if not user_message:
return func.HttpResponse(json.dumps({"message": "No message provided"}), status_code=400, mimetype="application/json")
file_name_with_extension = os.path.basename(user_message["Url"])
title = os.path.splitext(file_name_with_extension)[0]
create_request = {
"title": title
}
requests.set(json.dumps(create_request))
response_json = {
"status": "success",
"title": title
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")
@app.route(route="prompt_file", methods=["POST"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.semantic_search_input(arg_name="result", connection_name="$(CONNECTION_STRING_INPUT)", collection="$(COLLECTION_NAME)", query="{Prompt}", embeddings_model="$(EMBEDDING_MODEL_NAME)", chat_model="$(CHAT_MODEL_NAME)")
def prompt_file(req: func.HttpRequest, result: str) -> func.HttpResponse:
result_json = json.loads(result)
response_json = {
"content": result_json.get("Response"),
"content_type": "text/plain"
}
return func.HttpResponse(json.dumps(response_json), status_code=200, mimetype="application/json")

Просмотреть файл

@ -0,0 +1,280 @@
{
"author": "Gavin Aguiar",
"name": "OpenAI RAG Binding",
"description": "Template for RAG binding function",
"programmingModel": "v2",
"language": "python",
"jobs": [
{
"name": "Create New Project with RAG Binding function",
"type": "CreateNewApp",
"inputs": [
{
"assignTo": "$(APP_FILENAME)",
"paramId": "app-fileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CONNECTION_STRING_INPUT)",
"paramId": "rag-connection",
"required": true,
"defaultValue": "AzureConnectionString"
},
{
"assignTo": "$(COLLECTION_NAME)",
"paramId": "rag-collection-name",
"required": true,
"defaultValue": "MyCollectionName"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionApp",
"writeFile_FunctionApp" ]
},
{
"name": "Add textcompletion binding function to an existing file",
"type": "AppendToFile",
"inputs": [
{
"assignTo": "$(SELECTED_FILEPATH)",
"paramId": "app-selectedFileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CONNECTION_STRING_INPUT)",
"paramId": "rag-connection",
"required": true,
"defaultValue": "AzureConnectionString"
},
{
"assignTo": "$(COLLECTION_NAME)",
"paramId": "rag-collection-name",
"required": true,
"defaultValue": "MyCollectionName"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionBody",
"appendFileContent_FunctionApp"
]
},
{
"name": "Create New Blueprint file",
"type": "CreateNewBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-fileName",
"defaultValue": "blueprint.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CONNECTION_STRING_INPUT)",
"paramId": "rag-connection",
"required": true,
"defaultValue": "AzureConnectionString"
},
{
"assignTo": "$(COLLECTION_NAME)",
"paramId": "rag-collection-name",
"required": true,
"defaultValue": "MyCollectionName"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintFile",
"writeFile_BlueprintFile",
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
},
{
"name": "Add Textcompletion function to the Blueprint",
"type": "AppendToBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-existingFileName",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CONNECTION_STRING_INPUT)",
"paramId": "rag-connection",
"required": true,
"defaultValue": "AzureConnectionString"
},
{
"assignTo": "$(COLLECTION_NAME)",
"paramId": "rag-collection-name",
"required": true,
"defaultValue": "MyCollectionName"
},
{
"assignTo": "$(EMBEDDING_MODEL_NAME)",
"paramId": "embedding-model-name",
"required": true,
"defaultValue": "text-embedding-ada-002"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
}
],
"actions": [
{
"name": "readFileContent_FunctionApp",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_APP_CONTENT)",
"filePath": "function_app.py"
},
{
"name": "writeFile_FunctionApp",
"type": "WriteToFile",
"source": "$(FUNCTION_APP_CONTENT)",
"filePath": "$(APP_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the function app",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_FunctionBody",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_BODY_CONTENT)",
"filePath": "function_body.py"
},
{
"name": "appendFileContent_FunctionApp",
"type": "AppendToFile",
"createIfNotExists": false,
"source": "$(FUNCTION_BODY_CONTENT)",
"filePath": "$(SELECTED_FILEPATH)",
"continueOnError": false,
"errorText": "Unable to create httpTrigger function",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_BlueprintBody",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "blueprint_body.py"
},
{
"name": "readFileContent_BlueprintFile",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_CONTENT)",
"filePath": "blueprint.py"
},
{
"name": "appendFileContent_BlueprintBody",
"type": "AppendToFile",
"source": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the Blueprint",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "writeFile_BlueprintFile",
"type": "WriteToFile",
"source": "$(BLUEPRINT_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create blueprint",
"replaceTokens": true,
"FileExtension": ".py"
}
]
}

Просмотреть файл

@ -0,0 +1,12 @@
# Register this blueprint by adding the following line of code
# to your entry point file.
# app.register_functions($(BLUEPRINT_FILENAME))
#
# Please refer to https://aka.ms/azure-functions-python-blueprints
import azure.functions as func
import logging
import json
$(BLUEPRINT_FILENAME) = func.Blueprint()

Просмотреть файл

@ -0,0 +1,5 @@
@$(BLUEPRINT_FILENAME).route(route="$(FUNCTION_NAME_INPUT)", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@$(BLUEPRINT_FILENAME).text_completion_input(arg_name="response", prompt="{Prompt}", max_tokens="100", model="$(CHAT_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, response: str) -> func.HttpResponse:
response_json = json.loads(response)
return func.HttpResponse(response_json["content"], status_code=200)

Просмотреть файл

@ -0,0 +1,12 @@
import logging
import azure.functions as func
app = func.FunctionApp()
@app.route(route="$(FUNCTION_NAME_INPUT)", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.text_completion_input(arg_name="response", prompt="{Prompt}", max_tokens="100", model="$(CHAT_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, response: str) -> func.HttpResponse:
response_json = json.loads(response)
return func.HttpResponse(response_json["content"], status_code=200)

Просмотреть файл

@ -0,0 +1,5 @@
@app.route(route="$(FUNCTION_NAME_INPUT)", methods=["GET"], auth_level=func.AuthLevel.$(AUTHLEVEL_INPUT))
@app.text_completion_input(arg_name="response", prompt="{Prompt}", max_tokens="100", model="$(CHAT_MODEL_NAME)")
def $(FUNCTION_NAME_INPUT)(req: func.HttpRequest, response: str) -> func.HttpResponse:
response_json = json.loads(response)
return func.HttpResponse(response_json["content"], status_code=200)

Просмотреть файл

@ -0,0 +1,231 @@
{
"author": "Gavin Aguiar",
"name": "OpenAI TextCompletion Binding",
"description": "Template for TextCompletion binding function",
"programmingModel": "v2",
"language": "python",
"jobs": [
{
"name": "Create New Project with TextCompletion function",
"type": "CreateNewApp",
"inputs": [
{
"assignTo": "$(APP_FILENAME)",
"paramId": "app-fileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "text_completion_function"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionApp",
"writeFile_FunctionApp"
]
},
{
"name": "Add textcompletion binding function to an existing file",
"type": "AppendToFile",
"inputs": [
{
"assignTo": "$(SELECTED_FILEPATH)",
"paramId": "app-selectedFileName",
"defaultValue": "function_app.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"defaultValue": "text_completion_function"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_FunctionBody",
"appendFileContent_FunctionApp"
]
},
{
"name": "Create New Blueprint file",
"type": "CreateNewBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-fileName",
"defaultValue": "blueprint.py",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "text_completion_function"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintFile",
"writeFile_BlueprintFile",
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
},
{
"name": "Add Textcompletion function to the Blueprint",
"type": "AppendToBlueprint",
"inputs": [
{
"assignTo": "$(BLUEPRINT_FILENAME)",
"paramId": "blueprint-existingFileName",
"required": true,
"condition" : {
"name": "ClientId",
"values": [ "VSCode"],
"operator": "IN"
}
},
{
"assignTo": "$(FUNCTION_NAME_INPUT)",
"paramId": "trigger-functionName",
"required": true,
"defaultValue": "text_completion_function"
},
{
"assignTo": "$(AUTHLEVEL_INPUT)",
"paramId": "httpTrigger-authLevel",
"required": true,
"defaultValue": "FUNCTION"
},
{
"assignTo": "$(CHAT_MODEL_NAME)",
"paramId": "chat-model-name",
"required": true,
"defaultValue": "gpt-3.5-turbo"
}
],
"actions": [
"readFileContent_BlueprintBody",
"appendFileContent_BlueprintBody"
]
}
],
"actions": [
{
"name": "readFileContent_FunctionApp",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_APP_CONTENT)",
"filePath": "function_app.py"
},
{
"name": "writeFile_FunctionApp",
"type": "WriteToFile",
"source": "$(FUNCTION_APP_CONTENT)",
"filePath": "$(APP_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the function app",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_FunctionBody",
"type": "GetTemplateFileContent",
"assignTo": "$(FUNCTION_BODY_CONTENT)",
"filePath": "function_body.py"
},
{
"name": "appendFileContent_FunctionApp",
"type": "AppendToFile",
"createIfNotExists": false,
"source": "$(FUNCTION_BODY_CONTENT)",
"filePath": "$(SELECTED_FILEPATH)",
"continueOnError": false,
"errorText": "Unable to create Text Completion function",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "readFileContent_BlueprintBody",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "blueprint_body.py"
},
{
"name": "readFileContent_BlueprintFile",
"type": "GetTemplateFileContent",
"assignTo": "$(BLUEPRINT_CONTENT)",
"filePath": "blueprint.py"
},
{
"name": "appendFileContent_BlueprintBody",
"type": "AppendToFile",
"source": "$(BLUEPRINT_BODY_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create the Blueprint",
"replaceTokens": true,
"FileExtension": ".py"
},
{
"name": "writeFile_BlueprintFile",
"type": "WriteToFile",
"source": "$(BLUEPRINT_CONTENT)",
"filePath": "$(BLUEPRINT_FILENAME)",
"continueOnError": false,
"errorText": "Unable to create blueprint",
"replaceTokens": true,
"FileExtension": ".py"
}
]
}