rowboat/apps/copilot/copilot.py

86 lines
2.5 KiB
Python
Raw Normal View History

2025-01-13 17:57:37 +05:30
from openai import OpenAI
from flask import Flask, request, jsonify
from pydantic import BaseModel, ValidationError
from typing import List, Dict, Any, Literal
import json
from lib import AgentContext, PromptContext, ToolContext, ChatContext
openai_client = OpenAI()
MODEL_NAME = "gpt-4.1" # OpenAI model name
2025-01-13 17:57:37 +05:30
class UserMessage(BaseModel):
role: Literal["user"]
content: str
class AssistantMessage(BaseModel):
role: Literal["assistant"]
content: str
2025-04-15 00:56:15 +05:30
with open('copilot_edit_agent.md', 'r', encoding='utf-8') as file:
copilot_instructions_edit_agent = file.read()
2025-01-13 17:57:37 +05:30
def get_response(
messages: List[UserMessage | AssistantMessage],
workflow_schema: str,
current_workflow_config: str,
2025-02-20 15:48:17 +05:30
context: AgentContext | PromptContext | ToolContext | ChatContext | None = None,
2025-04-15 00:56:15 +05:30
copilot_instructions: str = copilot_instructions_edit_agent
2025-01-13 17:57:37 +05:30
) -> str:
# if context is provided, create a prompt for the context
if context:
2025-01-22 14:21:22 +05:30
match context:
case AgentContext():
context_prompt = f"""
2025-01-13 17:57:37 +05:30
**NOTE**: The user is currently working on the following agent:
{context.agentName}
"""
2025-01-22 14:21:22 +05:30
case PromptContext():
context_prompt = f"""
2025-01-13 17:57:37 +05:30
**NOTE**: The user is currently working on the following prompt:
{context.promptName}
"""
2025-01-22 14:21:22 +05:30
case ToolContext():
context_prompt = f"""
2025-01-13 17:57:37 +05:30
**NOTE**: The user is currently working on the following tool:
{context.toolName}
"""
2025-01-22 14:21:22 +05:30
case ChatContext():
context_prompt = f"""
2025-01-13 17:57:37 +05:30
**NOTE**: The user has just tested the following chat using the workflow above and has provided feedback / question below this json dump:
```json
{json.dumps(context.messages)}
```
"""
else:
context_prompt = ""
# add the workflow schema to the system prompt
sys_prompt = copilot_instructions.replace("{workflow_schema}", workflow_schema)
# add the current workflow config to the last user message
last_message = messages[-1]
last_message.content = f"""
Context:
The current workflow config is:
```
{current_workflow_config}
```
{context_prompt}
User: {last_message.content}
"""
updated_msgs = [{"role": "system", "content": sys_prompt}] + [
message.model_dump() for message in messages
]
response = openai_client.chat.completions.create(
2025-01-31 12:54:01 +05:30
model=MODEL_NAME,
2025-01-13 17:57:37 +05:30
messages=updated_msgs,
temperature=0.0,
2025-01-13 17:57:37 +05:30
response_format={"type": "json_object"}
)
return response.choices[0].message.content