baconnier commited on
Commit
4282819
·
verified ·
1 Parent(s): 8e8121c

Update art_explorer.py

Browse files
Files changed (1) hide show
  1. art_explorer.py +35 -44
art_explorer.py CHANGED
@@ -1,19 +1,27 @@
1
  from typing import Dict, Any, List, Optional
2
  from openai import OpenAI
3
  import json
4
- from pydantic import BaseModel
 
5
 
6
  class ExplorationNode(BaseModel):
7
- title: str
8
- description: str
9
- connections: List[str]
10
- depth: int
 
 
 
11
 
12
  class ExplorationPath(BaseModel):
13
  nodes: List[ExplorationNode]
14
  query: str
15
  domain: Optional[str] = None
16
 
 
 
 
 
17
  class ExplorationPathGenerator:
18
  def __init__(self, api_key: str):
19
  self.client = OpenAI(
@@ -23,62 +31,44 @@ class ExplorationPathGenerator:
23
 
24
  def generate_exploration_path(
25
  self,
26
- query: str, # Changed from user_query to query to match app.py
27
  selected_path: List[Dict[str, Any]] = None,
28
  exploration_parameters: Dict[str, Any] = None
29
  ) -> Dict[str, Any]:
30
- """
31
- Generate an exploration path based on the query and parameters
32
-
33
- Args:
34
- query: The user's exploration query
35
- selected_path: Previously selected exploration path nodes
36
- exploration_parameters: Additional parameters for exploration
37
-
38
- Returns:
39
- Dict containing the exploration path and metadata
40
- """
41
  try:
42
- # Set defaults
43
  selected_path = selected_path or []
44
  exploration_parameters = exploration_parameters or {}
45
 
46
- # Extract parameters
47
- depth = exploration_parameters.get("depth", 5)
48
- domain = exploration_parameters.get("domain")
49
-
50
- # Prepare system prompt
51
- system_prompt = """You are an expert art historian assistant. Generate structured exploration paths
52
- that help users discover connections and insights in art history. Format your response as a JSON object
53
- with 'nodes' containing exploration points."""
54
-
55
- # Prepare user message
56
- user_message = {
57
- "query": query,
58
- "depth": depth,
59
- "domain": domain,
60
- "previous_explorations": selected_path
61
- }
62
 
63
- # Make API call
64
  response = self.client.chat.completions.create(
65
  model="mixtral-8x7b-32768",
66
  messages=[
67
- {"role": "system", "content": system_prompt},
68
- {"role": "user", "content": json.dumps(user_message)}
69
  ],
70
  temperature=0.7,
71
  max_tokens=2000
72
  )
73
 
74
- # Parse and validate response
75
- result = json.loads(response.choices[0].message.content)
76
-
77
- # Validate with Pydantic
 
 
 
 
78
  exploration_path = ExplorationPath(
79
- nodes=[ExplorationNode(**node) for node in result["nodes"]],
80
  query=query,
81
- domain=domain
82
  )
83
 
84
  return exploration_path.model_dump()
@@ -88,5 +78,6 @@ class ExplorationPathGenerator:
88
  return {
89
  "error": str(e),
90
  "status": "failed",
91
- "message": "Failed to generate exploration path"
 
92
  }
 
1
  from typing import Dict, Any, List, Optional
2
  from openai import OpenAI
3
  import json
4
+ from pydantic import BaseModel, Field
5
+ from prompts import SYSTEM_PROMPT, format_exploration_prompt, DEFAULT_RESPONSE
6
 
7
  class ExplorationNode(BaseModel):
8
+ id: Optional[str] = None
9
+ node_id: Optional[str] = None
10
+ title: Optional[str] = Field(None, alias='content')
11
+ description: str = ""
12
+ connections: List[Dict[str, Any]] = Field(default_factory=list)
13
+ depth: Optional[int] = 0
14
+ content: Optional[str] = None
15
 
16
  class ExplorationPath(BaseModel):
17
  nodes: List[ExplorationNode]
18
  query: str
19
  domain: Optional[str] = None
20
 
21
+ class Config:
22
+ populate_by_name = True
23
+ arbitrary_types_allowed = True
24
+
25
  class ExplorationPathGenerator:
26
  def __init__(self, api_key: str):
27
  self.client = OpenAI(
 
31
 
32
  def generate_exploration_path(
33
  self,
34
+ query: str,
35
  selected_path: List[Dict[str, Any]] = None,
36
  exploration_parameters: Dict[str, Any] = None
37
  ) -> Dict[str, Any]:
38
+ """Generate an exploration path based on the query and parameters"""
 
 
 
 
 
 
 
 
 
 
39
  try:
 
40
  selected_path = selected_path or []
41
  exploration_parameters = exploration_parameters or {}
42
 
43
+ # Format the exploration prompt using the helper function
44
+ formatted_prompt = format_exploration_prompt(
45
+ user_query=query,
46
+ selected_path=selected_path,
47
+ exploration_parameters=exploration_parameters
48
+ )
 
 
 
 
 
 
 
 
 
 
49
 
 
50
  response = self.client.chat.completions.create(
51
  model="mixtral-8x7b-32768",
52
  messages=[
53
+ {"role": "system", "content": SYSTEM_PROMPT},
54
+ {"role": "user", "content": formatted_prompt}
55
  ],
56
  temperature=0.7,
57
  max_tokens=2000
58
  )
59
 
60
+ # Parse the response
61
+ try:
62
+ result = json.loads(response.choices[0].message.content)
63
+ except json.JSONDecodeError:
64
+ print("Failed to parse API response as JSON, using default response")
65
+ result = DEFAULT_RESPONSE
66
+
67
+ # Convert to ExplorationPath model
68
  exploration_path = ExplorationPath(
69
+ nodes=[ExplorationNode(**node) for node in result.get("nodes", [])],
70
  query=query,
71
+ domain=exploration_parameters.get("domain")
72
  )
73
 
74
  return exploration_path.model_dump()
 
78
  return {
79
  "error": str(e),
80
  "status": "failed",
81
+ "message": "Failed to generate exploration path",
82
+ "default_response": DEFAULT_RESPONSE
83
  }