-
Notifications
You must be signed in to change notification settings - Fork 82
feat: Add Anthropic Support #395
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ea92227
manual
par4m cfb4bb4
add json5 - fallback
par4m 67bbd48
Merge branch 'cocoindex-io:main' into feat-anthropic-dataflow
par4m c9f06dd
Merge branch 'cocoindex-io:main' into feat-anthropic-dataflow
par4m af19eaf
modify docs and example
par4m ef523b0
refactor: error handling and parsing
par4m File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -106,3 +106,4 @@ bytes = "1.10.1" | |
rand = "0.9.0" | ||
indoc = "2.0.6" | ||
owo-colors = "4.2.0" | ||
json5 = "0.4.1" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
use async_trait::async_trait; | ||
use crate::llm::{LlmGenerationClient, LlmSpec, LlmGenerateRequest, LlmGenerateResponse, ToJsonSchemaOptions, OutputFormat}; | ||
use anyhow::{Result, bail, Context}; | ||
use serde_json::Value; | ||
use json5; | ||
|
||
use crate::api_bail; | ||
use urlencoding::encode; | ||
|
||
pub struct Client { | ||
model: String, | ||
api_key: String, | ||
client: reqwest::Client, | ||
} | ||
|
||
impl Client { | ||
pub async fn new(spec: LlmSpec) -> Result<Self> { | ||
let api_key = match std::env::var("ANTHROPIC_API_KEY") { | ||
Ok(val) => val, | ||
Err(_) => api_bail!("ANTHROPIC_API_KEY environment variable must be set"), | ||
}; | ||
Ok(Self { | ||
model: spec.model, | ||
api_key, | ||
client: reqwest::Client::new(), | ||
}) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl LlmGenerationClient for Client { | ||
async fn generate<'req>( | ||
&self, | ||
request: LlmGenerateRequest<'req>, | ||
) -> Result<LlmGenerateResponse> { | ||
let messages = vec![serde_json::json!({ | ||
"role": "user", | ||
"content": request.user_prompt | ||
})]; | ||
|
||
let mut payload = serde_json::json!({ | ||
"model": self.model, | ||
"messages": messages, | ||
"max_tokens": 4096 | ||
}); | ||
|
||
// Add system prompt as top-level field if present (required) | ||
if let Some(system) = request.system_prompt { | ||
payload["system"] = serde_json::json!(system); | ||
} | ||
|
||
let OutputFormat::JsonSchema { schema, .. } = request.output_format.as_ref().expect("Anthropic client expects OutputFormat::JsonSchema for all requests"); | ||
let schema_json = serde_json::to_value(schema)?; | ||
payload["tools"] = serde_json::json!([ | ||
{ "type": "custom", "name": "extraction", "input_schema": schema_json } | ||
badmonster0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
]); | ||
|
||
let url = "https://api.anthropic.com/v1/messages"; | ||
|
||
let encoded_api_key = encode(&self.api_key); | ||
|
||
let resp = self.client | ||
.post(url) | ||
.header("x-api-key", encoded_api_key.as_ref()) | ||
.header("anthropic-version", "2023-06-01") | ||
.json(&payload) | ||
.send() | ||
.await | ||
.context("HTTP error")?; | ||
let resp_json: Value = resp.json().await.context("Invalid JSON")?; | ||
if let Some(error) = resp_json.get("error") { | ||
bail!("Anthropic API error: {:?}", error); | ||
} | ||
|
||
// Debug print full response | ||
// println!("Anthropic API full response: {resp_json:?}"); | ||
|
||
let resp_content = &resp_json["content"]; | ||
let tool_name = "extraction"; | ||
let mut extracted_json: Option<Value> = None; | ||
if let Some(array) = resp_content.as_array() { | ||
for item in array { | ||
if item.get("type") == Some(&Value::String("tool_use".to_string())) | ||
&& item.get("name") == Some(&Value::String(tool_name.to_string())) | ||
{ | ||
if let Some(input) = item.get("input") { | ||
extracted_json = Some(input.clone()); | ||
break; | ||
} | ||
} | ||
} | ||
} | ||
let text = if let Some(json) = extracted_json { | ||
// Try strict JSON serialization first | ||
serde_json::to_string(&json)? | ||
badmonster0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} else { | ||
// Fallback: try text if no tool output found | ||
match &resp_json["content"][0]["text"] { | ||
Value::String(s) => { | ||
// Try strict JSON parsing first | ||
match serde_json::from_str::<serde_json::Value>(s) { | ||
Ok(_) => s.clone(), | ||
badmonster0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Err(e) => { | ||
// Try permissive json5 parsing as fallback | ||
match json5::from_str::<serde_json::Value>(s) { | ||
Ok(_) => { | ||
println!("[Anthropic] Used permissive JSON5 parser for output"); | ||
s.clone() | ||
badmonster0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
Err(e2) => return Err(anyhow::anyhow!(format!("No structured tool output or text found in response, and permissive JSON5 parsing also failed: {e}; {e2}"))) | ||
} | ||
} | ||
} | ||
}, | ||
_ => return Err(anyhow::anyhow!("No structured tool output or text found in response")), | ||
} | ||
}; | ||
|
||
Ok(LlmGenerateResponse { | ||
text, | ||
}) | ||
} | ||
|
||
fn json_schema_options(&self) -> ToJsonSchemaOptions { | ||
ToJsonSchemaOptions { | ||
fields_always_required: false, | ||
supports_format: false, | ||
extract_descriptions: false, | ||
top_level_must_be_object: true, | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.