Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use latest PMAT (mostly caching stuff) #18

Merged
merged 4 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 0 additions & 100 deletions labs_api/cache.py

This file was deleted.

40 changes: 11 additions & 29 deletions labs_api/insights/insights.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from datetime import timedelta

import fastapi
from langchain.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
Expand All @@ -9,44 +11,22 @@
OmenMarket,
OmenSubgraphHandler,
)
from prediction_market_agent_tooling.tools.caches.db_cache import db_cache
from prediction_market_agent_tooling.tools.langfuse_ import (
get_langfuse_langchain_config,
observe,
)
from prediction_market_agent_tooling.tools.tavily_storage.tavily_models import (
TavilyResponse,
TavilyStorage,
)
from prediction_market_agent_tooling.tools.tavily_storage.tavily_storage import (
TavilyStorage,
tavily_search,
)
from prediction_market_agent_tooling.tools.tavily.tavily_models import TavilyResponse
from prediction_market_agent_tooling.tools.tavily.tavily_search import tavily_search
from prediction_market_agent_tooling.tools.utils import (
LLM_SUPER_LOW_TEMPERATURE,
utcnow,
)

from labs_api.insights.insights_cache import (
MarketInsightsResponse,
MarketInsightsResponseCache,
)


# Don't observe the cached version, as it will always return the same thing that's already been observed.
def market_insights_cached(
market_id: HexAddress, cache: MarketInsightsResponseCache
) -> MarketInsightsResponse:
"""Returns `market_insights`, but cached daily."""
if (cached := cache.find(market_id)) is not None:
return cached

else:
new = market_insights(market_id)
if new.has_insights:
cache.save(new)
return new
from labs_api.insights.insights_models import MarketInsightsResponse


@db_cache(max_age=timedelta(days=3))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought that in APIs, it makes sense to observe only the first call -- no benefit in observing every call from potentially many many users on frontend. That's why the db_cache decorator is above observe decorator.

@observe()
def market_insights(market_id: HexAddress) -> MarketInsightsResponse:
"""Returns market insights for a given market on Omen."""
Expand All @@ -56,17 +36,19 @@ def market_insights(market_id: HexAddress) -> MarketInsightsResponse:
raise fastapi.HTTPException(
status_code=404, detail=f"Market with id `{market_id}` not found."
)
except Exception as e:
logger.error(f"Failed to fetch market for `{market_id}`: {e}")
raise fastapi.HTTPException(status_code=500)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little simplification thanks to this -- on unhandled errors, APIs usually raise 500 instead of catching it and returning a dummy response.

try:
tavily_response = tavily_search(
market.question_title,
search_depth="basic",
include_answer=True,
max_results=5,
tavily_storage=TavilyStorage("market_insights"),
)
except Exception as e:
logger.error(f"Failed to get tavily_response for market `{market_id}`: {e}")
tavily_response = None
raise fastapi.HTTPException(status_code=500)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to inform the user that the market wasn't found? So probably raise a 404 (or any 4xx)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but that is already handled above:

Screenshot by Dropbox Capture

These 500 codes should be raised only if there are unseemed errors/bugs.

try:
summary = (
tavily_response_to_summary(market, tavily_response)
Expand Down
61 changes: 0 additions & 61 deletions labs_api/insights/insights_cache.py

This file was deleted.

40 changes: 40 additions & 0 deletions labs_api/insights/insights_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from prediction_market_agent_tooling.gtypes import HexAddress
from prediction_market_agent_tooling.tools.datetime_utc import DatetimeUTC
from prediction_market_agent_tooling.tools.tavily.tavily_models import (
TavilyResponse,
TavilyResult,
)
from pydantic import BaseModel


class MarketInsightResult(BaseModel):
url: str
title: str

@staticmethod
def from_tavily_result(tavily_result: TavilyResult) -> "MarketInsightResult":
return MarketInsightResult(url=tavily_result.url, title=tavily_result.title)


class MarketInsightsResponse(BaseModel):
market_id: HexAddress
created_at: DatetimeUTC
summary: str | None
results: list[MarketInsightResult]

@staticmethod
def from_tavily_response(
market_id: HexAddress,
created_at: DatetimeUTC,
summary: str | None,
tavily_response: TavilyResponse,
) -> "MarketInsightsResponse":
return MarketInsightsResponse(
market_id=market_id,
created_at=created_at,
summary=summary,
results=[
MarketInsightResult.from_tavily_result(result)
for result in tavily_response.results
],
)
38 changes: 12 additions & 26 deletions labs_api/invalid/invalid.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,15 @@
HexAddress,
OmenSubgraphHandler,
)
from prediction_market_agent_tooling.tools.caches.db_cache import db_cache
from prediction_market_agent_tooling.tools.is_invalid import is_invalid
from prediction_market_agent_tooling.tools.langfuse_ import observe
from prediction_market_agent_tooling.tools.utils import utcnow

from labs_api.invalid.invalid_cache import (
MarketInvalidResponse,
MarketInvalidResponseCache,
)


# Don't observe the cached version, as it will always return the same thing that's already been observed.
def market_invalid_cached(
market_id: HexAddress, cache: MarketInvalidResponseCache
) -> MarketInvalidResponse:
"""Returns `market_invalid`, but cached daily."""
if (cached := cache.find(market_id)) is not None:
return cached

else:
new = market_invalid(market_id)
if new.has_invalid:
cache.save(new)
return new
from labs_api.invalid.invalid_models import MarketInvalidResponse


@db_cache
@observe()
def market_invalid(market_id: HexAddress) -> MarketInvalidResponse:
"""Returns market invalid for a given market on Omen."""
Expand All @@ -39,13 +23,15 @@ def market_invalid(market_id: HexAddress) -> MarketInvalidResponse:
raise fastapi.HTTPException(
status_code=404, detail=f"Market with id `{market_id}` not found."
)
except Exception as e:
logger.error(f"Failed to fetch market for `{market_id}`: {e}")
raise fastapi.HTTPException(status_code=500)
try:
invalid = is_invalid(market.question_title)
return MarketInvalidResponse(
market_id=market_id,
created_at=utcnow(),
invalid=is_invalid(market.question_title),
)
except Exception as e:
logger.error(f"Failed to get is_invalid for market `{market_id}`: {e}")
invalid = None
return MarketInvalidResponse(
market_id=market_id,
created_at=utcnow(),
invalid=invalid,
)
raise fastapi.HTTPException(status_code=500)
20 changes: 0 additions & 20 deletions labs_api/invalid/invalid_cache.py

This file was deleted.

11 changes: 11 additions & 0 deletions labs_api/invalid/invalid_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from prediction_market_agent_tooling.markets.omen.omen_subgraph_handler import (
HexAddress,
)
from prediction_market_agent_tooling.tools.datetime_utc import DatetimeUTC
from pydantic import BaseModel


class MarketInvalidResponse(BaseModel):
market_id: HexAddress
created_at: DatetimeUTC
invalid: bool
Loading
Loading